in reply to Re: doing tr/// on-the-fly?
in thread doing tr/// on-the-fly?

Thanks. That helps some.

Changing the code to the following:

#!/usr/bin/env perl use strict; my $s = 'eabcde'; my $t = $s; print "$t\n"; $t =~ tr/abcd/efgh/; print "$t\n"; print '*' x 4, $/; my $search = 'abcd'; my $replace = 'efgh'; $t = $s; print "$t\n"; eval { $t =~ tr/$search/$replace/; }; print "$search\n"; print "$replace\n"; print "$t\n";
Gives me the results:
eabcde eefghe **** eabcde abcd efgh epbade
I don't see why the results of tr/// differ.

Replies are listed 'Best First'.
Re^3: doing tr/// on-the-fly?
by ikegami (Patriarch) on Mar 18, 2010 at 04:27 UTC
    eval BLOCK and eval EXPR, despite the similarity in name, are very different functions. You might know the former as try, an exception catching block. The latter also catches exceptions, but its goal is to parse and run dynamically generated Perl code.
Re^3: doing tr/// on-the-fly?
by Anonymous Monk on Mar 18, 2010 at 01:31 UTC
    Okay, I didn't duplicate exactly what you said. The following code:
    #!/usr/bin/env perl use strict; my $s = 'eabcde'; my $t = $s; print "$t\n"; $t =~ tr/abcd/efgh/; print "$t\n"; print '*' x 4, $/; my $search = 'abcd'; my $replace = 'efgh'; $t = $s; print "$t\n"; eval "\$t =~ tr/$search/$replace/"; print "$search\n"; print "$replace\n"; print "$t\n";
    ...does give me the expected results:
    eabcde eefghe **** eabcde abcd efgh eefghe
    Why the difference?

      Because:

      eval { $t =~ tr/$search/$replace/; };

      is just normal perl code where there is no interpolation so '$' is replaced with '$' and 's' is replaced with 'r' and 'e' is replaced with 'e' and 'a' is replaced with 'p', etc. while using string eval interpolates the variables $search and $replace.