Perl I/O
Opening files
open CONFIG, "dino.config"; # open for reading
open CONFIG, "<", "dino.config"; # same thing
open BEDROCK, ">", "fred.txt"; # overwrite
open LOG, ">>", "logfile.log"; # append
Read a file line-by-line
open(FH, $fileName) or die "open $fileName failed: $!";
while (my $line = <FH>){
chomp $line; # get rid of end-of-line
# do something with $line
}
A simpler alternative:
open(FH, $fileName) or die "open $fileName failed: $!";
while (<FH>){
chomp; # acts on the default variable $_
# do something with $_
}
Read a file all at once
open(FH, $fileName) or die "open $fileName failed: $!";
chomp(@lines = <FH>);
# process @lines
Write to a file that's been opened for writing
print LOG "Captain's log, stardate 3.14159\n"; # output goes to LOG
printf STDERR "%d percent complete.\n", $done/$total * 100;
Perl's built-in filehandles
STDIN, STDOUT, STDERR allow your Perl program to act like a standard Unix command.
Use select to choose an alternate default output filehandle:
select LOG;
$| = 1; # don't keep LOG entries sitting in the buffer
select STDOUT;
...
print LOG "This gets written to the LOG at once!\n";
Closing files
close CONFIG; # Perl automatically closes open files at program exit
Remapping STDERR to a log file
open STDERR, ">>", "/var/log/system.log" or die "$!";
Example: updating several files
#!/usr/bin/perl -w
chomp(my $date = `date`);
$^I = ".bak";
while (<>) {
s/^Author:.*/Author: Randal L. Schwartz/;
s/^Phone:.*\n//;
s/^Date:.*/Date: $date/;
print;
}
Setting $^I causes the <> to print the updated lines to the original file name and save the original contents as a backup file.