in reply to Perl Multiple If Conditions with Match Variables

It's also possible to use multiple "capturing lookaheads" for a kind of logical-and effect:

c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'xx foo yy bar zz baz'; ;; if (my ($c1, $c2, $c3) = $s =~ m{ \A (?! .* zot) (?= .* (bar)) (?= .* (baz)) (?= .* (foo)) }xms ) { print qq{c1 '$c1' c2 '$c2' c3 '$c3'}; } " c1 'bar' c2 'baz' c3 'foo'

Update: Another trick I like is to capture match success separately for later use, e.g., in conditionals:

c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'xx foo yy bar zz baz'; ;; my $match = my ($c1, $c2, $c3) = $s =~ m{ \A (?! .* zot) (?= .* (bar)) (?= .* (baz)) (?= .* (foo)) }xms; ;; if ($match) { print qq{c1 '$c1' c2 '$c2' c3 '$c3'}; } else { print 'no match'; } " c1 'bar' c2 'baz' c3 'foo'

Later Update: Oops... I didn't read beyond the first two  $x+2 subscripts to realize the matches might be made against completely different variables; shoulda read choroba's reply more carefully. Oh well, the trick still works with a single variable.


Give a man a fish:  <%-{-{-{-<