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

时间:2012-06-19 15:54:52

标签: 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"};

输出是:

OMG OMG
DDD
OMG OMG
RETURN IS DDD
 ORIG IS OMG OMG

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

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];

输出结果为:

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

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

2 个答案:

答案 0 :(得分:7)

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

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

return ("dd", ["AAA", "AAA"], \%stats);

......以后,在作业中:

my ($testStr, $testArrayRef, $testHashRef) = cat(...);
my @testArray = @$testArrayRef;
my %testHash  = %$testHashRef;

答案 1 :(得分:4)

除了raina77ow的回答之外,我强烈建议只传递引用,而不是从类型转换为引用再返回。它更容易阅读,而且代码更少麻烦(imho)

use Data::Dumper;
use strict;
use warnings;
sub cat {
    my $statsRef = shift;
    print $statsRef->{"dd"} ;
    $statsRef->{"dd"} = "DDD\n";
    print $statsRef->{"dd"} ;
    return ("dd",["AAA","AAA"],$statsRef); 
}

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

my ( $var, $arrRef, $hashRef ) = cat($test) ;

print "var " . Dumper($var) . "\n" ;
print "arrRef " . Dumper($arrRef) . "\n";
print "hashRef " . Dumper($hashRef) . "\n";