Reference in Perl

使用reference的目的

1. 创建@_,会拷贝整个array或hash,浪费内存空间

2.@_在子程序中是传入数据的拷贝,无法对修改传入的数据

与C语言对比的话,Perl的reference更像指针,或者C++的引用

 

the backslash(/) character is also the "take a reference to" operator.

反斜线符号还是引用操作符

 

-------------------------------------------------------------------------------------------

1.Reference to Array

对数组的引用

my @array = qw(a b c d e f g);

my $array_ref = /@array;

 

dereference to array 

解引用整体数组

@{$array_ref}

 

引用数组元素

$array[1]

${$array_ref}[1]

 

很多情况下,需要解引用的数组引用是一个标量值,如@{$array_ref}或${$array_ref}[1]

这种情况下,可以丢弃{},即@$array_ref或$$array_ref[1]

-------------------------------------------------------------------------------------------

Reference to Hash

对哈希的引用

my %hash = (

a => 1,

b => 2,

c => 3,

d => 4,

);

my $hash_ref = /%hash;

 

my $elem0 = $hash{'a'};

my $elem0 = ${$hash_ref}{'a'};

my $elem0 = $$hash_ref{'a'};

 

my @keys = keys %{$hash_ref};

my @keys = keys %$hash_ref;

 

引用哈希表中的值

my $val = $hash_ref->{'a'};

 

 

VariableInstantiating
the scalar
Instantiating a
reference to it
Referencing itDereferencing itAccessing an element
$scalar$scalar = "steve";
$ref = /"steve";
$ref = /$scalar$$ref or
${$ref}
N/A
@list@list = ("steve", "fred");
$ref = ["steve", "fred"];
$ref = /@list@{$ref}${$ref}[3]
$ref->[3]
%hash%hash = ("name" => "steve",
   "job" => "Troubleshooter");
$hash = {"name" => "steve",
   "job" => "Troubleshooter"};
$ref = /%hash%{$ref}${$ref}{"president"}
$ref->{"president"}
FILE

$ref = /*FILE{$ref} or scalar <$ref>

引用自http://www.troubleshooters.com/codecorn/littperl/perlsub.htm

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值