Perl: Read/Write to File

By Xah Lee. Date: . Last updated: .

Here is a example of reading in a file and print it out:

open(f,"<x.pl") or die "error: $!";
while ($line = <f>) {print $line}
close(f) or die "error: $!";
print "am printing myself\n";

The f in the above code is called a “file handle”. It is sometimes capitalized (e.g. open(F,"<x.pl")), and can also be a string instead (e.g. open("f","<x.pl") ).

The < in "<x.pl" means read. To open a file for writing, use >.

The <f> reads in a line from the file handle “f”.

In the line close(f) or die "error: $!";, it essentially means if (not close) then abort with error message. The die is abort, the $! is a predefined variable that holds system errors.

Here is a complete example of reading in a file and writing it to another file.

open(f1,"</Users/john/t1.txt") or die "error opening file f1: $!";
open(f2,">/Users/john/t2.txt") or die "error opening file f2: $!";
while ($line = <f1>) {print f2 $line;}
close(f1) or die "error: $!";
close(f2) or die "error: $!";