a11 has asked for the wisdom of the Perl Monks concerning the following question:

Hi yet again,
(last question for now!)
I was just wondering is it possible to have a string interpreted as an operator? For example, as a condition?? Say, $string=">=" or $string="ne"?
I understand that it's pretty unlikely to be possible, but Perl does loads of things completely unbelievable to me as an ex-C programmer, so I thought I'd ask just in case...
I can only think of a script that writes a perl-script into a file and then executes it... Not that bad after all, but maybe there is something better?
Thanks!!!

Replies are listed 'Best First'.
Re: A string interpreted as an operator
by davido (Cardinal) on Jul 14, 2006 at 15:59 UTC

    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

Re: A string interpreted as an operator
by muntfish (Chaplain) on Jul 14, 2006 at 16:00 UTC

    A perl script can generate and execute perl code itself, inline, without having to write to a file and execute that.

    Have a look at eval.


    s^^unp(;75N=&9I<V@`ack(u,^;s|\(.+\`|"$`$'\"$&\"\)"|ee;/m.+h/&&print$&
Re: A string interpreted as an operator
by ikegami (Patriarch) on Jul 14, 2006 at 21:34 UTC
Re: A string interpreted as an operator
by diotalevi (Canon) on Jul 14, 2006 at 21:06 UTC

    See also overload.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊