G'day abualiga,
As ++NetWallah points out, eval can be unsafe.
If your eval code started off like this:
$ perl -Mstrict -Mwarnings -E 'say eval for map { "12 $_ 3" } qw{+ - * + / % **}' 15 9 36 4 0 1728
Using a despatch table like this is a safer option.
$ perl -Mstrict -Mwarnings -E ' my %op_hash = ( q{+} => sub { $_[0] + $_[1] }, q{-} => sub { $_[0] - $_[1] }, q{*} => sub { $_[0] * $_[1] }, q{/} => sub { $_[0] / $_[1] }, q{%} => sub { $_[0] % $_[1] }, q{**} => sub { $_[0] ** $_[1] }, ); say for map { $op_hash{$_}->(12, 3) } qw{+ - * / % **}; ' 15 9 36 4 0 1728
And you can add your own sanity checks:
$ perl -Mstrict -Mwarnings -E ' my %op_hash = ( q{+} => sub { $_[0] + $_[1] }, q{-} => sub { $_[0] - $_[1] }, q{*} => sub { $_[0] * $_[1] }, q{/} => sub { die "Divide by zero!" if $_[1] == 0; $_[0] / +$_[1] }, q{%} => sub { $_[0] % $_[1] }, q{**} => sub { $_[0] ** $_[1] }, ); say for map { $op_hash{$_}->(12, 0) } qw{+ - * / % **}; ' Divide by zero! at -e line 6.
I don't know what context you're intending to use this in: the overload pragma may be of some use.
Update: s/unsafe:/unsafe./ and added "If your eval code started off like this: "
-- Ken
In reply to Re: interpolating operators within strings
by kcott
in thread interpolating operators within strings
by abualiga
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |