1

我一直在玩 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

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

4

2 回答 2

7

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

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

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

...后来,在作业中:

my ($testStr, $testArrayRef, $testHashRef) = cat(...);
my @testArray = @$testArrayRef;
my %testHash  = %$testHashRef;
于 2012-06-19T15:59:06.543 回答
4

除了raina77ow 的答案,我强烈建议只传递参考,而不是从类型转换为参考然后再返回。它更容易阅读并且编码的麻烦更少(恕我直言)

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";
于 2012-06-19T16:07:49.173 回答