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

This should be easy, but I'm haven't stumbled upon the answer yet.

I can successfully use the tr/// operator if both search list and replacement list are hardcoded. ie.

my $s =~ tr/abcd/ABCD/;
But the following does not produce the same result:
my $replace = 'ABCD'; my $s =~ tr/abcd/$replace/;
Any clarification you can provide would be greatly appreciated. Thanks.

Replies are listed 'Best First'.
Re: configurable tr///?
by MidLifeXis (Monsignor) on Jan 27, 2010 at 22:42 UTC

    From the docs for tr...

    Because the transliteration table is built at compile time, neither the SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote interpolation. That means that if you want to use variables, you must use an eval():
    eval "tr/$oldlist/$newlist/"; die $@ if $@; eval "tr/$oldlist/$newlist/, 1" or die $@;

    It is said that "only perl can parse Perl." I don't even come close until my 3rd cup of coffee. --MidLifeXis

Re: configurable tr///?
by toolic (Bishop) on Jan 27, 2010 at 22:40 UTC
    tr does not interpolate variables. You must use eval.
Re: configurable tr///?
by Anonymous Monk on Jan 27, 2010 at 22:41 UTC
Re: configurable tr///?
by umasuresh (Hermit) on Jan 27, 2010 at 23:36 UTC
    I had the same question a while back but didn't post it here. Thanks for posting it and all the monks for their answers.