Thursday, November 20, 2014

How to implement linux tail command in perl

I have tried writing a Perl script to simulate Linux tail command - print last n lines from a file. This is one the common interview question in Perl. This can be extended to print selected lines of other Linux command like head. It works perfectly fine.


print "\nImplements linux tail command in perl \n\n";

$file   =  $ARGV[0];
$n = $ARGV[1];
open(FILE, $file);
@arr = ;
close(FILE);
$length  = scalar(@arr);
$n = $length  - $n;

while($n<$length )
{
print $arr[$n];
$n =$n + 1;
}

Comment  below if you have a better option

2 comments:

  1. how about implementing tail -f after this :)
    while(1){
    $prev_size = -s $file;
    tailf($file,10) if (-s $file > $prev_size);
    }

    tailf() will be your written code with little updates :)

    ReplyDelete
  2. We can also write tail implementation in Perl as below

    my $maxline = 10;
    if(scalar(@ARGV) == 2){
    $maxline = shift;
    }

    my $file_name =shift;
    open(FILE, "$file_name") || die "Can't open file. Error: $!\n";
    my @arr = ;
    close(FILE);
    my $index=scalar(@arr)-$maxline;
    print @arr[$index .. $#arr];

    ReplyDelete

Looking to move from development to DevOps? Here is what you should know

DevOps is a buzz word in the last decade, everybody wants to try their luck in DevOps. DevOps is the most generic area of software engineeri...