in reply to Regex: return the pattern instead of the actual match

In view of the alternation, perhaps OP means that the intent is to print that part of the regex that produced the match.

That could be achived by using multiple regexen instead of alternation:

#!/usr/bin/perl use strict; use warnings; use 5.012; # #926110 my $regex1 = qr/foo\d+/; my $regex2 = qr/bar\S+?/; my @string = qw(foo17 barABC nomatch); for my $string(@string) { if ($string =~ m/($regex1)/ && $regex1 =~ /(.*)/s) { say "$1 when string is \"$string\""; } elsif ( $string=($regex2) && $regex2 =~ /(.*)/s ) { say "$1 when string is \"$string\""; } else { say "no match on $string"; } }
which produces this:
(?-xism:foo\d+) when string is "foo17" (?-xism:bar\S+?) when string is "barABC" (?-xism:bar\S+?) when string is "nomatch"

Update: Or, better (simpler and more info in output):

hashbang, strict, warn, etc... my $regex1 = qr/foo\d+/; my $regex2 = qr/bar\S+?/; my @string = qw(foo17 barABC this-has-no-match); for my $string(@string) { if ($string =~ m/($regex1)/) { say "matched part of \"$string\" is $1 when regex is \"$r +egex1\""; next; } elsif ( $string=~ m/($regex2)/ ) { say "matched part of \"$string\" is $1 when regex is \"$regex2 +\""; next; } else { say "no match on $string"; } }
outputting:
matched part of "foo17" is foo17 when regex is "(?-xism:foo\d+)" matched part of "barABC" is barA when regex is "(?-xism:bar\S+?)" no match on this-has-no-match