in reply to how to use string RE (against $_ and capture)

In your first code sample, you have:

my $re_str=qr{([0-6BS])}; $_="B"; my $ans; if (eval m{$re_str})

Why are you using eval? It should not be needed.

In your second code sample:

my $re_str="qr{([0-6BS])}"; $_="B"; my $ans; if (eval m{$re_str})

The m{$re_str} will be interpreted as m/qr{([0-6BS])}/ which is looking to match something that starts with "qr". (And I'm not sure how the "{([0-6BS])}" will get interpreted as. "{" and "}" in a regex are normally used to quantify the number of matches.)

To store a regex as a hash key, you could prefix the regex with a character that won't otherwise appear as the first character of any of your hash keys. So, something like this:

#not tested, YMMV for $key (keys %options) { if ($key =~ s/^#//) { if (/$key/) { print "Match: $1\n"; } } else } if ($_ eq $key) { print "Equals: $1\n"; } } }

Replies are listed 'Best First'.
Re^2: how to use string RE (against $_ and capture)
by AnomalousMonk (Archbishop) on Nov 12, 2016 at 00:15 UTC
    ... I'm not sure how the "{([0-6BS])}" will get interpreted as. "{" and "}" in a regex are normally used to quantify the number of matches.

    Apparently, if the RE compiler can't see anything in the regex that looks like a count or count range, it just gives up on the whole counted quantifier thing and takes the curlies as literal characters.

    c:\@Work\Perl>perl -wMstrict -le "$_ = 'xxqr{S}xx'; print qq{matched '$&', \$1 is '$1'} if m/qr{([0-6BS])}/; " matched 'qr{S}', $1 is 'S'
    (Tested under ActiveState 5.8.9, Strawberry 5.14.4.1.)

    To store a regex as a hash key, you could prefix the regex with a character that won't otherwise appear as the first character of any of your has keys.

    I still prefer some sort of separate tag to distinguish pattern from exact matching:

    c:\@Work\Perl>perl -wMstrict -MData::Dump -le "my %options = ( qr{ x (Y) z }xms => { type => 'pattern', name => 'foo', }, '(?x) x (Y) z ' => { type => 'pattern', name => 'fum', }, 'xYzzy' => { type => 'exact', name => 'bar', }, 'zzzzz' => { type => '?????', name => 'zot', }, ); dd \%options; ;; $_ = 'xYzzy'; for my $p (sort keys %options) { my ($p_type, $p_name) = @{ $options{$p} }{ qw(type name) }; if ($p_type eq 'pattern') { if ($_ =~ $p) { print qq{'$p_name' pattern match of $p, \$1 is '$ +1'}; } } elsif ($p_type eq 'exact') { if ($_ eq $p) { print qq{'$p_name' exact match of '$p'}; } } else { die qq{unknown: $p; type '$p_type'; name '$p_name'}; } } " { "(?^msx: x (Y) z )" => { name => "foo", type => "pattern" }, "(?x) x (Y) z " => { name => "fum", type => "pattern" }, "xYzzy" => { name => "bar", type => "exact" }, "zzzzz" => { name => "zot", type => "?????" }, } 'foo' pattern match of (?^msx: x (Y) z ), $1 is 'Y' 'fum' pattern match of (?x) x (Y) z , $1 is 'Y' 'bar' exact match of 'xYzzy' unknown: zzzzz; type '?????'; name 'zot' at -e line 1.
    (Test under same Perl versions as above.)


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