Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: tr operator in eval

by pgmer6809 (Acolyte)
on Sep 26, 2020 at 03:54 UTC ( #11122229=note: print w/replies, xml ) Need Help??


in reply to tr operator in eval -- updated

I don't think that answer is correct. I know that tr does not interpolate, the patterns are defined at compile time according to the camel book. But the book says that you can put variables in the tr statement if you then use eval to execute the statement. the example in the book (p.76) is  eval "tr/$oldlist/$newlist/;" This does not work. this two step however does work:
# this next two step works..... $xtr = "$bad =~ tr/$card//;" ; $kards = eval "$xtr;"; print "xtr kards = $kards from eval cmd : $xtr\n"; #output: xtr kards = 5 from eval cmd : AKQJT98765432KKKK =~ tr/K// +;

Replies are listed 'Best First'.
Re^2: tr operator in eval
by AnomalousMonk (Bishop) on Sep 26, 2020 at 04:13 UTC

    Try this:

    Win8 Strawberry 5.30.3.1 (64) Sat 09/26/2020 0:05:59 C:\@Work\Perl\monks >perl use strict; use warnings; my $kards; my $bad = 'AKQJT98765432KKKK'; my $card = 'K'; eval "\$kards = \$bad =~ tr/$card//"; print "1: Num of '$card' in $bad is == $kards \n"; my $kings = $bad =~ tr/K//; print "2: Num of '$card' in $bad is == $kings \n"; __END__ 1: Num of 'K' in AKQJT98765432KKKK is == 5 2: Num of 'K' in AKQJT98765432KKKK is == 5
    Note that  \$kards \$bad in the eval string are escaped (update: and $card is not). Why?

    Update: Just read your update to the OP and I think you pretty much have the idea I was trying to get across. However, now try running the OP update code with strict and warnings enabled.


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2021-06-20 03:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (93 votes). Check out past polls.

    Notices?