(可选)从子例程返回数组还是哈希?

时间:2015-08-11 18:07:43

标签: arrays perl hash subroutine

如何从子例程返回哈希值或数组,具体取决于用户想要的内容?

基本上我想要一个子程序,当被要求返回一个哈希时,它会返回一个哈希值,但当被要求返回一个数组时,它将返回一个包含该哈希键的数组。

例如:

my %hash = foo();

my @array = foo();  # @array contains "keys %hash"

# pseudo code
sub foo {

     # Define a hash
     my %hash = (
         'key1' => 'val1',
         'key2' => 'val2',
         'key3' => 'val3',
     );

     # I know this is not valid Perl code, but it represents what I want.
     return keys %hash if wantarray;
     return %hash      if wanthash;
}

我知道您可以使用wantarray来确定是否要返回数组或标量,但我需要类似的功能来选择性地返回数组或散列。

2 个答案:

答案 0 :(得分:2)

您的子程序可能会返回数组或reference to hash

my @array = foo();  # @array contains "keys %hash"
my $hash_reference = foo();

print $array[0],"\n"; # keys returned by foo are in random order
print $hash_reference->{key1},"\n";


# sample code
sub foo {

     # Define a hash
     my %hash = (
         'key1' => 'val1',
         'key2' => 'val2',
         'key3' => 'val3',
     );

     if( wantarray) {
         return keys %hash;
     }else{
         return \%hash
     }
}

答案 1 :(得分:1)

只需添加一个参数,以便在传入参数时返回键:

sub foo {
    my $want_keys = shift;

    my %hash = (a => 1, b => 2, c => 3, );

    return keys %hash if $want_keys;

    return %hash;
}

my %hash = foo();

my @keys = foo(1); # or foo('keys');

唯一的另一种方法是在需要列表时返回散列,否则返回键的数组引用,这意味着调用者之后必须取消引用:

sub foo {
    my %hash = (a=>1, b=>2);
    return %hash if wantarray;
    return [keys %hash];
}

my $keys = foo();
my %hash = foo();