Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How can I convert these commands to the perl script?
rm screenlog;tail -n 200 screenlog.0 > screenlog;

Replies are listed 'Best First'.
Re: Mini bash script to perl
by toolic (Bishop) on Nov 04, 2011 at 15:42 UTC
Re: Mini bash script to perl
by Ratazong (Monsignor) on Nov 04, 2011 at 15:10 UTC

    A simple way, without any error-handling etc:

    system("rm screenlog"); system("tail -n 200 screenlog.0 > screenlog");
    You might need to adapt the path to your screenlog-files, however.

    HTH, Rata

Re: Mini bash script to perl
by CountZero (Bishop) on Nov 04, 2011 at 17:29 UTC
    Have a look at File::Tail, Tail::Tool or even MultiTail.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Mini bash script to perl
by hbm (Hermit) on Nov 04, 2011 at 15:46 UTC

    Shell commands rewritten in Perl will often seem horribly verbose, but don't be discouraged.

    Here's one way:

    use strict; use warnings; use Tie::File; use Fcntl 'O_RDONLY'; my $file = 'screenlog'; unlink $file; tie my @lines, 'Tie::File', "$file.0", mode => O_RDONLY; my $end = (scalar @lines > 200 ? 200 : scalar @lines); # added open(OUT,">",$file) or die("Unable to open $file: $!"); print OUT join "\n", @lines[-$end..-1]; # changed close OUT; untie @lines;

    Update: Corrections above.

      One difference between the one liner and your code (other than the original one liner prints the last 200 instead of the last 20 lines) is that the original one-liner handles files having less than 200 lines gracefully. If "screenlog.0" has less than 200 lines, your code will spit out a warning and a blank line of each line "missing". That is, if screenlog.0 only has 30 lines, the original shell one liner will put 30 lines in screenlog, and generate no warnings, while your code will issue 170 warnings, and put 170 additional blank lines in "screenlog".

      Shell commands rewritten in Perl will often seem horribly verbose, but don't be discouraged.
      I'd say, if you want to rewrite shell commands in Perl, think twice, don't do it, and if you insist and need advice, get that advice from shell experts.

        Point taken (regarding your first paragraph.)