今天通过的这个代码的变体(由perl程序员编写),它令人困惑:
my $k = {3,5,6,8};
my $y = {%$k};为什么?这是做什么的?这看起来和下面的是一样的:
my $y = $k;上下文在使用dbi模块的调用中:
while (my $x = $db->fetchrow_hashref )
{ $y{something} = {%$x}; }发布于 2012-06-02 12:41:36
不同之处在于,它是对数据结构进行克隆,而不引用相同的内存。
例如:
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-02 13:03:54
在本例中,{ }是散列构造器。它创建一个新的散列并返回对该散列的引用。所以
比较
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}; # 4https://stackoverflow.com/questions/10859819
复制相似问题