[Chicago-talk] Using a hash in a regex

Randal L. Schwartz merlyn at stonehenge.com
Thu Jul 13 13:43:01 PDT 2006

>>>>> "Jay" == Jay Strauss <me at heyjay.com> writes:

Jay> How do you use a hash in a regex?  I remember it being mentioned but I
Jay> couldn't find it in the archives.  For example,

Jay> %h = (this=>1, that=>2);

Jay> $s = "this is a test";

Jay> # now what I'd like to do is:
Jay> my $n = m/$s/%h/;  #and have $n = 1;

Andy must've been distracted by a bright shiny object.  You can do this:

my %h = (this=>1, that=>2);
my $s = "this is a test";
my $regex = join "|", reverse sort keys %h;
$s =~ s/($regex)/$h{$1}/g;
print $s, $/;

That replaces "this" with "1" in the string.  I *think* that's what you want.
It's not exactly what you said.  But it's what would likely be in the
archive. :)

Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!

More information about the Chicago-talk mailing list