加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl hashref / perl语法

发布时间:2020-12-15 23:20:10 所属栏目:大数据 来源:网络整理
导读:今天通过的这段代码的变体(由perl编码器编写),令人困惑: my $k = {3,5,6,8}; my $y = {%$k}; 为什么?那是做什么的?这似乎与此相同: my $y = $k; 使用dbi模块调用上下文: while (my $x = $db-fetchrow_hashref ) { $y{something} = {%$x}; } 解决方法 不
今天通过的这段代码的变体(由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})手动初始化哈希是非常非常难看的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读