有没有办法从Perl的max函数返回变量名?

时间:2017-04-17 17:43:31

标签: perl max

使用Perl的List::Util模块,有没有办法从max()返回变量名和实际值?例如:

my $a = 1;
my $b = 2;
my $c = 3;

my $max = max($a,$b,$c);

如何获得3,以及变量名$c?我的意图是做一些事情:

#psuedocode
if(max is from $c) {
print "Max from C";
}

或者也许这样做的方法没有List::Util

1 个答案:

答案 0 :(得分:3)

sub pairmax {
    my $name = shift;
    my $max  = shift;
    while (@_) {
       if ($_[1] > $max) {
          $name = shift;
          $max  = shift;
       } else {
          shift;
          shift;
       }
    }

    return wantarray ? ($name,$max) : $name;
}

my $key_of_max = pairmax( a=>$a, b=>$b, c=>$c );

my ($key_of_max, $max) = pairmax( a=>$a, b=>$b, c=>$c );