chomp $_; my $line = $_; my @array = map { s/^\s+//; # strip leading spaces s/\s+$//; # strip tailing spaces $_ # return the modified string } split '\s+', $line;
You don't need anything this complicated. Just do this:
my @array = split;
print @array."\n"; # prints number of elements instead of whole array
The concatenation operator (.) forces scalar context on its operands and an array in scalar context returns the number of elements in the array. You need to use list context instead:
print @array, "\n";
$hash->{$line_num}=@array; # does not works because of previous issue
Again you are forcing scalar context on the array which evaluates to the number of elements in the array. If you want to store the contents of the array then you have to either store a reference of the array:
$hash->{ $line_num } = \@array;
or copy the array to an anonymous array.
$hash->{ $line_num } = [ @array ];
In other words your while loop could be written more simply as:
while ( <FH> ) { $hash->{ $. } = [ split ]; }
But if you are using the line number as hash keys then you should probably be using an array instead of a hash.
my @data; while ( <FH> ) { push @data, [ split ]; }
Or:
my @data = map [ split ], <FH>;
In reply to Re: help with split into array
by jwkrahn
in thread help with split into array
by dusoo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |