Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Printing Last Element of a line using perl memory?

by pemungkah (Priest)
on Feb 15, 2013 at 01:49 UTC ( #1018828=note: print w/ replies, xml ) Need Help??


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
  • -l auto-chomps
  • -n wraps the code in a while(<>){ ... }
  • The substitutions remove leading and trailing blanks
  • The split extracts the words in the line (whitespace-separated)
  • The pop takes the last word
  • We save this for each line
  • At end of file, we print the current last word, which will be from the last line


Comment on Re: Printing Last Element of a line using perl memory?
Download Code
Replies are listed 'Best First'.
Re^2: Printing Last Element of a line using perl memory?
by LanX (Canon) 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 (Curate) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1018828]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2015-07-29 01:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (260 votes), past polls