Filehandles and File Tests

This lecture notes is based on Prof Doreen De Leon's lectures.

Reading

Learning Perl, Chapter 11

Filehandles

Opening and Closing a Filehandle

open SCORES, "midterm"; 
$firstscore = <SCORES>;
chomp($firstscore);
print $firstscore, "\n";

If the following file midterm exists

12
23
45
13
39

The output is

12

If the file midterm doesn't exists

readline() on closed filehandle SCORES at test.pl line 2.
Use of uninitialized value in scalar chomp at test.pl line 3.
Use of uninitialized value in print at test.pl line 4.

Remove the file midterm and run the following program

$success = open SCORES, "midterm"; 
if($success) {
   $firstscore = <SCORES>;
   chomp($firstscore);
   print $firstscore, "\n";
} else {
    print "Fail to open the file midterm.\n";
}

Here is the output

Fail to open the file midterm.

put the midterm file back

open SCORES, "midterm"; 
$sum=0;
$count=0;
while(defined($score = <SCORES>)) {
   chomp($score);
   $sum+=$score;
   $count++;
} 
print "Average: ", ($sum/$count);

For the following program, if file square doesn't exist, the computer will create one. If it exists, the computer will overwrite the content of the file.

open OUT, ">squres"; 
for($i = 1; $i <= 10; $i++) { 
    print OUT "$i ", ($i*$i), "\n";
}

Run the above program several times and run the following program several times

open OUT, ">>squres"; 
for($i = 1; $i <= 10; $i++) { 
    print OUT "$i ", ($i*$i), "\n";
}

close

open SCORES, "midterm"; 
$sum=0;
$count=0;
while(defined($score = <SCORES>)) {
   chomp($score);
   $sum+=$score;
   $count++;
} 
print "Average: ", ($sum/$count);
close SCORES;
open OUT, ">squres"; 
for($i = 1; $i <= 10; $i++) { 
    print OUT "$i ", ($i*$i), "\n";
}
close OUT;

die

Remove the file midterm and test the next program.

open SCORES, "midterm" or die "Cannot open file midterm $!";
$firstscore = <SCORES>;
chomp($firstscore);
print $firstscore, "\n";

Output

Cannot open file midterm: No such file or directory at test.pl line 1.

$0

The following program print out the file name of the perl script.

print $0;

Using Filehandles

$scores_file = "scores.txt";
$result = "result.txt";
open SCORES, $scores_file or die "Can't open file $scores_file";
open RESULT, ">$result" or die "Can't open file $result"; 
while(<SCORES>) {
    chomp;
    @array = split(",", $_);
    print RESULT 0.3*$array[0] + 0.25*$array[1] + 0.45*$array[2];
    print RESULT "\n";
}

The file scores.txt is

55,22,33
11,33,44
39,21,11

The output result.txt is

36.85
31.35
21.9
$scores_file = "scores.txt";
$result = "result.txt";
open SCORES, $scores_file or die "Can't open file $scores_file";
open RESULT, ">$result" or die "Can't open file $result"; 
select RESULT; # change the default of output
while(<SCORES>) {
    chomp;
    @array = split(",", $_);
    print 0.3*$array[0] + 0.25*$array[1] + 0.45*$array[2];
    print "\n";
}

File Tests

$filename = "file";
print "$filename exists" if -e $filename;