Chris Stinemetz wrote:
Why does this short program only seem to capture the last line of
input in the @array, but when I put the for loop inside the while loop
all lines of input are available in @array.
I thought by declaring the @array outside the while loop would make
all of its contents available once all the lines are read in the while
loop.
#!/usr/bin/perl
use warnings;
use strict;
my @array;
while ( my $line =<DATA> ) {
chomp $line;
@array = split(/\s+/, $line,-1);
You are assigning (=) to the array and every time you assign new values
the old values are replaced so only the last file line is in @array when
the loop ends.
The use of chomp is redundant because the pattern /\s+/ removes newlines
as well.
The use of -1 as the third argument is superfluous in this case
To sum up, your loop would be better as:
while ( <DATA> ) {
@array = split;
}
But if you want to save all the lines and still split them then:
while ( <DATA> ) {
push @array, [ split ];
}
Which will save the fields in an array of arrays.
perldoc perllol
perldoc perldsc
John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction. -- Albert Einstein
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/