Полезная информация

Learning Perl on Win32 Systems

Learning Perl on Win32 SystemsSearch this book
Previous: 10.4 A Slight Diversion: dieChapter 10
Filehandles and File Tests
Next: 10.6 The -x File Tests
 

10.5 Using Filehandles

After 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 a text file:

open (FIL,"some_file");
while (<FIL>) {
        chomp;
        print "I saw $_ in some_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";

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 all of the text from a file specified in $a into a file specified in $b. It illustrates nearly everything we've learned in the last few pages:[7]

[7] Although this method is entirely redundant when you consider the File::Copy module.

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:$!";


Previous: 10.4 A Slight Diversion: dieLearning Perl on Win32 SystemsNext: 10.6 The -x File Tests
10.4 A Slight Diversion: dieBook Index10.6 The -x File Tests