Using Perl 5.26.1 under Linux I want to use a variable in the searchlist of a tr operator expression. The example on p.76 of the camel book, has two things wrong with it
a) eval " ... code ... " as shown in the book gives an eval error message. To get rid of the message I need to put the code in braces.
b) even putting the code in braces it does not work. See this:
$kards = -99; $bad="AKQJT98765432KKKK"; $card='K'; eval {print "eval is testing for $card in $bad \n"; $kards = $bad =~ tr/$card//; # tried also tr/$card/$card/; +same bad result. }; print "Num of $card in $bad = $kards \n"; $king = $bad =~ tr/K//; print "Num of K in $bad is = $king \n"; =cut Returns the following: eval is testing for K in AKQJT98765432KKKK Num of K in AKQJT98765432KKKK = 0 Num of K in AKQJT98765432KKKK is = 5 =end
Why isn't the variable $kards set to 5 as it should be?
UPDATE
The problem is that $kards should be set to the result of the eval execution, not put inside the eval execution. So this works:
$kards = -99; $bad="AKQJT98765432KKKK"; $card='K'; # this next bit works. xtr is just so I can print what eval is eva +l ing. $xtr = "$bad =~ tr/$card//;" ; $kards = eval "$bad =~ tr/$card//;"; #<====== Note the ; " ; at + the end. This seems required. print "xtr kards = $kards from eval cmd : $xtr\n"; #output: xtr kards = 5 from eval cmd : AKQJT98765432KKKK =~ tr/K// +;
but note that the code eval runs must be in double quotes, not in braces. so <code>$kards = eval {$xtr;} ; does NOT work.
In reply to tr operator in eval -- updated by pgmer6809
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |