简体   繁体   English

在Perl中解引用多维数组的正确方法是什么?

[英]What is the proper way to dereference a multidimensional array in Perl?

In my code I have a multidimensional array 在我的代码中,我有一个多维数组

       $rows[$x][$y]

I am passing it to a sub function with multiple uses but at some point that function will need to remove (pop) one of the elements from the main array. 我将其传递给具有多种用途的子函数,但在某个时候该函数将需要从主数组中移除(弹出)一个元素。

I believe the proper way to pass it is by referencing it since I am passing more than just the array: 我相信传递它的正确方法是通过引用它,因为我传递的不仅仅是数组:

        filterout(\@rows, $y, $data );

But am unsure of the syntax to dereferencing it on the subroutine side. 但是我不确定在子例程方面取消引用它的语法。

Would appreciate any help, thanks as alway. 非常感谢您的帮助,谢谢。

To pop from an array reference, use 要从数组引用弹出 ,请使用

my $last = pop @$aref;

Or, in more recent Perl versions, 或者,在最新的Perl版本中,

my $last = pop $aref->@*;

To pop the inner array, you need to dereference the given element of the array reference: 要弹出内部数组,您需要取消引用数组引用的给定元素:

my $last = pop @{ $aref->[$index] };

or 要么

my $last = pop $aref->[$index]->@*;

It's an array ref pointing to an array of array refs pointing to arrays of scalars. 它是一个数组ref指向一个数组ref的数组,该数组ref指向一个标量数组。 So you'll need two de-references for a single element, one for a column and none for a row: 因此,您将需要为单个元素进行两个取消引用,对于一个列需要一个取消引用,而对于行则不需要一个:

sub filterout(\@$$) {
     my($array_ref, $y, $data) = @_;

     # single element <row>,<col>
     $array_ref->[ <row >]->[ <column> ] = ...;

     # pop column of <row>
     pop(@{ $array_ref->[ <row> ] });

     # pop row
     pop(@{ $array_ref });
}

filterout(@rows, $y, $data);

Note the prototype, which makes filterout() work like push() . 注意原型,它使filterout()push()一样工作。

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

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