I want each (small) file specified with ARGV read in its own array. If I don’t test $ARGV, <> will slurp all files in a single table. Is there a better/shorter/simpler way of doing it?
# invocation: ./prog.pl *.txt
@table = ();
$current = "";
while (<>)
{
if ($ARGV ne $current)
{
@ar = ();
$current = $ARGV;
if ($current)
{
push @table, \@ar;
}
}
push @ar;
}
Please always
use strictanduse warningsat the top of your programs, and declare variables close to their first point of use usingmy.It is simplest to test end of file on the
ARGVfilehandle to determine when a new file is about to be opened.This code uses a state variable
$eofto record whether the previous file has been completely read to avoid unnecessarily adding a new element to the@tablearray when the end of the@ARGVlist is reached.@Alan Haggai Alavi’s idea of incrementing an index at end of file instead of setting a flag is far better as it avoids the need to explicitly create an empty array at the start of each file.
Here is my take on his solution, but it is completely dependent on Alan’s post and he should gete the credit for it.