Monday, 14 January 2013

Perl Notes - File Processing


File Processing

File Handle
Standards: STDIN, STDOUT, STDERR
Custom file handles are by convention all upper-case: FILE, FILE_IN, FILE_OUT
<FILE>
read one line from an input file handle, including the \n
Print to file handle
print FILE $x, "hello", $y; ## write to previously opened FILE
print "Hello there\n"; ## writes to STDOUT by default
Write to an output file handle. The things to write are separated by commas, but the
file-handle is not. File handle defaults to STDOUT
Open for reading
open(IN_FILE, "poem.txt");
Open for writing
open(OUT_FILE, ">poem2.txt");
Standard file processing loop...
while ($line = <IN_FILE>) {
chomp($line); ## remove EOLN
print OUT_FILE $line, "\n";
}
die – error detection – open() returns undef on error
open(F, $fname) || die "Cannot open $fname";

No comments:

Post a Comment