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.
|