免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2295 | 回复: 6
打印 上一主题 下一主题

请教一下,如何完整copy一个引用指向的数据结构,如果这个数据结构中仍然有引用。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-07-05 10:33 |只看该作者 |倒序浏览
请教一下,如何完整copy一个引用指向的数据结构,如果这个数据结构中仍然有引用。

一个指向hash的引用可以这样copy: $copy = {%{$ds_ref}};

但是如果$ds_ref 指向的数据结构中还有引用,那该如何copy。谢谢

论坛徽章:
0
2 [报告]
发表于 2011-07-05 10:50 |只看该作者
没看明白,是这个意思吗?
  1. use Data::Dumper;

  2. $hash_ref = {abc => 123,
  3.              xyz => [456, 789],
  4.             };
  5. $ds_ref = $hash_ref;
  6. $copy = {%{$ds_ref}};

  7. print Dumper $copy;
复制代码

论坛徽章:
0
3 [报告]
发表于 2011-07-05 11:16 |只看该作者
大概可以描述为这样。
  1. $ds_ref->{data}=123;
  2. $ds_ref->{string}="abcd";
  3. $ds_ref->{child}=$child_ref;
  4. $child_ref->{data}=456;
  5. $child_ref->{string}="efgh";

  6. $copy={%{$ds_ref}};
复制代码
希望将$ds_ref指向的整个数据结构完全copy出来。但是上面代码中的如果修改了$child_ref 那么$copy指向的数据结构也会被修改(因为$copy->{child}是一个ref)。难道只能用递归解决么?

论坛徽章:
46
15-16赛季CBA联赛之四川
日期:2018-03-27 11:59:132015年亚洲杯之沙特阿拉伯
日期:2015-04-11 17:31:45天蝎座
日期:2015-03-25 16:56:49双鱼座
日期:2015-03-25 16:56:30摩羯座
日期:2015-03-25 16:56:09巳蛇
日期:2015-03-25 16:55:30卯兔
日期:2015-03-25 16:54:29子鼠
日期:2015-03-25 16:53:59申猴
日期:2015-03-25 16:53:29寅虎
日期:2015-03-25 16:52:29羊年新春福章
日期:2015-03-25 16:51:212015亚冠之布里斯班狮吼
日期:2015-07-13 10:44:56
4 [报告]
发表于 2011-07-05 11:17 |只看该作者
猜都可以猜出来要用模块 Clone 吧?

论坛徽章:
0
5 [报告]
发表于 2011-07-05 12:55 |只看该作者
谢谢,我去试一下。

论坛徽章:
0
6 [报告]
发表于 2011-07-05 13:32 |只看该作者
my $v = eval{Dumper($copy)};

论坛徽章:
0
7 [报告]
发表于 2011-07-05 15:36 |只看该作者
回复 1# rick_7


   
An array is a defined area of storage for list values, so we can generate a reference to it with the
backslash operator:
$arrayref = \@array;
This produces a reference through which the original array can be accessed and manipulated.
Alternatively, we can make a copy of an array and assign that to a reference by using the array
reference constructor (also known as the anonymous array constructor) [...]:
$copyofarray = [@array];
Both methods give us a reference to an anonymous array that we can assign to, delete from, and modify.
The distinction between the two is important, because one will produce a reference that points to the
original array, and so can be used to pass it to subroutines for manipulations on the original data,
whereas the other will create a copy that can be modified separately.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP