in reply to Using variables with tr///

The searchlist to tr is generated at compile-time, so you can't use variables and expect them to be interpolated at run-time.

In the docs:

Note that because the translation 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 $@;
So you'll have to use eval for that. In which case, you may get better performance using s/// anyway; you'll have to benchmark it to check.

Replies are listed 'Best First'.
RE: Re: Using variables with tr///
by cwest (Friar) on Jul 17, 2000 at 16:56 UTC
    And that benchmark, quite pitifully, looks like this:
    Benchmark: timing 1000000 iterations of Eval, S_op... Eval: 140 wallclock secs (133.80 usr + 0.03 sys = 133.83 CPU) @ + 7472.17/s (n=1000000) S_op: 1 wallclock secs ( 0.81 usr + 0.00 sys = 0.81 CPU) @ 12 +34567.90/s (n=1000000)
    with:
    #!/usr/bin/perl -w use strict; $|++; use Benchmark; my $string = 'cat'; my $search = 'c'; my $replace = 'b'; timethese( 1000000, { Eval => sub { eval "$string =~ tr/$search/$replace/" + }, S_op => sub { $string =~ s/$search/$replace/g }, } );
    Man, that's ugly.
    --
    Casey