Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: difference in regex

by sundialsvc4 (Abbot)
on May 29, 2018 at 14:27 UTC ( [id://1215379]=note: print w/replies, xml ) Need Help??


in reply to difference in regex

(After dropping up-votes on every single comment in this thread up to now ...)

If what you literally want to do is to “split the string by commas and take the last piece,” what I would probably have done is to first split the string on a comma, then pop the last entry off the resulting array.   This will work whether-or-not there is actually a comma in the string, since in that case the array will contain only one entry.   I would prefer this approach because it represents a literal interpretation of how you originally described your objective, and because it’s how I am accustomed to see this sort of thing being done most of the time.   (The split function has many useful features – read the doc page in its entirety.)

Replies are listed 'Best First'.
Re^2: difference in regex
by jwkrahn (Abbot) on May 29, 2018 at 18:26 UTC
    what I would probably have done is to first split the string on a comma, then pop the last entry off the resulting array.

    As in:

    my @array = split /,/, $string; my $value = pop @array;

    But you don't really need an array to do that because you can get the last value directly from the list that split returns:

    my $value = ( split /,/, $string )[ -1 ];
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re^2: difference in regex
by haukex (Archbishop) on May 30, 2018 at 13:32 UTC

    I'm all for TIMTOWTDI, but I wondered about performance. And it turns out that while a split version is faster for short strings, performance suffers a lot the more commas there are in the string:

    use warnings; use strict; use Benchmark qw/cmpthese/; my $str = join ',', 'a'..'z', 5; my $exp_path = join ',', 'a'..'z'; my $exp_value = 5; cmpthese(-2, { split => sub { my @x = split /,/, $str; my ($path, $value); $value = pop @x if @x>1; $path = join ',', @x; #die unless $path eq $exp_path && $value eq $exp_value; }, regex => sub { my ($path, $value) = $str=~/^ (?| ([^,]*) | (.*) , ([^,]*) ) $/x; #die unless $path eq $exp_path && $value eq $exp_value; }, } ); __END__ Rate split regex split 326127/s -- -66% regex 966896/s 196% --

    Update: This version using rindex beats both split and the regex.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-03-29 08:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found