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

I'm not entirely sure I understand what you're trying to achieve, but dereffing and stringifying a qr// ref gives you a usable pattern string. For example:
my $re1 = qr{([0-4])}; my $re2 = qr{([5-9])}; my %hash = ("$$re1" => "foo", "$$re2" => "bar"); $_ = "-5-"; for my $re (keys %hash) { print "match: ($1) $hash{$re}\n" if /$re/; } # outputs: # match: (5) bar
Of course in the above it's now re-compiling the regex when executing it.

Dave.

Replies are listed 'Best First'.
Re^2: how to use string RE (against $_ and capture)
by perl-diddler (Chaplain) on Nov 07, 2016 at 23:59 UTC
    My problem has come in being able to recognize when I have a regex vs. a regular string in a key. I tried using a "ref $re", looking for a Regexp (no go), and I tried looking for "qr" -- only works if you store qr as a string initially, and try to evaluate it later. That's what I ended up trying to do. Looking for something like "(?" makes me a bit less comfortable than searching for "qr", though -- it looks a bit sloppy for some reason, but maybe I'm just not used it.
      I tried using a "ref $re", looking for a Regexp (no go) ...

      I'm not sure what this means. Again, my take:

      c:\@Work\Perl\monks>perl -wMstrict -le "my $re_obj = qr{([0-6BS])}; if (ref $re_obj) { print 'A: reference: ', ref $re_obj; } else { print 'A: not a reference'; } ;; my $re_str = '' . $re_obj; if (ref $re_str) { print 'B: reference: ', ref $re_str; } else { print 'B: not a reference'; } " A: reference: Regexp B: not a reference


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

        "tried using a 'ref $re', looking for a Regexp" means I tried using 'ref' on '$re' and expected to get a RegExp, but didn't, as in:
        my %hash=(qr{([0-4])}=>"foo", a=>"foo2"); $_=2; for my $re (keys %hash) { P "re=%s, ref=%s", $re, ref $re; P "match:(%s) %s", $1, $hash{$re} if /$re/; } ' re=a, ref= re=(?^:([0-4])), ref= match:(2) foo
        In the case that matches where "re=(?^:(0-4))", the ref was blank. I felt this was confusing -- since if you first assign the "qr" expression to a scalar and check the ref, you do get a ref of Regexp. But if you put it directly into the hash and do a ref on the key you pull out, the ref-type is lost. After the qr-expression has been used as a key in a hash, you lose the reference. At that point, determining that it was a Regexp, is a bit "unpretty", in that it seems one would test if the expression began with '(?'.

        Also, the '^' being inserted after '(?' looks odd since the original 'qr' expression didn't include it. Do you know why it was inserted in the stringified version?

        At this point, to check whether or not I need to use the 'key' directly or use it in a RE it seems I look for the paren, question-mark, which just looks strange, even though it works.