|
|
Listing C.24 demonstrates how to read in ('slurp') an entire file into an array with a single Perl command.
Listing C.24 arrayFile1.pl
my($fileName) = "somedata.txt"; my($currentLine) = ""; my($index) = 0; my(@fileContents); open(INPUT, "<$fileName") || die "Cannot open $fileName: $!\n"; (@fileContents) = <INPUT>; foreach $index (0..$#fileContents) { $currentLine = $fileContents[$index]; print "$currentLine"; }
You can invoke the Perl script arrayFile1.pl from the command line as follows,
perl -w arrayFile1.pl
and the output will be as follows:
# this is a comment line Jones:Tom:1000 Smith:Ann:2000 Smith:Bill:3000
This technique is useful when you want to minimize the amount of time that a file is open (for whatever reason). Since the array containing the file contents will be in main memory, you can process the array contents much faster than the line-by-line approach that was used in earlier examples.
|
|