Print perl hash value in foreach loop

Experts - Any advice on how to get a hash value in a foreach loop?
Values print correctly on standalone print statements, but I can't access value
in foreach loop.
See sample code below and thanks in advance.

foreach my $z (sort keys %hash) {
  for $y (@{$hash{$z}}) {
    print "$z ->";			# Prints key1
    print "$y ->";			# Prints Value1
    print $hash1{"$y"},"\n";		# Prints NULL <-- Why is this NULL??
  }
}

print $hash1{"Value1"};			# Prints HashValue <-- I want this value in foreach

Could you provide the output of the following?

use Data::Dumper;

# After the hash is populated.
print Dumper \%hash;
print Dumper \%hash1;

It's similar to the following:

          'Key1' => [
                      ' Value1',
                      ' Value2',
                      ' Value3',
                      ' Value4',
                      ' Value5',
                      ' Value6',
                      ' Value7',
                      ' Value8',
                      ' Value9'
                    ],

---------- Post updated at 04:56 PM ---------- Previous update was at 04:43 PM ----------

Missed %hash1, see below and thanks!

$VAR1 = {
          'Value1' => 'HashValue1',
          'Value2' => 'HashValue2',
          'Value3 => 'HashValue3',
          'Value4' => 'HashValue4',
          'Value5' => 'HashValue5',
          'Value6' => 'HashValue6',
          'Value7' => 'HashValue7',
          'Value8' => 'HashValue8',
          'Value9' => 'HashValue9'
                 };

Notice that 'space Value1' is not the same that 'Value1' . Is that a copy and paste from your output?
If that is the case, $hash1{$y} or $hash1{"$y"} is undefined, since it would be equivalent to $hash1{' Value1'} and the key dereference should be $hash1{'Value1'}

It's not exact copy/paste, it's similar data. Not that my data is top secret, I just can't post the actual online.

Actual is more along the lines:

$VAR1 = {
               'Key1' => [
                              ' Value-1',
                              ' Value-2',
                              ' Value-3',
                              ' Value-4',
                             ],

The values do really have a "space" in front. I didn't see that until you requested the dumper output.

they also have a "-" in them as well. Not sure if that is causing the issue.

But when doing a standalone print of:

print $hash1{"Value-1"}; 

Seems to work fine.

The '-' is not a problem since the key is a string; what is a problem is that ' Value-1' is not the same that 'Value-1' , since the the space in front counts as part of the key.

There is no $hash1{' Value-1'} , but there is a $hash1{'Value-1'}
Correct what it would become the keys, in the array, in %hash

1 Like

Thanks Aia!
I was stumped, big time. I appreciate your time looking into this for me.
I also wanted to tell you that I learn a lot from your posts on this forum.

1 Like