[Israel.pm] regex substitue with lookup table

David Baird david.baird at homemail.com
Sun Mar 28 01:15:49 PST 2004

Corrected response:

An tested 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 substitutions. Also, here is a version with more variables
used, which I think is clearer to read:

my ($found, $p1, $p2, $p3, $number) =
    /((someText )(.+?)( someMoreText)) (\d+)/;
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