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

Fellow monks, I beseech your wisdom....

I've got a file that contains strings that look like this: ITEM-####, which I would like to transform into something I can use to make Perl check against like items in our database, for example: ITEM-1234.

I thought I might achieve this with something simple like

my $string = qw(ITEM-####); $string =~ s/#/\d/g;
but to no avail. Instead I got a warning: "Unrecognized escape \d passed through."

So then I tried escaping the escape, like so:

my $string = qw(ITEM-####); $string =~ s/#/\\d/g;
But that makes my string look like this: ITEM-\\d\\d\\d\\d, which isn't what I'm looking for.

My last idea was to use qw...

my $esc = qw(\d); my $string = qw(ITEM-####); $string =~ s/#/$esc/g;
But that also got expanded to include two back slashes: ITEM-\\d\\d\\d\\d.

So now I'm stumped. Is there any way I can do this? Li'l help?

Update: FunkyMonk is right, my code does work. I was looking at it in the debugger, and apparently the debugger itself was adding the extra backslash. Thank you both.

Replies are listed 'Best First'.
Re: Escaping Escapes
by moritz (Cardinal) on Jan 29, 2008 at 20:38 UTC
    The "Unrecognized escape \d passed through." message is there to stop people who don't remember that the right hand half of a s/.../.../g expression is a string, not a regex.

    Here's one workaround:

    my $string = qq(ITEM-####); # don't use qw() here unless you want a li +st, BTW $string =~ s/#/'\d'/eg;
Re: Escaping Escapes
by FunkyMonk (Bishop) on Jan 29, 2008 at 20:58 UTC
    Your code works for me with perl 5.10 & 5.8.8 after removing qw//:
    my $string = 'ITEM-####'; print "$string\n"; $string =~ s/#/\\d/g; print "$string\n";

    output:

    ITEM-#### ITEM-\d\d\d\d