in reply to Mini bash script to perl

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.

Replies are listed 'Best First'.
Re^2: Mini bash script to perl
by JavaFan (Canon) on Nov 04, 2011 at 16:09 UTC
    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.)