Except, even that's too much repetition.use List::Util qw( reduce ); my %ops = ( add => sub { reduce { $a + $b } @_ }, multiply => sub { reduce { $a * $b } @_ }, # etc ... ); my $op = shift or die "You must specify an operation followed by numbe +rs.\n"; die "Non-numeric input.\n" if grep /\D/, @ARGV; die "Invalid operation.\n" unless exists $ops{$op}; print "$op (@ARGV)= ". $ops->(@ARGV) . "\n";
Learn CPAN, young padawan. It is rare that someone hasn't already solved at least part of whatever it is you're looking at. Writing core Perl for more than 50% of a program is a sign of "I don't know CPAN," not brilliance.use List::Util qw( reduce ); my %ops = ( add => '+', multiply => '*', # etc ... ); %ops = map { $_ => eval q(sub { reduce { $a ) . $ops{$_} . q( $b } @_ }) } keys %ops; # And so forth.
Update: Fixed typo s/op/ops/ inside eval.
In reply to Re^2: Simple add and multiply subroutines
by dragonchild
in thread Simple add and multiply subroutines
by negzero7
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |