in reply to How to read each line of a file into a nested array
001 use strict; 002 my @array; 003 open (INFILE, "<filename") or die "could not open file"; 004 foreach (<INFILE>) { 005 chomp; 006 push @array, [m/(\d+)/, $_]; 007 } 008 close INFILE;
Line by line explaination:
Line 1: rule #1 always use strict it will save you hours in the long run.
Line 2: Create a place to put our answers
Line 3: open your data file INFILE is now the file handle for your data file. Relplace "filename" with the name of your file. It is good practice to always check the results of an open open will return a false value if it fails and a true value if it suceeds the right side of the or will never happen if it suceeds but we will die if it fails.
Line 4: The diamond operator <> reads one line from INFILE and sets the value of $_ to that string.
Line 5: chomp the newline off the end of $_
Line 6: Line noise? Let's break it down. push @array, will add whatever comes after the comma to the end of @array, "push" them on to the end. What is it pushing? Well the square brackets [] will turn whatever is inside of them into an anonymous array. This anonymous array will be push onto the end of @array. So Line 6 could be rewritten as
or$_ =~ m/(\d+)/; #set $1 to the first group of digits push @array, [$1, $_];
or even$_ =~ m/(\d+)/; my @subarray = ($1, $_); push @array, [@subarray];
etc., etc., etc. TMTOWTDI$_ =~ m/(\d+)/; my @subarray = ($1, $_); push @array, \@subarray;
Line 7: End of for loop
Line 8: close the file
Anyway,
$array[0][0] will be "1"
$array[0][1] will be "1 2 3 4 5"
$array[1][0] will be "10"
$array[1][1] will be "10 20 30 40 50"
$array[2][0] will be "200"
$array[2][1] will be "200 100 300 2 1"
--
flounder
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: How to read each line of a file into a nested array
by opolat (Novice) on Jun 22, 2002 at 11:22 UTC | |
|
Re: Re: How to read each line of a file into a nested array
by Anonymous Monk on Jun 22, 2002 at 08:30 UTC |