eval will evaluate strings as code. Don't eval strings from outside sources, because it's possible for someone to hand you a string to evaluate that does malicious things. But yes, Perl does let you evaluate strings as code. Doing so is hard to get right, and can expose you to a lot of security risks.

my $operator = '+'; my( $x, $y ) = (2, 5); eval "print \$x $operator \$y, qq/\\n/;";

Like most tasks in Perl, there are other ways to do it that could be safer. For example, a hash dispatch table:

my( %dispatch ) = ( '+' => sub { return $_[0] + $_[1]; }, '-' => sub { return $_[0] - $_[1]; } ); my $operation = '+'; exists $dispatch{$operation} or die "I don't know how to $operation.\n"; my( $x, $y ) = ( 2, 5 ); print $dispatch{$operation}->( $x, $y ), "\n";

This has the advantage of letting you specifically define what the user is allowed to tell your script to do. Notice how easy it is to check whether the operation requested exists in your dispatch table, and if it doesn't, inform the user what went wrong.


Dave


In reply to Re: A string interpreted as an operator by davido
in thread A string interpreted as an operator by a11

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.