in reply to Simple add and multiply subroutines

Not that I'm disagreeing with all the errors/problems other people have pointed out, but this is really the canonical case for using a dispatch table.

#!/usr/bin/perl -w use strict; my $op = shift or die "You must specify an operation followed by numbe +rs.\n"; die "Non-numeric input.\n" if grep /\D/, @ARGV; my %perform = ( add => sub { local $" = "+"; eval "@ARGV"; }, multiply => sub { local $" = "*"; eval "@ARGV"; }, ); die "Invalid operation.\n" unless defined $perform{$op}; print $perform{$op}->();

-- 
Human history becomes more and more a race between education and catastrophe. -- HG Wells

Replies are listed 'Best First'.
Re^2: Simple add and multiply subroutines
by jwkrahn (Abbot) on Apr 08, 2008 at 06:35 UTC

    Dispatch table - yes, string eval - OMG NO! especially not for a beginner!

    Your grep test for "Non-numeric input" won't accept floating point numbers or negative numbers.

      Nor engineering notation, nor imaginary numbers, nor Roman numerals either. It will, however, handle the integers as shown in the original request. :)

      String eval... OK, you're right. Easy enough to fix, and I see (behind the cut tags) that the poster just before me already did that.

      
      -- 
      Human history becomes more and more a race between education and catastrophe. -- HG Wells