in reply to regex s/// using hash
This seems to be a misleading (yet usefull) feature. it means that (${code}) isn't an "always true" assertion. But is it reliable enough to be used?
In (?(cond)|...), cond is not a regexp. While the syntax is similar, ?{code} has a different meaning there than in regexs.
In regexs, (?{code}) always matches. The return value is stored in $^R.
In (?(?{code})|...), (?{code})'s return value is used to determine which sub-regexs to use.
But is it reliable enough to be used?
Yes, it's reliable. The only catch is that these blocks are closures, so you can run into problem when you use lexical (my) variables declared outside of the regex in these blocks. I always use package (our) variables. If you have a lexical variable you don't want to convert, you could always create an alias to it.
our %pkg_hash; local *pkg_hash = \%lex_hash;
You seem to have problems deciding whether the keys are strings or regexs. Either way, your snippets are buggy. If they're strings, your 2nd and 3rd snippet should be
my $re = join '|', map quotemeta, keys %dict; s/($re)/$hash{$1}/g;
use Regexp::List qw( ); my $re = Regexp::List->new()->list2re(keys %dict); s/$re/$hash{$1}/g;
quotemeta converts strings to regexs, and Regexp::List works with strings (while Regexp::Assemble works on regexs).
If the keys are regex, your snippets won't work except for the simplests of regexs (those without any metachars) because you won't be able to lookup the appropriate hash entry in the replace expression.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: regex s/// using hash
by oha (Friar) on Oct 16, 2007 at 13:48 UTC | |
by ikegami (Patriarch) on Oct 16, 2007 at 13:57 UTC | |
by oha (Friar) on Oct 16, 2007 at 14:01 UTC | |
by ikegami (Patriarch) on Oct 16, 2007 at 14:06 UTC | |
by oha (Friar) on Oct 16, 2007 at 14:12 UTC |