返回语句中的 perl 引用和取消引用 [英] perl reference and dereference on return statement

查看:48
本文介绍了返回语句中的 perl 引用和取消引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 perl,并且有一个与引用相关的问题.我正在研究函数 get_id.

I am learning perl, and have a problem related to references. I am working on the function get_id.

如果我返回$self->{_id},我会得到两个不能运行的数组地址(c).

If i return $self->{_id}, I will get two array address which cannot run (c).

据我所知,$a 是引用,@{$a} 是数组,@{$a}[0]会返回值 0?

In my understanding, $a is the reference and @{$a} is array and @{$a}[0] would return the value 0?

这是我第一次在stackoverflow上发帖,所以解释可能不够清楚,抱歉.

This is my first time post question on stackoverflow, therefore the explaination may not clear enough, sorry about that.

@a1 = [0]  
@a2 = [1]

my self{   
  _id = [\@a1,\@a2]; }   //given
  
sub get_id(){
   my $self      = shift;
   return  $self->{_id};
}

sub print{
    
...

   my $a = $obj -> get_id();

   my $b = @{$a}[0] * 100;    // c  (given)

..
} 

推荐答案

$arr 是对数组的引用时,@$arr@{$arr } 是它引用的数组.数组的第一个(或第零个)元素是 $arr->[0] (或 $$arr[0],但箭头符号更常见).

When $arr is a reference to an array, @$arr or @{ $arr } is the array it refers to. The first (or zeroth) element of the array is $arr->[0] (or $$arr[0], but the arrow notation is more common).

以下

my @arr = [0];

创建一个具有单个元素的数组,该元素是一个数组引用.要获得 0,您需要执行

creates an array with a single element, and that element is an array reference. To get the 0, you need to do

$arr[0]->[0]

可以缩短为

$arr[0][0]

要创建一个以 0 作为单个元素的数组,请使用

To create an array with 0 as the single element, use

my @arr = (0);

顺便说一句,不要使用 $a$b,它们是 排序.使用 my 词法化它们可能会导致难以调试的错误.

BTW, don't use $a and $b, they are special variables used in sort. Lexicalising them with my can lead to bugs that are hard to debug.

这篇关于返回语句中的 perl 引用和取消引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆