[Israel.pm] regex substitue with lookup table

David Baird david.baird at homemail.com
Sun Mar 28 01:05:57 PST 2004

Yossi Itzkovich wrote:
> I have a code that looks like this:
> if (/someText (.+?) someMoreText (\d+)/)
> {
>       if (exists $hash{$2})
>       {
>             my $newStr=$hash{$2};
>             s/someText $newStr someMoreText/;
>       }
> }

> Sorry,
> It should be:
> s/someText (.+?) someMoreText/someText $newStr someMoreText/;

An untested first try:

if (/((someText )(.+?)( someMoreText)) (\d+)/) {
    substr $_, index($_, $1), length($1), $2 . $hash{$5} . $4
        if exists $hash{$5};

I think that when placing found text in a regex pattern, then you run
the risk that part of your found text (in someText and someMoreText)
contain regex metacharacters. I run into this problem especially when
processing text files. I therefore use substr to replace such text. I
think the s/// function is better suited for very specific and more
predictable substations. Also, here is a version with more variables
used, which I think is clearer to read:

my ($found, $p1, $p2, $p3, $number) = /((someText )(.+?)( someMoreText))
substr $_, index($_, $found), length($found), $p1 . $hash{$number} . $p3
    if defined $number and exists $hash{$number};

I welcome comments, but also refer y'all to my previous run of messages
last year about using string functions instead of regex functions for
safer and simple operations.


More information about the Perl mailing list