in reply to Returning transliteration from eval

( eval "( $string1 | $string2 ) =~ tr[$n1][$n1]" ), ( eval "( ~$string1 & $string2 ) =~ tr[\$ndiff][\$ndiff]" +), ( eval "( $string1 & ~$string2 ) =~ tr[\$ndiff][\$ndiff]" +), ( eval "( $string1 & $string2 ) =~ tr[$n2][$n2]" ) ),

You need more backslashes :)

( eval "( \$string1 | \$string2 ) =~ tr[$n1][$n1]" ), ( eval "( ~\$string1 & \$string2 ) =~ tr[\\$ndiff][\\$ndif +f]" ), ( eval "( \$string1 & ~\$string2 ) =~ tr[\\$ndiff][\\$ndif +f]" ), ( eval "( \$string1 & \$string2 ) =~ tr[$n2][$n2]" ) ),

In other words, you don't want $string1 and $string2 to be interpolated, but you do want $ndiff interpolated, and prefixed with a backslash, which itself must be escaped.

As you have it, you're eval'ing code like

~0000 & 0101 ) =~ tr[$ndiff][$ndiff]

but you'd want

~$string1 & $string2 ) =~ tr[\1][\1]

In case of doubt, when string eval doesn't do what you expect, for debugging purposes always print out the string to be eval'ed...

Replies are listed 'Best First'.
Re^2: Returning transliteration from eval
by albert (Monk) on Jan 28, 2011 at 16:39 UTC
    Thanks. I guessed it was a backslash issue, but hadn't stumbled to that one.

    You've made a light bulb go off, and I'm much clearer on eval now. Point on printing out the eval is well-taken, and will use it in the future.

      Habitual backslasher ikegami might have something to say about it but single (non-interpolating/literal) quotes can be a bit easier to read.

      ( eval '( $string1 | $string2 ) =~ tr[$n1][$n1]' ), ( eval '( ~$string1 & $string2 ) =~ tr[$ndiff][$ndiff]' ), ( eval '( $string1 & ~$string2 ) =~ tr[$ndiff][$ndiff]' ), ( eval '( $string1 & $string2 ) =~ tr[$n2][$n2]' ) ),

      Update: my eyes are getting old. I missed the interpolation in the trs.

        ...but that wouldn't interpolate where interpoplation is needed ($n1, $n2 and $ndiff).

        (With single quotes, the resulting code such as ( ~$string1 & $string2 ) =~ tr[$ndiff][$ndiff] would count the total number of characters belonging to the set '$','n','d','i','f' — which is not what is intended here.)

        print 'f $ d d i $ n' =~ tr/$ndiff/$ndiff/; # 7

        (Update: added sample code for the downvoter, who apparently didn't get it.)