 XP is just a number PerlMonks

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

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

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 \$_ if not defined \$_;
unshift( @_, shift( @_ ) + shift( @_ ) );
'Subtract'   => sub { return \$_ if not defined \$_;
unshift( @_, shift( @_ ) - shift( @_ ) );
&{\$funk{Subtract}}},
'Multiply'   => sub { return \$_ if not defined \$_;
unshift( @_, shift( @_ ) * shift( @_ ) );
&{\$funk{Multiply}}},
'Divide'     => sub { return \$_ if not defined \$_;
unshift( @_, shift( @_ ) / shift( @_ ) );
&{\$funk{Divide}}},
'IsEqual'    => sub { for ( 1 .. \$#_ ) { return 0 if \$_ != \$_[\$
+_] } 1 },
'IsNotEqual' => sub { &{\$funk{IsEqual}} ? 0 : 1 },
);

sub Funk::TIESCALAR { bless \\$_, \$_ }
sub Funk::FETCH { \${\$_} }
sub Funk::STORE { \${\$_}=\$funk{\$_} }

my \$op;
tie \$op, 'Funk', \$op;

#Usage:
#  You now simply decide the operator you want and pass it the args:
#  my \$two = \$op->( 1, 1 );

# Test loop:
my @testArgs = ( 3, 3 );
for ( sort keys %funk )
{
\$op = \$_;
my \$answer = \$op->( @testArgs );

# print the result:
\$^A = "";
"\$_( " . 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?

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 contemplating the Monastery: (7)
As of 2021-01-26 15:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
The STEM quote I most wish I'd made is:

Results (271 votes). Check out past polls.

Notices?