#!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.