Tail function to print last 10 lines of a file

This can be easily written using the linux ‘tail’ command in Perl. But if you dont want to use that the other solution I saw was to add in an array and print the last 10 lines. This did not look efficient to me so I tried improving it a little. Here I only use a 2 counters but I still need to open the file twice.

my $count1, $count2=0;
open(FH,”same.txt”);
while (<FH>)
{
$count1++;
}
$count2 = $count1 -10;
$count1=0;
close(FH);
open(FH,”same.txt”);
while(<FH>)
{
if($count1 == $count2)
{
print $_;
$count2++;
}
$count1++;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s