Linux Classes
Share This With a Friend  

Can Perl Manipulate Linux Files?

Dealing with Files

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
(Please feel free to answer questions posted by others!)

mosaddek     (11 Oct 2011, 13:03)
ohh found it; thanks a lot Bob; great place to learn from scratch.
mosaddek     (11 Oct 2011, 13:00)
if (/^#/) { print "MATCH: $_"; }
what the (/^#/) did here? a bit explanation could helped a lot. thanks.

I welcome your comments. However... I am puzzled by many people who say "Please send me the Linux tutorial." This website *is* your Linux Tutorial! Read everything here, learn all you can, ask questions if you like. But don't ask me to send what you already have. :-)

NO SPAM! If you post garbage, it will be deleted, and you will be banned.
Notify me about new comments on this page
Hide my email

Ask Bob Rankin - Free Tech Support

Copyright © by - Privacy Policy
All rights reserved - Redistribution is allowed only with permission.