Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Simple way to split on last match?

by Marshall (Monsignor)
on Aug 05, 2012 at 19:22 UTC ( #985567=note: print w/replies, xml ) Need Help??


in reply to Simple way to split on last match?

In Perl, you can use the index of [-1] to indicate the last array element. A REGEX would work fine here also. I don't know without benchmarking, but I suspect that the regex version is actually faster.
#!/usr/bin/perl -w use strict; my $line ='last -- From --00--SPLIT ?--11452'; my ($last) = (split(/--/, $line))[-1]; print "using split: $last\n"; ($last) = $line =~ /(\d+)\s*$/; print "using regex: $last\n"; __END__ Prints: using split: 11452 using regex: 11452
Update: I guess I should say that the parens around ($last) are necessary to put $last into a list context, otherwise you just get 1 or 0 value. Here we want the actual value that was captured rather than whether it the expression "worked" or "not.

Replies are listed 'Best First'.
Re^2: Simple way to split on last match?
by aturtle (Novice) on Aug 05, 2012 at 20:36 UTC
    Hey thanks! my ($last) = (split(/--/, $line))-1; Works The -1 is what is significant in getting the last one i guess. -Turtle
      Yes that is correct.
      A Perl "list slice" can have indices of [-3,2,-1,3,-4] in any order. The one thing that I wish Perl could do that it cannot do: is to say "I want all of the stuff past index X" in a simple syntax.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2016-10-01 21:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?






    Results (8 votes). Check out past polls.