1

I'm sure I'm missing something, I am done storing arrays as values to my hash, but what I'm printing is an array reference and not the elements although I'm looping through it. All I'm getting is ARRAY(0x1c....).

Here is what I have done so far:

foreach $y ($hash{$first_char}){
    print $y;
}

What is missing?

EDIT: this might be a duplicate, but it isn't specific.

ANSWER: missing the @{}

foreach $y (@{$hash{$first_char}}){
        print $y;
    }
Community
  • 1
  • 1
Atieh
  • 230
  • 2
  • 16
  • 3
    maybe it is `foreach $y (@{$hash{$first_char}}){`? – foibs Dec 15 '13 at 19:59
  • 2
    Please indent correctly. You need to show us how you are populating %hash (and @splitted.) It would be very helpful to have a sample input and what you are expecting. – gwaigh Dec 15 '13 at 20:00

2 Answers2

3

I'm guessing your %hash is a hash of array references. (Showing output of:

use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper \%hash;

would help clarify your question.)

If so, and you are trying to loop over the elements in one of the arrays, you want:

for my $y ( @{ $hash{$first_char} } ) {

It's also a really good idea to do use strict; use warnings; and to use lexical variables (declared with my and restricted to the shortest practical scope).

ysth
  • 96,171
  • 6
  • 121
  • 214
  • well, now that I know that, if I ask the user to enter any letter to use as key and I print the target array, I get a completely diff one. For example, passing 'h' to the key and the array corresponds to words starting with 's'. – Atieh Dec 15 '13 at 20:17
  • I suspect you were pushing the same array to the hash for each letter; using lexical variables properly can fix that. – ysth Dec 15 '13 at 21:28
  • actually no, I was pushing the array of the previous key to the current one. One more question, the elements (words) in those arrays, it seems I can't compare them with strings..any idea why? – Atieh Dec 16 '13 at 08:18
2

If the values of the elements in %hash are arrays then they must be array references (e.g. a scalar value (since hash values can be nothing but scalar values)).

Therefore, if you wish to loop over each of the values in the stored arrays, you'll want to dereference the array-refs by changing the object of your foreach loop (INNERLOOP) to be (@{$hash{$first_char}}).

Note that I wrapper your statement in a @{} construct to get at the underlying array.

amon
  • 57,091
  • 2
  • 89
  • 149
Tim Peoples
  • 344
  • 2
  • 9