4

今天传递的这段代码的变体(由 perl 编码器编写),令人困惑:

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

为什么?那有什么作用?这似乎与此相同:

   my $y = $k;

上下文在使用 dbi 模块的调用中:

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

2 回答 2

8

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

例如:

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

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

于 2012-06-02T04:41:36.383 回答
0

{ },在这种情况下,是哈希构造函数。它创建一个新的散列并返回对它的引用。所以

比较

my $k = { a => 4 };
my $y = $k;
$k->{a} = 5;
print $y->{a};   # 5

my $k = { a => 4 };
my $y = { %$k };
$k->{a} = 5;
print $y->{a};   # 4
于 2012-06-02T05:03:53.793 回答