First thing to note is that the keys are literals and that storing a "qr{([0-6BS])}" can only be safely stored as a string, since compiled, it becomes a Regexp-ref, and ref's don't store too well in strings. So I'm trying to figure out a way to convert that string to a usable RE and have it return a captured value of the single-character matched.
A form that works for matching (but not for putting in the hash table because it converts the key to a ref) is:
I included that example so you could see what type of output I wanted (i.e. "ans containing 'B').> perl -we'use strict; use P; my $re_str=qr{([0-6BS])}; $_="B"; my $ans; if (eval m{$re_str}) { $ans=$1; } P "ans=%s, re_s=%s", $ans, $re_str; ' ans=B, re_s=(?^:([0-6BS]))
As soon as I turn my re_str into a string though I start having problems.
my $re_str="qr{([0-6BS])}"; $_="B"; my $ans; if (eval m{$re_str}) { $ans=$1; } P "ans=%s, re_s=%s", $ans, $re_str;'
ans=∄, re_s=qr{([0-6BS])}
In this case, it looks like the if wasn't taken so nothing got assigned to ans. In any case, $ans contains an undef (the '∄' symbol literally means "there does not exist").
I've tried several variations in the eval, including assigning the string re to another var and using that in my match, like:
my $re_str="qr{([0-6BS])}"; $_="B"; my $ans; if (eval P (q(my $re=%s; m{$re}), $re_str) ) { $ans=$1; } P "ans=%s, re_s=%s", $ans, $re_str;'
ans=∄, re_s=qr{([0-6BS])}
But no change. I've tried storing the result
to a package var by changing the "my $ans" to "our $ans". no good.
I feel like there some be some obvious, simple solution for something so trivial, but it is eluding me.
Could someone point out what I might use instead?
Ideally, instead of using "$ans" I could use something like
my $re_str="qr{([0-6BS])}"; $_="B"; our @ans = m{$re_str}; P "ans=%s, re_s=%s", \@ans, $re_str;'
ans=[], re_s=qr{([0-6BS])}
to allow the possibility of multiple matches in "re_str" being captured, but an empty array is definitely not so helpful and any value returned would be better than none.
Ideas?..... Thanks!
In reply to how to use string RE (against $_ and capture) by perl-diddler
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |