[Israel.pm] Re: regex substitute with lookup table (Yuval Yaari)

roiem at actcom.co.il roiem at actcom.co.il
Sun Mar 28 14:06:47 PST 2004

> if (/someText (.+?) someMoreText (\d+)/)
> {
>       if (exists $hash{$2})
>       {
>             my $newStr=$hash{$2};
>             s/someText $newStr someMoreText/;
>       }
> }

Hmmm, how about 

  someText (.+?)
  someMoreText (\d+)
    exists $hash{$2}?'':'ThisRegexpWillNeverMatch'
  })/someText $hash{$2} someMoreText $2/x;


  someText (.+?) (?{local $newStr=$1})
  someMoreText (\d+) (?{$newStr=$hash{$2} if exists $hash{$2}})
  /someText $newStr someMoreText $2/x;

both of which, of course, have never been tested, or even compiled.

They do make use of the experimental embedded code and postponed
subexpression features of Perl. The first option causes (I ought to say,
"should cause", because I have no idea if it will really work) the
entire regexp to fail if the value doesn't exist, and the second one
sets $newStr to the old value unless the value exists in the hash.

Both of these behave slightly differently, in that they will backtrack
and try to find a different match for $2 if it didn't work.

According to the Apocalypses, Perl 6 will have a mechanism for these
things, "code assertions" if I remember correctly.

- Roie Marianer

More information about the Perl mailing list