将数组推送到哈希时推送操作不起作用

Push operation not working while pushing array to a hash

我有两个数组 @arr1@arr2,我的 Perl 代码中有一个散列 %hash

我在 @arr1 中有某些元素,在 @arr2 中也有类似的某些元素。我想将 @arr1 的元素作为散列 %hash 的键,并将数组 @arr2 的元素作为散列 %hash.

的那些键的值

我在我的 Perl 脚本中使用以下代码来执行此操作:

use strict;
use warnings;
use Data::Dumper;

my %hash = ();
my @abc = ('1234', '2345', '3456', '4567');
my @xyz = ('1234.txt', '2345.txt', '3456.txt', '4567.txt');

push(@{$hash{@abc}}, @xyz);
print Dumper(%hash);

执行后,我得到以下输出:

./test.pl

$VAR1 = '4';
$VAR2 = [
          '1234.txt',
          '2345.txt',
          '3456.txt',
          '4567.txt'
        ];

它不打印键值,而是打印它们的总数。我需要输出是在执行脚本后打印每个键及其值。

有人可以帮忙吗。谢谢。

您正在寻找 slice 一次分配哈希的多个元素:

use strict;
use warnings;
use Data::Dumper;

my %hash = ();
my @abc = ('1234', '2345', '3456', '4567');
my @xyz = ('1234.txt', '2345.txt', '3456.txt', '4567.txt');

@hash{@abc} = @xyz;
print Dumper(\%hash);

产生(虽然键的顺序可能不同):

$VAR1 = {
          '4567' => '4567.txt',
          '2345' => '2345.txt',
          '3456' => '3456.txt',
          '1234' => '1234.txt'
        };

说明

push(@{$hash{@abc}}, @xyz); 所做的是将元素推入存储在单个散列条目中的数组引用中 - @abc 在这里用于标量上下文,其计算结果为数组的长度,因此 4 . 改为使用切片将值列表分配给相应的键列表。

然后 print Dumper(%hash); 首先将 %hash 变成交替键和值的列表,因此它们是两个不同的 Data::Dumper 条目。传递对散列的引用会使它打印出实际的数据结构作为一件事。