in reply to From arrayref to hashref

An addendum to broquaint for ref newbies:

One thing that got me about array/hash refs is that I can assign an array to a hash, even elements becoming keys, odd elements becoming values:

@array = (Bannana, Fruit, Corn, Vegetable); %hash = @array;# (Bannana => Fruit, Corn => Vegetable);

But you cannot dereference an array ref to a hash:

$food = \@array; print $$food{Corn}; # woops!

Once I realized how it worked, I thought that I was stupid to have suspected otherwise - until I learned it was a semi - common problem.

Hope that helps!

Cheers,
Erik

Replies are listed 'Best First'.
Re: Re: From arrayref to hashref
by Sidhekin (Priest) on Mar 21, 2002 at 17:06 UTC

    Actually, it is not stupid -- you can use overload to make that kind of thing work (even without using bless(), I think, though I should have to tinker with it some).

    However, if you don't need to optimize for speed, and don't feel like tinkering with overload, there is always good old TIMTOWTDI:

    $food = \@array; print +{@$food}->{Corn}; # yay! print @{{@$food}}{Corn,Bannana}; # slice!

    Have the appropriate amount of fun with it :-)

    Update: Found a better CPAN search link.

    The Sidhekin
    print "Just another Perl ${\(trickster and hacker)},"

      Neato - Bandito! I hadn't even *thought* of that (You can tell I'm not much beyond newbie myself - at least I understood why it works). Thanks a bunch!

      Cheers,
      Erik