You have a string, probably code and want to find an unused character to use as a delimiter for a quote-ish operator.

For me this arose using Filter::Simple on arbitrary code.

The snippet uses tr/// backwards in a sense, the eval is required as tr's char sets are determined at compile time

TIMTOWTDI but it think this is nice, though perhaps not best.

$possibly_safe = "^!|~¦¡£\0"; $mystery_str = '$a !~ /qr^some|thing^'; $mystery_str =~ tr!/!!d; # make eval interpolation safe eval "(\$safe = \$possibly_safe) =~ tr/$mystery_str//d"; print $safe; # "¦¡£\0"
Update: There's a bit of chicken-egg action here. Can't believe I didn't notice it for 6 months.
Oh, the shame.

The old code:

$possibly_safe = "^!|~¦¡£\0"; $mystery_str = '$a !~ qr^some|thing^'; eval "(\$safe = \$possibly_safe) =~ tr/$mystery_str//d"; print $safe; # "¦¡£\0"

Replies are listed 'Best First'.
Re: Finding a safe char with tr///d
by BrowserUk (Patriarch) on Jan 29, 2003 at 00:51 UTC

    Nice++. I could have used this recently in Re: Cleaning Data Between Specified Columns (the original version at the bottom).

    If you used $possible_safe = join'', map chr, 0 .. 255; your pretty much guarenteed to find a safe char to use. (You might need to temporarially disable utf-8 if your dealing with unicode stuff I guess.)


    Examine what is said, not who speaks.

    The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

      Except you're in for some funny looks when what happens to be a "safe character" is an open paren, bracket, etc. :-)

      Makeshifts last the longest.

        Ain't that what \Q and \E are for:)... I know, I know... you'd have to monkey with the regex as well. Silly me.

        On a related note, it good to know I'm not the only one who uses control chars as temporary placeholders in strings.

        I agree that 0x7f was a bad choice in a utf-8/unicode world. Using a BOM like "\xEF\xBB\xBF" might make some sense though.


        Examine what is said, not who speaks.

        The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.