可选地 return 来自子例程的数组或散列?

Optionally return either an array or a hash from a subroutine?

如何根据用户的需要,return 从子例程中生成散列或数组?

基本上我想要一个子程序,当被要求return一个散列时它会return一个散列,但是当被要求return一个数组时它会return 一个包含该散列键的数组。

例如:

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 来确定是要对数组还是标量进行 returned,但我需要类似的功能来选择性地 returning 数组或哈希。

只需添加一个参数,这样如果它被传入,它 returns keys:

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();

您的子例程可以 return 数组或 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
     }
}