如何在Perl中创建哈希散列? [英] How do I create a hash of hashes in Perl?
本文介绍了如何在Perl中创建哈希散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
%a =();
%b =();
$ b {str} =hello;
$ a {1} =%b;
$ b =();
$ b {str} =world;
$ a {2} =%b;
打印$ a {1} {str} $ a {2} {str};
我假设哈希就像数组一样,为什么我不能使哈希包含另一个?
解决方案
-
您应该始终使用use strict在您的程序中。
-
使用引用和匿名哈希。
使用strict;使用警告;
my%a;
my%b;
$ b {str} =hello;
$ a {1} = {%b};
%b =();
$ b {str} =world;
$ a {2} = {%b};
打印$ a {1} {str} $ a {2} {str};
{%b}
创建对散列%b
的副本的引用。您需要在这里复制,因为您稍后将其清空。
Based on my current understanding of hashes in Perl, I would expect this code to print "hello world." It instead prints nothing.
%a=();
%b=();
$b{str} = "hello";
$a{1}=%b;
$b=();
$b{str} = "world";
$a{2}=%b;
print "$a{1}{str} $a{2}{str}";
I assume that a hash is just like an array, so why can't I make a hash contain another?
解决方案
You should always use "use strict;" in your program.
Use references and anonymous hashes.
use strict;use warnings;
my %a;
my %b;
$b{str} = "hello";
$a{1}={%b};
%b=();
$b{str} = "world";
$a{2}={%b};
print "$a{1}{str} $a{2}{str}";
{%b}
creates reference to copy of hash %b
. You need copy here because you empty it later.
这篇关于如何在Perl中创建哈希散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文