Filehandles and File Tests
- Here's one way to do it:
print "What file? "; chomp($filename = <STDIN>); open(THATFILE, "$filename") || die "cannot open $filename: $!"; while (<THATFILE>) { print "$filename: $_"; # presume $_ ends in \n }
The first two lines prompt for a filename, which is then opened with the filehandle
THATFILE. The contents of the file are read using the filehandle, and printed toSTDOUT. - Here's one way to do it:
print "Input file name: "; chomp($infilename = <STDIN>); print "Output file name: "; chomp($outfilename = <STDIN>); print "Search string: "; chomp($search = <STDIN>); print "Replacement string: "; chomp($replace = <STDIN>); open(IN,$infilename) || die "cannot open $infilename for reading: $!"; ## optional test for overwrite... die "will not overwrite $outfilename" if -e $outfilename; open(OUT,">$outfilename") || die "cannot create $outfilename: $!"; while (<IN>) { # read a line from file IN into $_ s/$search/$replace/g; # change the lines print OUT $_; # print that line to file OUT } close(IN); close(OUT);This program is based on the file-copying program presented earlier in the chapter. New features here include the prompts for the strings, the substitute command in the middle of the
whileloop, and the test for overwriting a file. Note that backreferences in the regular expression do work, but references to memory in the replacement string do not. - Here's one way to do it:
while (<>) { chomp; # eliminate the newline print "$_ is readable\n" if -r; print "$_ is writable\n" if -w; print "$_ is executable\n" if -x; print "$_ does not exist\n" unless -e; }
This
whileloop reads a filename each time through. After discarding the newline, the series of statements tests the file for the various permissions. - Here's one way to do it:
while (<>) { chomp; $age = -M; if ($oldest_age < $age) { $oldest_name = $_; $oldest_age = $age; } } print "The oldest file is $oldest_name ", "and is $oldest_age days old.\n";First, we loop on each filename being read in. The newline is discarded, and then the age (in days) gets computed with the
-Moperator. If the age for this file exceeds the oldest file we've seen so far, we remember the filename and its corresponding age. Initially,$oldest_agewill be zero, so we're counting on there being at least one file that is more than zero days old.The final
printstatement generates the report when we're done.