Perl子程序 - 返回

时间:2014-06-19 08:46:15

标签: perl hash

以下代码是动态生成哈希。如果我不在子程序的return部分中给出else语句,我会得到

$VAR1 = {
    'fruit' => { 'apple' => 'skin' } };

但是如果我得到return声明

$VAR1 = {
    'fruit' => {
        'apple' => {
            'red' => 'skin'}
        }
    };  

这就是我想要的。
是什么造就了这一点。有人可以教育我。

sub construct_hash{
    my ($hash, $value, $head, @tail ) = @_;
    if(@tail){
        $hash = { $head => construct_hash(\%{$hash}, $value, shift @tail, @tail)} ;
    }else{
        $hash->{$head} = $value;
        return $hash;
    }
}
my %h;
my @keys = qw (fruit apple red);
my $value = 'skin';
print Dumper construct_hash(\%h, $value, shift @keys, @keys);

1 个答案:

答案 0 :(得分:1)

如果未指定从子例程返回的内容,Perl将返回所评估的最后一个表达式的值(请参阅return)。在这种情况下,这意味着子例程返回$hash->{$head}分支中的else

相关问题