Reputation: 103
I have a two hashes with the same key but different values.
%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 code looks like this
my %errordata;
for my $key (keys %hash1) {
$errordata{$key} = [ $hash2{$key}, $hash1{$key} ];
}
use Data::Dumper;
print Dumper \%errordata;
So, my question is how can I print the values without the first hash's values based on the code above? because I tried doing a while
loop but it shows the ARRAY(0x2113a30)
instead.
while (my($g,$w) = each %errordata)
{
print "$_" for @{$w};
}
Thank you.
EDIT
output should something like this
ERROR MESSAGE: ERROR MESSAGE1
FULL PATH: A1
LINE: C4
Upvotes: 2
Views: 120
Reputation: 3222
Your code until it builds %errordata
hash looks fine.
While retriving the data from %errordata
, you're expecting it to print values as FULL PATH
and LINE
as values for each key called ERROR MESSAGE
.
You can use foreach
loop to print them.
...
foreach my $key( sort keys %errordata ){
print "ERROR MESSAGE: $key\n";
print "FULL PATH: $errordata{$key}[1]\n";
print "LINE: $errordata{$key}[0]\n";
}
Since LINE
and FULL PATH
would be always your hash of arrays 1st and 2nd element respectively.
Upvotes: 2
Reputation: 6808
Please investigate following piece of code for compliance of your problem.
NOTE: while( my($g,$w) = each %errordata )
will not order pairs base on key order
(use for
with sort keys %errordata
instead)
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]";
}
Output
$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
Upvotes: 3