Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all I have the following code
foreach $key (keys %method) { $message_ref->[0]=~s/$key/$method{$key}/; }
$message_ref->[0] contains a number between 1 and 100 and possibly some other text.I want this number to be replaced by the equivalent text listed in %method. However if the number is 23, and the for loop yields a key equal to 2 then $message_ref->[0] becomes equal to the text equivalent to 2 with the 3 at the end. Does anyone know how I can ensure 23 will only be replaced with 23's text and not 2's? Any help at all would be greatly appreciated ASAP Cheers.

Edit: Added <code> tags. larsen

Replies are listed 'Best First'.
Re: Matching and replacing
by benn (Vicar) on Mar 25, 2003 at 14:00 UTC
    You can use word-boundary anchors like this...
    $message_ref->[0] =~ s/\b$key\b/$method{$key}/;
    Cheers.
Re: Matching and replacing
by davorg (Chancellor) on Mar 25, 2003 at 14:02 UTC

    One quick and dirty solution would be to ensure that higher (and therefore longer) keys are substituted first.

    foreach $key (sort { $b <=> $a } keys %method) { $message_ref->[0] =~ s/$key/$method{$key}/; }
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Matching and replacing
by robartes (Priest) on Mar 25, 2003 at 17:13 UTC
    Not directly related to your immediate question (which has already been answered adequately by other monks), but if your $key is always numerical, you might gain some speed by using an array instead of a hash. It's up to you to decide whether it is worth refactoring your code :)
    $message_ref->[0]=~s/\b$_\b/$method[$_]/ for @method;
    Note that:
    • This code is untested.
    • You can also use davorg's method by sorting @method.

    Update: removed 'e' modifier from regexp - not needed.

    CU
    Robartes-