推到数组引用 [英] Push to array reference

查看:118
本文介绍了推到数组引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Perl数组引用?谷歌搜索建议我先尊重阵列,但是这并不能真正发挥作用。它推到deferenced阵列,未引用的阵列

Is it possible to push to an array reference in Perl? Googling has suggested I deference the array first, but this doesn't really work. It pushes to the deferenced array, not the referenced array.

例如,

my @a = ();

my $a_ref = [@a];

push(@$a_ref,"hello");

print $a[0];

@a 将不会被更新,这code将失败,因为该数组仍然是空的。

@a will not be updated and this code will fail because the array is still empty

(我还在学习Perl的引用,所以这可能是一个非常简单的问题。很抱歉,如果这样)

(I'm still learning Perl references, so this might be an incredibly simple question. Sorry if so)

推荐答案

它可以帮助想在内存方面地址,而不是变量名。

It might help to think in terms of memory addresses instead of variable names.

my @a = ();       # Set aside memory address 123 for a list.

my $a_ref = [@a]; # Square brackets set aside memory address 456.
                  # @a COPIES the stuff from address 123 to 456.

push(@$a_ref,"hello"); # Push a string into address 456.

print $a[0]; # Print address 123.

的字符串进入一不同的存储器位置。

The string went into a different memory location.

相反, $ a_ref 变量指向列表的存储位置 @a 影响记忆位置123.由于 @a 也指存储位置123,它的价值也随之变化。

Instead, point the $a_ref variable to the memory location of list @a. push affects memory location 123. Since @a also refers to memory location 123, its value also changes.

my $a_ref = \@a;       # Point $a_ref to address 123. 
push(@$a_ref,"hello"); # Push a string into address 123.
print $a[0];           # Print address 123.

这篇关于推到数组引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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