Consider the example of having as input a list of numbers, some of which are not known exactly but only known to be inside a given range (that is encoded in a string value).
The following code snippet adds up the given numbers, returning an upper and lower bound for the result:
#!/usr/bin/perl use strict; use warnings; my @ranges = ('15', '28-31', '3-4', '40', '17-19'); my ($total_min, $total_max); foreach my $range (@ranges) { my ($min) = $range =~ /^(\d+)/; my ($max) = $range =~ /(\d+)$/; $total_min += $min; $total_max += $max; } print "total is between $total_min and $total_max\n";
It works fine, but regarding the regex part, the need to
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;
Is there an alternative syntax for string extraction using regexes that would allow this?
It's not about performance or such. It's about my brain receiving a nice dose of dopamin whenever I write a line of concise, functional, self-contained code - and the opposite when I can't.
----
PS: Even better would be the following, but unfortunately it seems that Perl's += operator does not work that way:
($total_min, $total_max) += STATEMENT_RETURNING_A_LIST_OF_TWO_NUMS;
In reply to Is there a more functional regex syntax? by smls
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |