koknat has asked for the wisdom of the Perl Monks concerning the following question:

Problem: I have a hash %a that is arranged like this: $a{$b}{$c}{$d} = value

I want to call a function, passing in a reference to a part of the array

$w = "xyz"; &myfunc($a_ref->$w);
I thought this would work, but I get the error
Can't call method "xyz" on unblessed reference

# My workaround my %a = %$a_ref; my %b = %{$a{$w}}; my $b_ref = \%b; &myfunc($b_ref);

The workaround does exactly what I want, but it's ugly and eats up memory and CPU cycles. Is there a better way?

Thanks

Replies are listed 'Best First'.
Re: Hash reference
by Transient (Hermit) on Jun 03, 2005 at 22:19 UTC
    is xyz your key? or is it x, then y, then z?

    Have you tried:
    $w = "xyz"; &myfunc($a_ref->{$w});
    ??
      Thanks very much. That worked. I didn't think the braces were needed, but they make all the difference.
      &myfunc($a_ref->$w); # BAD &myfunc($a_ref->{$w}); # GOOD
      Yes, "xyz" was the key.
        The braces are indeed important because you're providing a key, and expecting a value. The value is actually a reference!

        When you don't provide the braces you are no longer passing a key and expecting a value. Instead you're trying to call a function!

        That's why you get the error message, can't call method on unblessed reference.. because you have a hash, not an object.

Re: Hash reference
by djohnston (Monk) on Jun 03, 2005 at 22:31 UTC
    If I understand you correctly, I think this is what you want: myfunc($a_ref->{$w}).