http://www.perlmonks.org?node_id=1018828


in reply to Printing Last Element of a line using perl memory?

A somewhat different way of doing it:
perl -lne 's[\A\s+][]; s[\s+\Z][]; $last=pop [split /\s+/] if $_; END +{ print $last }' scan.log

Replies are listed 'Best First'.
Re^2: Printing Last Element of a line using perl memory?
by LanX (Saint) on Feb 15, 2013 at 09:42 UTC
    > The pop takes the last word

    Version warning! =)

    not with < 5.14

    DB<100> $_=join " ",a..z => "a b c d e f g h i j k l m n o p q r s t u v w x y z" DB<101> $x= pop [ split / / ] ;; Type of arg 1 to pop must be array (not anonymous list ([])) at (eval +20)[multi_perl5db.pl:644] line 2, at EOF DB<102> $x= pop @{[ split / / ]} # Workaround => "z"

    Cheers Rolf

      Thanks! Filing that one.
        here a way to avoid a temp array

        DB<100> $_=join " ",a..z => "a b c d e f g h i j k l m n o p q r s t u v w x y z" DB<101> $x = (split / /)[-1] => "z"

        Cheers Rolf

Re^2: Printing Last Element of a line using perl memory?
by jaredor (Priest) on Feb 15, 2013 at 18:12 UTC

    ++ for the END block idea. A further tweak would be to not process data in the main loop, but only the END block. Unfortunately I could not think of a slick way to make $_ available to END from the last loop iteration, so I had to cheat a little to golf your solution. Apparently the autosplit array does remain resident:

    perl -nae 'END { print "$F[-1]\n"; }' scan.log

    Good examples like yours are weaning me from sed ;-)

      Ooh, nice! I'll use that one too.