dusoo has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys, i'm trying to parse simple thing but does not work for me as I thought it might. I would like to put line's array to a hash and later play with it. Problem is that adding array to a hash does not work here. What I'm doing wrong here ?
file's data: 010 011 012 020 021
code: ... my $line_num=1; my $hash; while (<FH>) { chomp $_; my $line = $_; my @array = map { s/^\s+//; # strip leading spaces s/\s+$//; # strip tailing spaces $_ # return the modified string } split '\s+', $line; print $array[0]."\n"; # WORKS print $array[1]."\n"; # WORKS print @array."\n"; # prints number of elements instead of whole array $hash->{$line_num}=@array; # does not works because of previous issue $line_num++; }
Thanks, Dusoo

Replies are listed 'Best First'.
Re: help with split into array
by jwkrahn (Abbot) on Aug 17, 2011 at 08:04 UTC
    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>;
Re: help with split into array
by Anonymous Monk on Aug 17, 2011 at 07:41 UTC

    Recycling my answer from here

    To build a hashe of arrays , you need to store, arrayrefs in the hash, like this

    #!/usr/bin/perl -- use strict; use warnings; my %foo; my @bar; $foo{bar}=\@bar; $foo{BAR}=\@bar; for ( 1 .. 2){ my @arr = "ab$_" .. "ab4"; $foo{$_} = \@arr; } use Data::Dumper; print Dumper( \%foo ); __END__ $VAR1 = { '1' => [ 'ab1', 'ab2', 'ab3', 'ab4' ], 'bar' => [], 'BAR' => $VAR1->{'bar'}, '2' => [ 'ab2', 'ab3', 'ab4' ] };

    See the \ operator takes a reference, to an array (\@array), to a hash (\%hash), to a scalar (\$scalar)

    See Tutorials: References quick reference