今天通过的这段代码的变体(由perl编码器编写),令人困惑:
my $k = {3,5,6,8};
my $y = {%$k};
Run Code Online (Sandbox Code Playgroud)
为什么?那是做什么的?这似乎与此相同:
my $y = $k;
Run Code Online (Sandbox Code Playgroud)
使用dbi模块调用上下文:
while (my $x = $db->fetchrow_hashref )
{ $y{something} = {%$x}; }
Run Code Online (Sandbox Code Playgroud)
小智 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
Run Code Online (Sandbox Code Playgroud)
顺便说一下,使用所有逗号(如同my $k = {3,5,6,8})手动初始化哈希是非常非常难看的.
| 归档时间: |
|
| 查看次数: |
281 次 |
| 最近记录: |