On Tue, 10 Jul 2007 11:32:54 -0700 (PDT)
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
> 

you could also do:

my %operator = (
        minus => sub { return $_[0] - $_[1] },
        add => sub { return $_[0] + $_[1] },
        multiply => sub { return $_[0] / $_[1] },
        divide => sub { return $_[0] * $_[1] },
);

foreach (values %operator)  {
my $result = &{$_}($big,$small);
print $result;
}

thats a different concept, but usually you want to avoid eval, since you could 
open a door for code injection.

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


Reply via email to