如何在Perl中创建哈希散列?

Mik*_*ike 7 perl hash perl-data-structures

基于我目前对Perl中哈希的理解,我希望这段代码可以打印出"hello world".它没有打印任何东西.

%a=();

%b=();
$b{str} = "hello";  
$a{1}=%b;

$b=();
$b{str} = "world";
$a{2}=%b;

print "$a{1}{str}  $a{2}{str}"; 
Run Code Online (Sandbox Code Playgroud)

我假设散列就像一个数组,为什么我不能让散列包含另一个?

Ale*_*nii 6

  1. 你应该总是使用"use strict;" 在你的程序中.

  2. 使用引用和匿名哈希.

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}";
Run Code Online (Sandbox Code Playgroud)

{%b}创建对哈希副本的引用%b.你需要在这里复制,因为你以后将其清空.


mob*_*mob 6

哈希哈希很难在第一时间做到正确.在这种情况下

$a{1} = { %b };
...
$a{2} = { %b };
Run Code Online (Sandbox Code Playgroud)

会带你到你想去的地方.

有关perldoc perllolPerl中二维数据结构的详细信息,请参阅参考资料.