First - use strict. That would have caught the obvious error that @arrays and @{$arrays} are not the same thing.

The second thing is that you're looping over the outer array. But, you're building an ArrayOfArrays. So, you'll need an inner for-loop and an outer for-loop. Here's one way to rewrite your script:

use strict; # I'm assuming I'm getting @data from some file. use IO::File; my $fh = IO::File->new('Some_filename') || die "Cannot open 'Some_filename' for reading\n"; my @data = <$fh>; $fh->close; # At this point, I have the entire file in @data. my @array; foreach my $line (@data) { push @array, [ split / /, $line ]; } # There are a number of ways I could've written the above statement. # Two others could be: # # my @array; # push @array, [ split / /, $_ ] for @data; # or # my @array = map { split / /, $_ } @data; # # It's completely up to you what you're most comfortable with. # At this point, we're ready to loop through the file. I'm # going to assume you want to print the second and fourth # elements of each line out. (That corresponds to array \ # indices 1 and 3.) foreach my $line_from_file (@array) { foreach my $value (@{$line_from_file}) { # NOTE: Since I'm using array references, I have to # dereference the value using the -> (arrow) operator. print "2nd: $value->[1] ... 4th: $value->[3]\n"; } }
I hope that helps.

------
We are the carpenters and bricklayers of the Information Age.

Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.


In reply to Re: foreach loop with array of arrays by dragonchild
in thread foreach loop with array of arrays by Lhamo_rin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.