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;
    }
2
  • 3
    maybe it is foreach $y (@{$hash{$first_char}}){? Commented Dec 15, 2013 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. Commented Dec 15, 2013 at 20:00

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

3 Comments

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'.
I suspect you were pushing the same array to the hash for each letter; using lexical variables properly can fix that.
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?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.