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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.