In: Computer Science
The objective is to read the last five lines of a file (text file) in Perl. I wrote down what I have written so far in Perl but I get an error message saying, "Can't open sample.txt: No such file or directory." The sample.txt file is located in the same directory that I am executing the perl scripts on the command line.
sample.txt
=============================================================
My
name
is
Jennifer
and
I
like
to
eat
tacos
de
birria
.
===========================================================
#!/usr/bin/perl
$filename= 'sample.txt';
open my $fh, "+>", $file or die "Can't open $filename: $!\n";
print "$file[-5]\n";
print "$file[-4]\n";
print "$file[-3]\n";
print "$file[-2]\n";
print "$file[-1]\n";
In case of any query, do comment. Please rate answer. Thanks
Code is as below:
#!/usr/bin/perl
$filename= 'sample.txt';
#corrected the file name here, you were using undeclared variable
open my $fh, "+<", $filename or die "Can't open $filename: $!\n";
#reverse the array of lines read by file handle into an array
chomp(my @linesInFile = reverse(<$fh>));
#determine the length of array
$length = @linesInFile;
#if length is greater than 5 then only print 5 lines so assign length to 5
if($length > 5){
$length =5;
}
#for loop to print the files
for (my $i=0; $i < $length; $i++) {
print "$linesInFile[$i]\n";
}
==================screen shot of the code==============
output: