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

I'm testing the following using Perl 5.24.0.

Observe the strange behavior of "tr" when single-quotes are used as delimiters:

Input:

#!/usr/bin/perl -w -- $s = '-abcdefgh'; $s =~ tr/abc//cd; print "s = '$s'\n"; $s = '-abcdefgh'; $s =~ tr/a-c//cd; print "s = '$s'\n"; $s = '-abcdefgh'; $s =~ tr'abc''cd; print "s = '$s'\n"; $s = '-abcdefgh'; $s =~ tr'a-c''cd; print "s = '$s'\n";

Output:

s = 'abc' s = 'abc' s = 'abc' s = '-ac'

Effectively, character ranges get disabled when this specific character is used as the delimiter, and "-" becomes just one more literal character in the SEARCHLIST. Is this outcome intended? Did I miss where this special case is documented? I would expect an exception like that to be listed in the doc (tr leads you to Quote Like Operators; scroll down a bit to the part on tr and y).

Replies are listed 'Best First'.
Re: undocumented tr special behavior for single-quoted transform
by LanX (Saint) on Jan 06, 2018 at 10:33 UTC
    Single quotes inhibit interpolation

    From the same perldoc perlop#Gory-details-of-parsing-quoted-constructs

  • '' , q//, tr''', y''', the replacement of s'''

    The only interpolation is removal of \ from pairs of \\ . Therefore "-" in tr''' and y''' is treated literally as a hyphen and no character range is available. \1 in the replacement of s''' does not work as $1 .

  • HTH

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Wikisyntax for the Monastery

      Thank you for pointing out what I missed. My only remaining concern is this phrase at the top of that section:

      Interpolation

      The next step is interpolation in the text obtained, which is now delimiter-independent. ...

      I think this should say "delimiter-dependent".

        Well personally I consider the perldocs to be quite messy.

        Everything is documented, but you need to be an expert to find it and cope with various styles of various authors from various eras.

        For instance I only found this part by searching for the string tr'.

        (But I knew that delimiter ' has special meanings for various operators)

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Wikisyntax for the Monastery