Re: trying to learn

Abhijit Menon-Sen <[email protected]> Fri, 3 Sep 2004 12:16:51 +0530
Newsgroups gmane.user-groups.linux.delhi.devel
Message-ID <[email protected]>
At 2004-09-03 12:15:25 +0545, [email protected] wrote:
>
> In the for loop I want my new array name to be assigned at runtime
> like @line1, @line2 and so..

Whenever you find yourself wanting to name variables "@line1, @line2 and
so on", step back and ask yourself why you aren't using an array, which
gives you variables "named" $line[1], $line[2], and so on.

> @numbers = <STDIN>;
> 
> @all_lines = split(/\n/, @numbers);

This is wrong.

For starters, split works on strings, not numbers. Your @numbers already
contains what you want to put in @all_lines. But, apart from that, since
you want to operate on each line separately, why not do so directly?

$i = 0;
$total = 0;
@lines = ();

while ( $numbers = <STDIN> ) {
    # $sum = sum of the numbers in $numbers

    $lines[$i++] = $sum;
    $total += $sum;
}

To find the sum of one line, you will need to use split / /.

-- ams