Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: How to use a variable in tr///

by Roy Johnson (Monsignor)
on Apr 08, 2005 at 11:30 UTC ( [id://445987]=note: print w/replies, xml ) Need Help??


in reply to Re: How to use a variable in tr///
in thread How to use a variable in tr///

There is no transliteration built into s///g. The OP's example was tr/abc/def/. s/// can't do that without some help (some kind of lookup structure, or embedding a tr command in the eval'd replacement, and in that case, why not just eval?).

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^3: How to use a variable in tr///
by merlyn (Sage) on Apr 08, 2005 at 12:43 UTC
    why not just eval?
    Because with eval, you must worry about delimiters. For example, if either string had contained "/", the eval example given elsewhere in this thread would fail. Also, eval invites disaster in a proxy-privilege environment (like CGI or other daemons).

    The lookup table isn't hard to create:

    ## initialization my $old = 'abc'; my $new = 'xyz'; my %table; @table{split //, $old} = split //, $new; my $table_re = join '|', map quotemeta reverse sort keys %table; ## the deed my $string = 'abracadabra'; $string =~ s/($table_re)/$table{$1}/g;

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      The "why not just eval?" referred to the case of embedding an eval'd tr/// in an s///e, which would be no better. But your cautions are valid. [Update: and addressed here]

      Update:
      Though for character replacement, I'd build the regex using a character class rather than alternation:

      my $table_re = sprintf '[%s]', join '', map quotemeta, keys %table;

      Caution: Contents may have been coded under pressure.
Re^3: How to use a variable in tr///
by Hena (Friar) on Apr 08, 2005 at 11:33 UTC
    Umm... right you are... Silly me :). Usually i just try to stay away from eval as it can be nasty sometimes.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://445987]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-25 22:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found