in reply to Read Last Line of A File Only

Maybe you could use tail -1
#!/usr/bin/perl -w use strict; while( 1 ) { my $file = shift || last; open TAIL, "tail -1 $file|" or die "can't do tail -1 $file:$!\ +n"; my $line = <TAIL>; print $line; close TAIL; }

Plankton: 1% Evil, 99% Hot Gas.

Replies are listed 'Best First'.
Re^2: Read Last Line of A File Only
by Aristotle (Chancellor) on Aug 23, 2004 at 20:22 UTC

    Or better yet, using the safer syntax options available in 5.6 and later:

    my $lastline = do { open my $pipe, '-|', tail => -1, $file or die "Can't spawn tail: $!\n"; <$pipe>; }; print $lastline;

    I'm not sure why you chose to write your loop that way, either. Why the obfuscatory infinite loop with an abort condition as in this?

    while( 1 ) { my $file = shift || last; # ... }

    It took me a moment to realize that you meant something entirely different than what I assumed at first glance. The natural thing would have been to put the abort condition where you normally put it: in the loop condition.

    while( @ARGV ) { my $file = shift; # ... }

    Of course, that's clearer written as

    for my $file ( @ARGV ) { # ... }

    So we get

    for my $file ( @ARGV ) { my $lastline = do { open my $pipe, '-|', tail => -1, $file or die "Can't spawn tail: $!\n"; <$pipe>; }; print $lastline; }

    I find that significantly clearer despite the changes not changing any of the semantics.

    Makeshifts last the longest.

      Or better yet, using the safer syntax options available in 5.6 and later:
      my $lastline = do { open my $pipe, '-|', tail => -1, $file or die "Can't spawn tail: $!\n"; <$pipe>; }; print $lastline;

      Interesting. Could you please point me to the documentation of this feature? I took a look around perldoc and couldn't find it, so I am surely searching the wrong way

      Thanks in advance

      Ciao!
      --bronto


      The very nature of Perl to be like natural language--inconsistant and full of dwim and special cases--makes it impossible to know it all without simply memorizing the documentation (which is not complete or totally correct anyway).
      --John M. Dlugosz

        You're talking about the multi-argument form for piped opens? Sorry, that was added in Perl 5.8. The hooks were there in 5.6, ie the syntax was recognized, but Perl would die with an error at runtime if you tried to do that.

        perl58delta says:

        If your platform supports fork(), you can use the list form of "open" for pipes. For example:

        open KID_PS, "-|", "ps", "aux" or die $!;

        forks the ps(1) command (without spawning a shell, as there are more than three arguments to open()), and reads its standard output via the KID_PS filehandle. See perlipc.

        When I said "safer options" I also referred to lexical filehandles, of course, for which my assertion about 5.6 was correct.

        Makeshifts last the longest.