perl hashref / perl语法

前端之家收集整理的这篇文章主要介绍了perl hashref / perl语法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
今天通过的这段代码的变体(由perl编码器编写),令人困惑:

my $k = {3,5,6,8};
   my $y = {%$k};

为什么?那是做什么的?这似乎与此相同:

my $y = $k;

使用dbi模块调用上下文:

while (my $x = $db->fetchrow_hashref )
               {  $y{something} = {%$x};  }

解决方法

不同之处在于它在不引用相同内存的情况下克隆数据结构.

例如:

use strict;
use warnings;
use Data::Dumper;

my $h={'a'=>1,'b'=>2};
my $exact_copy=$h; #$exact_copy references the same memory as $h
$h->{b}++; #$h maps b to 3

print Dumper($exact_copy) . "\n"; #a=>1,b=>3

my $clone={%$h}; #We dereference $h and then make a new reference
$h->{a}++; #h now maps a to 2

print Dumper($clone) . "\n"; #a=>1,b=>3 so this clone doesn't shadow $h

顺便说一下,使用所有逗号(如我的$k = {3,8})手动初始化哈希是非常非常难看的.

猜你在找的Perl相关文章