Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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?


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

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
and the web crawler heard nothing...

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

    Results (94 votes). Check out past polls.