perl子例程知道是否传递散列或单个值

时间:2014-02-02 20:59:08

标签: perl hash arguments subroutine

我正在编写一个perl子例程,我希望能够灵活地将值作为哈希值传递,或者作为单个值传递。我想知道如何将参数传递给子例程,以便我可以单独处理这些情况。例如:

#case 1, pass in hash
test(arg1 => 'test', arg2 => 'test2');

#case 2, just pass in single values
test('test', 'test2');

sub test { 
    #if values passed in as a hash, handle one way
    if(...) { 

    }
    #if values passed in as single values, do something else
    else { 

    }
}

有没有办法在perl中检测到这个?谢谢!

2 个答案:

答案 0 :(得分:4)

使用匿名HASH参考我会做什么:

#case 1, pass in hash
test({arg1 => 'test', arg2 => 'test2'});

#case 2, just pass in single values
test('test', 'test2');

sub test { 
    my $arg = shift;

    if(ref $arg eq 'HASH') { 
        ...;
    }
    #if values passed in as single values, do something else
    else { 
         ...;
    }
}

请参阅
http://perldoc.perl.org/perlref.html
http://perldoc.perl.org/perlreftut.html

答案 1 :(得分:1)

另一个答案是完全没问题(而且我已经加倍了),但是本着“更多那种方式去做它”的精神,以及为了拉扯我自己的商品......

use v5.14;
use strict;
use warnings;
use Kavorka qw( multi fun );

# define a function with positional arguments
multi fun test (Str $arg1, Str $arg2) {
   say "positional";
   say "\$arg1 is $arg1";
   say "\$arg2 is $arg2";
}

# define a function with named arguments
multi fun test (Str :$arg1, Str :$arg2) {
   say "named";
   say "\$arg1 is $arg1";
   say "\$arg2 is $arg2";
}

# Call the function with positional arguments
test('foo', 'bar');

# Call the function with named arguments
test(arg1 => 'foo', arg2 => 'bar');

# Call the function with named arguments again
test({ arg1 => 'foo', arg2 => 'bar' });