How to test if a capture is defined in Perl regexp matching?
#!/usr/bin/env perl
use v5.10;
my $str="foobar
barfoo";
while($str =~ m/(?:(f.*))|(?:(b.*))/g) {
say "+ $1";
say "- $2";
}
It outputs
+ foobar
-
+
- barfoo
while what I want is
+ foobar
- barfoo
I.e. if $1 or $2 aren’t matched, it shouldn’t print.
The thing is you aren’t testing if it’s defined, so it’s going to print the +/- either way.