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

Here's my take:

c:\@Work\Perl\monks>perl -wMstrict -le "my $re_obj = qr{([0-6BS])}; my $re_str = '' . $re_obj; print $re_str; ;; if ('ABC' =~ $re_str) { print qq{match, \$1 captured '$1'}; } else { print 'no match'; } " (?^:([0-6BS])) match, $1 captured 'B'


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

Replies are listed 'Best First'.
Re^2: how to use string RE (against $_ and capture)
by perl-diddler (Chaplain) on Nov 08, 2016 at 02:20 UTC
    What I meant is how, after "$re_str" has been stringified, would the code know the string is meant to be used as a regexp instead of a direct compare. The keys represent command-line flags or switches after one dash has been removed, but in this case I wanted the key to match several possibilities.

    As I noted in the other response, it looks like searching for '(?' at the beginning of the expression is the best way.

      ... how, after "$re_str" has been stringified, would the code know the string is meant to be used as a regexp instead of a direct compare.

      The code "knows" because the string is used by a   =~  m//  s/// (I think that's all of them) matching operator. And what's a "direct compare" anyway?


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

        If one's key is in '$_', direct compare is either "$_ eq 'x'" or in this case, using "$_" as a hash key, directly and not trying to match it to a Regex.

        Thus my need to know if a key in the table is a literal or a regex so I can do the right test to see if the key matches.