如何从Perl中的sub传递和返回哈希?

use*_*896 1 perl hash reference subroutine

我一直在玩Perl中的哈希.以下按预期工作:

use strict;
use warnings;

sub cat {
        my $statsRef = shift;
        my %stats = %$statsRef;

        print $stats{"dd"};
        $stats{"dd"} = "DDD\n";
        print $stats{"dd"};
        return ("dd",%stats);
}

my %test;
$test{"dd"} = "OMG OMG\n";

my ($testStr,%output) = cat (\%test);
print $test{"dd"};

print "RETURN IS ".$output{"dd"} . " ORIG IS ". $test{"dd"};
Run Code Online (Sandbox Code Playgroud)

输出是:

OMG OMG
DDD
OMG OMG
RETURN IS DDD
 ORIG IS OMG OMG
Run Code Online (Sandbox Code Playgroud)

当我在混合中添加一个数组时,它会出错.

use strict;
use warnings;  sub cat {
        my $statsRef = shift;
        my %stats = %$statsRef;

        print $stats{"dd"};
        $stats{"dd"} = "DDD\n";
        print $stats{"dd"};         return ("dd",("AAA","AAA"),%stats); }
 my %test; $test{"dd"} = "OMG OMG\n";

my ($testStr,@testArr,%output) = cat (\%test);
print $test{"dd"};

print "RETURN IS ".$output{"dd"} . " ORIG IS ". $test{"dd"}. " TESTARR IS ". $testArr[0];
Run Code Online (Sandbox Code Playgroud)

输出是:

OMG OMG
DDD
OMG OMG
Use of uninitialized value in concatenation (.) or string at omg.pl line 20.
RETURN IS  ORIG IS OMG OMG
 TESTARR IS AAA
Run Code Online (Sandbox Code Playgroud)

为什么数组显示但哈希不是?

rai*_*7ow 7

所有列表都在Perl中自动展平.因此,赋值运算符将无法神奇地区分子例程返回的列表之间的边界.在你的情况下,这意味着@testArr将使用由给定的结果列表cat,并且%输出将不会得到它 - 因此Use of unitialized value...警告.

如果需要专门返回散列或数组,请使用引用:

return ("dd", ["AAA", "AAA"], \%stats);
Run Code Online (Sandbox Code Playgroud)

......以及之后的作业:

my ($testStr, $testArrayRef, $testHashRef) = cat(...);
my @testArray = @$testArrayRef;
my %testHash  = %$testHashRef;
Run Code Online (Sandbox Code Playgroud)