One common operation in Perl is to open a text file and process it line by line. You might
be creating a report or just sifting through the file to find certain strings. This example
opens a file whose name is stored the $file variable and then prints each line that starts
with the pound sign:
open MYFILE, $file or die "Can't open $file: $! \n";
while (<MYFILE>) {
if (/^#/) { print "MATCH: $_"; }
}
A few things may need explaining here. The open command assigns a file handle (in this case, MYFILE) to the file named in the $file variable. You can use any file handle or variable names you like in the open command. If the file cannot be opened for some reason (it doesn't exist, it isn't readable, and so on), then the program will terminate (courtesy of the die command) with a message like this:
Can't open panda.txt: No such file or directory
The special variable $! contains the reason for the failure and was substituted into the error message. If the file is opened successfully, the program continues, and the <MYFILE> construct will return the next line from the file in the $_ variable. (You'll find that a lot of Perl functions use this special $_ variable.) When the end of the file is reached, <MYFILE> will return a null value, causing the loop to terminate.
Previous Lesson: Perl Looping
Next Lesson: Perl Pattern Matching
Comments - most recent first
|
|
||