On Tue, 10 Jul 2007, Chas Owens wrote:

On 7/10/07, Vincent Li <[EMAIL PROTECTED]> wrote:

 I am trying to experiment a simple perl math caculation script I wrote:

 #!/usr/bin/perl
 use strict;
 use warnings;

 my %operator = (
      minus => '-',
      add => '+',
      multiply => '*',
      divide => '/',
) ;

 my $big = 5;
 my $small = 2;

 for (values %operator) {

 my $result = $big  $_ $small;

 print "$result\n";

}

 I know the "my $result = $big $_ $small" is not valid perl expression,and
 may look stupid :) but you get the idea that I want to achieve that
 because the operator is stored in a varible and unknown to me. I guess
 there is other way around, I am just not aware of.

 Thanks in advance

 Vincent

A better way to construct this is with anonymous subroutines:

#!/usr/bin/perl
use strict;
use warnings;

my %operator = (
   minus    => sub { (shift) - shift },
   add      => sub { (shift) + shift },
   multiply => sub { (shift) * shift },
   divide   => sub { (shift) / shift },
);

my $big = 5;
my $small = 2;

for my $key (keys %operator) {
   my $op = $operator{$key};
   my $result = $op->($big, $small);
   print "$key: $big and $small = $result\n";
}


Ah, Thanks guys, that is what I want.

Vincent

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to