in reply to Re: regex question
in thread regex question

That's actually a really nice way to use a hash to look through a string and replace keys with values.

You could even generalize it to multi-character keys:

my %value_lkup = ( A => '1000', B => '2000', CDE => '3000', ); my $pat = '(?:' . join('|', keys %value_lkup) . ')'; s/($pat)/$value_lkup{$1}/g;

Replies are listed 'Best First'.
Re^3: regex question
by ikegami (Patriarch) on Sep 03, 2009 at 00:00 UTC

    To make it a general solution, you need to add quotemeta and you gotta be careful about ordering if one key can be the the start of another key. And if you're going to add (?:), you might as well use qr//.

    my ($pat) = map qr/$_/, join '|', map quotemeta, sort { length($b) <=> length($a) } keys %value_lkup; my @data = map $value_lkup{$_}, /$pat/g;