gpt4 book ai didi

perl hashref/perl 语法

转载 作者:行者123 更新时间:2023-12-04 22:26:32 25 4
gpt4 key购买 nike

今天传递的这段代码的变体(由 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

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

关于perl hashref/perl 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10859819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com