简体   繁体   English

数组-如何动态取消对数组的引用? (Perl)

[英]Arrays - how to dynamically dereference array? (Perl)

When I do: 当我做:

my (@array1, @array2) = get_returns();

The get_return function returns a list of arbitrary elements. get_return函数返回任意元素的列表。 In this particular case, the get_returns function returns a list of two arrays. 在这种特殊情况下, get_returns函数返回两个数组的列表。 However this stores all the contents of the return into array1 instead of splitting the two arrays up. 但是,这会将返回的所有内容存储到array1而不是拆分两个数组。

I am not sure how to dereference the arrays through the function I am calling using something explicit like @{$arr} . 我不确定如何通过使用类似@{$arr}显式调用函数来解除对数组的引用。 I am doing a form of RPC calling where the returns (and their types) are not known beforehand by the program. 我正在做一种RPC调用的形式,其中程序事先不知道返回值(及其类型)。 I also do not want to have to dereference the array outside of the function call. 我也不想在函数调用之外取消对数组的引用。 Is there a workaround to dynamically dereference the arrays? 是否有解决方法来动态取消对数组的引用?

Update 更新资料

In the get_returns function, I am sending and receiving a response from a server. get_returns函数中,我正在发送和接收来自服务器的响应。 This returns a JSON table where the "returns" field is an array of returns: 这将返回一个JSON表,其中的“ returns”字段是一个返回数组:

sub get_returns {
    my $data = remotely_call_some_function();
    $t = $json->decode($data);
    my @returns = @{$t->{"returns"}};
    return @returns;
}

the get_returns function returns a list of two arrays. get_returns函数返回两个数组的列表。

No, it returns a number of scalars. 不,它返回多个标量。 That's the only thing a sub can return. 这是sub可以返回的唯一内容。 In this specific case, it returns two references to arrays. 在这种特定情况下,它将返回对数组的两个引用。 You could grab them as follows: 您可以按以下方式抓取它们:

my ($array1, $array2) = get_returns();

I also do not want to have to dereference the array outside of the function 我也不想在函数外部取消引用数组

To do that, you'd need named arrays outside of get_returns for get_returns to populate. 为此,您需要在get_returns以外的命名数组中填充get_returns

sub get_returns {
    my $data_json = remotely_call_some_function();
    my $data = $json->decode($data_json);
    my $returns = $data->{returns};
    @{ $_[0] } = $returns->[0];
    @{ $_[1] } = $returns->[1];
}

get_returns(\my @array1, \my @array2);

I recommend against this. 我建议不要这样做。

Per a comment that includes Data::Dumper output in the OP, you're receiving $VAR1 = [['e1', 'e2'], ['e1', 'e2']] . 根据OP中包含Data::Dumper输出的注释,您将收到$VAR1 = [['e1', 'e2'], ['e1', 'e2']] That's an array of array references. 那是一个数组引用数组。 Here's how you can receive and then dereference the inner arefs: 这是您如何接收然后取消引用内部区域的方法:

my ($aref1, $aref2) = get_returns();

# deref and print each element of an array reference

for my $elem (@$aref1){
    print "$elem\n";
}

# get a single element

my $x = $aref2->[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM