in reply to foreach loop with array of arrays
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:
I hope that helps.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"; } }
------
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: foreach loop with array of arrays
by Anonymous Monk on Aug 29, 2014 at 18:56 UTC |