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
Update:
I would much prefer to be able to write the whole body of the of loop in the above example in the form:
$total_min += SELF_CONTAINED_FUNCTIONAL_STATEMENT;
$total_max += SELF_CONTAINED_FUNCTIONAL_STATEMENT;
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.)
|
|---|