Weird perl behaviour regarding references

ぃ、小莉子 提交于 2019-12-25 06:03:15

问题


I'm having a piece of code where in a subroutine I have a hash and I push it's reference to an array. Then I return that array:

sub subroutine1 {
    my @arr;
    my %hash = ("a", "b", "c", "d");
    foreach $key (keys %hash) {
        #I'm doing something
    }
    push @arr, \%hash;
    return @arr;
}

But later when I use the return value of the subroutine, this value is the hash reference instead of an array that contains one element which is a hash reference.

So the code above could work for me without bothering to put the hash reference in the array - I could just be returning the hash reference. It works for me either way so I choose the shorter.

My question is, why is perl doing this? Is this an expected behavior?

Here is where I am calling the subroutine: inside another subroutine. I'm also using a statistics module for which I do all the dereferencing.

sub subroutine2 {
    my @other_arr;
    for ($i = 0; $i < $val; $i++) {
         push @other_arr, subroutine1($somedata);
    }
    foreach my $key (@keys) { # the keys of the hash are available from elsewhere
        my $keystat = Statistics::Descriptive::Full->new(); 
        for (my $i =0; $i < @other_arr; $i++) {
            $keystat->add_data(${$other_arr[$i]}{$key});
        }
    }
    # other stuff
}

回答1:


Subroutines never return arrays in perl, they only return lists of (0 or more) scalars.

If you call the sub in scalar context, your return @arr will get that context and return the number of elements in @arr. If you call it in list context, the elements of @arr will be returned as a list.

If what you want is to return an array reference, do return \@arr.



来源:https://stackoverflow.com/questions/33533768/weird-perl-behaviour-regarding-references

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!