Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Is there a more functional regex syntax?

by kennethk (Monsignor)
on Sep 18, 2012 at 15:54 UTC ( #994307=note: print w/ replies, xml ) Need Help??


in reply to Is there a more functional regex syntax?

What about something more like:

$range =~ /^(\d+)(?:-(\d+))?$/; $total_min += $1; $total_min += $2//$1;
I personally think holding onto $min and $max reads easier, but I can understand the desire for conciseness.

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.


Comment on Re: Is there a more functional regex syntax?
Select or Download Code
Re^2: Is there a more functional regex syntax?
by kennethk (Monsignor) on Sep 18, 2012 at 16:56 UTC
    Or, as an improvement in the regex, /^(?=(\d+))(?:\d+-)?(\d+)$/, so that both $1 and $2 are always defined. So, as 1 line,
    $totals[$_] += ($range =~ /^(?=(\d+))(?:\d+-)?(\d+)$/)[$_] for 0,1;
    Or more simply, if you want to keep the variables separate,
    $total_min += ($range =~ /^(\d+)/)[0]; $total_max += ($range =~ /(\d+)$/)[0];

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      Thank, this is what I've been looking for!

      It's not extremely pretty, but it should scale nicely for the general case of needing the result of a regex string extraction as a right-hand-side value.

      PS: The regex suggested by tobyink above can make the single-line case much more readable: /(\d+)/g

        The regex suggested by tobyink above can make the single-line case much more readable

        The advantage of mine is that it actually enforces format, which may or may not be of concern. I also like that you expect two values and you get two values; a little less slight of hand for maintenance. But I do appreciate the elegance of his choice of indices.

        Also be aware you'll need to initialize @totals = (0,0) so that the index -1 doesn't map to your first term. tobyink does it, but didn't really emphasize its importance.


        #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2014-12-25 00:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (159 votes), past polls