in reply to problem with substitute in regexp

my %replace = ('111'=>bar, '222'=>world, '333'=>perl); my $find = join "|", sort keys %replace; my $str = "f111,f222,f333"; $str =~ s/f([0-9]+)/$replace{$1}/g; print "$str\n";
output
bar,world,perl


just as moritz said!!!

Replies are listed 'Best First'.
Re^2: problem with substitute in regexp
by roboticus (Chancellor) on Nov 10, 2011 at 11:37 UTC

    ansh batra:

    While it *will* give the proper output, it's rather ugly, and would give a poor example for other initiates. I'd suggest a little tune-up:

    • If you compile under strict, it will report bare words it the first line.
    • The second line does nothing, so it just makes things harder to read.
    • You're capturing the digits group, but ignoring the group. Remove the parenthesis.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

    Update: AnomalousMonk pointed out my blindness: he *is* using the capture group. D'oh!

      roboticus
      #! /usr/bin/perl -w use strict; my %replace = ('111'=>"bar", '222'=>"world", '333'=>"perl"); my $str = "f111,f222,f333"; $str =~ s/f([0-9]+)/$replace{$1}/g; print "$str\n";

      • used strict and warnings
      • forgot to remove the second line . it was there in original code
      • dint get your third point
      • and sorry for these mistakes . i dont know how i am into bad/lazy programming habits. thanks for reminding

        ansh batra:

        For the third point, I was just meaning that you don't need the parenthesis. But I was totally wrong (as AnomalousMonk pointed out to me), as I missed that you *are* using the capture group as the key to the hash for your replacement. As you can see, we *all* make mistakes! ;^)

        Your latest version looks good.

        ...roboticus

        When your only tool is a hammer, all problems look like your thumb.

Re^2: problem with substitute in regexp
by bluray (Sexton) on Nov 11, 2011 at 16:36 UTC
    Hi,

    Even if  my $find=join "|", sort keys %replace; is removed, the output I am getting is the same. So, just wonder the use of that in this context since this is already sorted.