Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Array of operators ...

by tobyink (Abbot)
on Sep 12, 2013 at 20:18 UTC ( #1053793=note: print w/replies, xml ) Need Help??


in reply to Array of operators ...

You can't create a reference to an operator, but you can create a reference to a sub.

my @term = (4, 5); my @ops = ( [ '+' => sub { $_[0] + $_[1] } ], [ '-' => sub { $_[0] - $_[1] } ], [ '*' => sub { $_[0] * $_[1] } ], [ '/' => sub { $_[0] / $_[1] } ], ); for my $op (@ops) { my ($symbol, $coderef) = @$op; printf( "%s %s %s = %s\n", $term[0], $symbol, $term[1], $coderef->(@term), ); }

That's arguably a little cleaner and safer than using eval, but eval might be simpler and may be sufficient for your needs.

use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Replies are listed 'Best First'.
Re^2: Array of operators ...
by TJPride (Pilgrim) on Sep 12, 2013 at 22:07 UTC
    I used this exact approach when I was duplicating the PHP "date" function in Perl. Given, as you go to longer mathematical expressions, it'll probably be simpler to just pattern match for non-allowed characters (anything that isn't a number or limited set of operators) and then eval if everything looks ok.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1053793]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2016-12-02 18:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (47 votes). Check out past polls.