gpt4 book ai didi

perl - 如何从同一个键打印出不同的值?

转载 作者:行者123 更新时间:2023-12-02 19:08:32 25 4
gpt4 key购买 nike

我有两个具有相同键但不同值的哈希值。

%HASH1

ERROR MESSAGE1 => A1
ERROR MESSAGE2 => A2
ERROR MESSAGE3 => A3
ERROR MESSAGE4 => A4

%HASH2

ERROR MESSAGE1 => C4
ERROR MESSAGE2 => C5
ERROR MESSAGE3 => C6
ERROR MESSAGE4 => C7

我的代码如下所示

my %errordata;
for my $key (keys %hash1) {
$errordata{$key} = [ $hash2{$key}, $hash1{$key} ];
}

use Data::Dumper;
print Dumper \%errordata;

所以,我的问题是如何根据上面的代码打印没有第一个哈希值的值?因为我尝试执行 while 循环,但它显示的是 ARRAY(0x2113a30)

while (my($g,$w) = each %errordata)
{
print "$_" for @{$w};
}

谢谢。

编辑

输出应该是这样的

ERROR MESSAGE: ERROR MESSAGE1
FULL PATH: A1
LINE: C4

最佳答案

请调查以下代码段是否符合您的问题。

注意:while( my($g,$w) = every %errordata ) 不会根据 key 顺序对对进行排序(使用 for排序键 %errordata 代替)

use strict;
use warnings;
use feature 'say';

my %hash1 = (
'ERROR MESSAGE1' => 'A1',
'ERROR MESSAGE2' => 'A2',
'ERROR MESSAGE3' => 'A3',
'ERROR MESSAGE4' => 'A4'
);

my %hash2 = (
'ERROR MESSAGE1' => 'C4',
'ERROR MESSAGE2' => 'C5',
'ERROR MESSAGE3' => 'C6',
'ERROR MESSAGE4' => 'C7'
);

my %errordata;

for my $key (keys %hash1) {
$errordata{$key} = [ $hash2{$key}, $hash1{$key} ];
}

use Data::Dumper;
print Dumper \%errordata;

say '--- Loop while --------------';
while (my($g,$w) = each %errordata)
{
say
"ERROR MESSAGE: $g
FULL PATH: $errordata{$g}[1]
LINE: $errordata{$g}[0]";
}

say '--- Loop for ----------------';
for( sort keys %errordata ) {
say
"ERROR MESSAGE: $_
FULL PATH: $errordata{$_}[1]
LINE: $errordata{$_}[0]";
}

输出

$VAR1 = {
'ERROR MESSAGE3' => [
'C6',
'A3'
],
'ERROR MESSAGE2' => [
'C5',
'A2'
],
'ERROR MESSAGE1' => [
'C4',
'A1'
],
'ERROR MESSAGE4' => [
'C7',
'A4'
]
};
--- Loop while --------------
ERROR MESSAGE: ERROR MESSAGE3
FULL PATH: A3
LINE: C6
ERROR MESSAGE: ERROR MESSAGE2
FULL PATH: A2
LINE: C5
ERROR MESSAGE: ERROR MESSAGE1
FULL PATH: A1
LINE: C4
ERROR MESSAGE: ERROR MESSAGE4
FULL PATH: A4
LINE: C7
--- Loop for ----------------
ERROR MESSAGE: ERROR MESSAGE1
FULL PATH: A1
LINE: C4
ERROR MESSAGE: ERROR MESSAGE2
FULL PATH: A2
LINE: C5
ERROR MESSAGE: ERROR MESSAGE3
FULL PATH: A3
LINE: C6
ERROR MESSAGE: ERROR MESSAGE4
FULL PATH: A4
LINE: C7

关于perl - 如何从同一个键打印出不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64692736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com