Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^2: Is it possible to store an arthimetric operator in a variable?

by Adam (Vicar)
on Jul 19, 2005 at 17:27 UTC ( #476190=note: print w/ replies, xml ) Need Help??


in reply to Re: Is it possible to store an arthimetric operator in a variable?
in thread Is it possible to store an arthimetric operator in a variable?

For those curious, this is how I might do it using tie.

#!perl -w use strict; # You could write any kind of function you wanted... # I thought I'd go for multi-operand functions. my %funk; %funk = ( 'Add' => sub { return $_[0] if not defined $_[1]; unshift( @_, shift( @_ ) + shift( @_ ) ); &{$funk{Add}}}, 'Subtract' => sub { return $_[0] if not defined $_[1]; unshift( @_, shift( @_ ) - shift( @_ ) ); &{$funk{Subtract}}}, 'Multiply' => sub { return $_[0] if not defined $_[1]; unshift( @_, shift( @_ ) * shift( @_ ) ); &{$funk{Multiply}}}, 'Divide' => sub { return $_[0] if not defined $_[1]; unshift( @_, shift( @_ ) / shift( @_ ) ); &{$funk{Divide}}}, 'IsEqual' => sub { for ( 1 .. $#_ ) { return 0 if $_[0] != $_[$ +_] } 1 }, 'IsNotEqual' => sub { &{$funk{IsEqual}} ? 0 : 1 }, ); sub Funk::TIESCALAR { bless \$_[1], $_[0] } sub Funk::FETCH { ${$_[0]} } sub Funk::STORE { ${$_[0]}=$funk{$_[1]} } my $op; tie $op, 'Funk', $op; #Usage: # You now simply decide the operator you want and pass it the args: # $op = 'Add'; # my $two = $op->( 1, 1 ); # Test loop: my @testArgs = ( 3, 3 ); for ( sort keys %funk ) { $op = $_; my $answer = $op->( @testArgs ); # print the result: $^A = ""; formline "\@>>>>>>>>>>>>>>>>>>>>> = $answer\n", "$_( " . join( ', ', @testArgs ) . " )"; print $^A; } __END__
Additional code could be added to do argument checking and the like.


Comment on Re^2: Is it possible to store an arthimetric operator in a variable?
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://476190]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2015-07-05 15:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (67 votes), past polls