Learning Perl

Learning PerlSearch this book
Previous: 10.3 A Slight Diversion: dieChapter 10
Filehandles and File Tests
Next: 10.5 The -x File Tests
 

10.4 Using Filehandles

Once a filehandle is open for reading, you can read lines from it just as you can read from standard input with STDIN. So, for example, to read lines from the password file:

open (EP,"/etc/passwd");
while (<EP>) {
    chomp;
    print "I saw $_ in the password file!\n";
}

Note that the newly opened filehandle is used inside the angle brackets, just as we have used STDIN previously.

If you have a filehandle open for writing or appending, and if you want to print to it, you must place the filehandle immediately after the print keyword and before the other arguments. No comma should occur between the filehandle and the rest of the arguments:

print LOGFILE "Finished item $n of $max\n";
print STDOUT "hi, world!\n"; # like print "hi, world!\n"

In this case, the message beginning with Finished goes to the LOGFILE filehandle, which presumably was opened earlier in the program. And hi, world still goes to standard output, just as when you didn't specify the filehandle. We say that STDOUT is the default filehandle for the print statement.

Here's a way to copy data from a file specified in $a into a file specified in $b. It illustrates nearly everything we've learned in the last few pages:[3]

open(IN,$a) || die "cannot open $a for reading: $!";
open(OUT,">$b") || die "cannot create $b: $!";
while (<IN>) {      # read a line from file $a into $_
    print OUT $_;   # print that line to file $b
}
close(IN) || die "can't close  $a: $!";
close(OUT) || die "can't close  $b: $!";

[3] Although it's entirely redundant with the File::Copy module.


Previous: 10.3 A Slight Diversion: dieLearning PerlNext: 10.5 The -x File Tests
10.3 A Slight Diversion: dieBook Index10.5 The -x File Tests