Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Is there a more functional regex syntax?

by AnomalousMonk (Chancellor)
on Sep 18, 2012 at 16:54 UTC ( #994313=note: print w/replies, xml ) Need Help??

in reply to Is there a more functional regex syntax?

I, too, would be inclined toward something like the initial form of the code given in the OP for reasons of readability and maintainability. However, here's another way to glue everything together:

>perl -wMstrict -le "my @ranges = ('15', '28-31', '3-4', '40', '17-19'); my ($total_min, $total_max); ;; m{ \A (\d+) (?{ $total_min += $^N }) (?: - (\d+))? (?{ $total_max += $^N }) \z }xmsg for @ranges; ;; print qq{total between $total_min and $total_max}; " total between 103 and 109


I would much prefer to be able to write the whole body of the of loop in the above example in the form:

This seems to come a bit closer to what smls asked for (but I like BrowserUk's solution better!) and has a bit of input validation:

perl -wMstrict -le "my @ranges = qw(15 28-31 3-4 40 17-19 99- -99 -99- x x-x); my ($total_min, $total_max); ;; my $extract_ranges = qr{ \A (\d+) (?: - (\d+))? \z }xms; for (@ranges) { $total_min += /$extract_ranges/ && $1; $total_max += /$extract_ranges/ && $^N; } ;; print qq{total between $total_min and $total_max}; " total between 103 and 109

(Update: Now that I look back on this thread, my second approach looks rather like kennethk's first idea.)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://994313]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2017-11-24 01:14 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (343 votes). Check out past polls.