Perl中如何将数组引用转换为哈希引用以适配子例程?
如何将数组哈希传入仅接受哈希引用的Perl子例程?
首先看你手里的这个数组哈希结构(Perl里数组元素实际是哈希引用,因为数组只能存标量):
[ { 'id' => '6', 'image' => '/x/eng/rlse/DOT/R9.0xN/final/bedrock/export/x86_64/tarball/image.tgz' }, { 'new_netboot_image' => '/x/eng/bbnbs/daemon/DOT/R9.2x/cit-ok/final/bedrock/export/x86_64/netboot/netboot/kernel', 'version' => '9.2', 'ntest' => '/x/eng/bbnbs/daemon/DOT/R9.2x/cit-ok/test/nate/bin/ntest', 'nate_lib' => '/x/eng/ctl/test-tools;/x/eng/ctl/test-tools/' } ];
你现在的问题是,直接把这个数组(或者数组引用)传给cleanup_version_mapping_update子例程,但这个子例程只接受哈希引用,类型不匹配肯定会报错。下面给你两种常见的解决思路:
思路一:遍历数组,逐个传入哈希引用
如果子例程是要处理数组里的每一个哈希元素,那你只需要遍历这个数组,把每个哈希引用单独传进去就行。代码示例:
# 假设$orig_cleanup_version_settings是数组引用 foreach my $hashref (@$orig_cleanup_version_settings) { $Api->service_db->cleanup_version_mapping_update($hashref); } # 如果是普通数组@orig_cleanup_version_settings,就这么写: foreach my $hashref (@orig_cleanup_version_settings) { $Api->service_db->cleanup_version_mapping_update($hashref); }
这样每次传的都是子例程需要的哈希引用,完全符合要求。
思路二:把数组包装成哈希引用传入
如果子例程期望接收的是一个包含所有这些数据的哈希引用(比如需要把整个数组作为哈希的一个值),那你可以把数组打包成一个哈希,再传它的引用。比如:
# 把数组放到哈希的某个键下,比如'items' my $wrapper_hashref = { items => $orig_cleanup_version_settings }; # 传入子例程 $Api->service_db->cleanup_version_mapping_update($wrapper_hashref);
或者如果你想用数组索引作为哈希的键,也可以这么写:
my $indexed_hashref = { map { $_ => $orig_cleanup_version_settings->[$_] } 0 .. $#$orig_cleanup_version_settings }; $Api->service_db->cleanup_version_mapping_update($indexed_hashref);
为什么你当前的代码会有问题?
你现在直接传$orig_cleanup_version_settings,这个变量是数组引用(从Dumper的[]包裹格式能看出来),但子例程要求的是哈希引用,两种引用类型不兼容,Perl会抛出类似Not a HASH reference的错误。所以必须按照上面的思路,把数据转换成子例程需要的类型再传入。
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

