http://qs1969.pair.com?node_id=340225


in reply to creating a subroutine for accessing hash of arrays

A better simplification is to stop writing extra loops.
if (exists $partners{$item}) { my ($partners, $email, $nickname, $realname, $postcode, $phone) = @{ +$partners{$item}}; # Do something. }
That not only is conceptually simpler, but it is much more efficient. Hashes are good for looking things up by name, use them that way.

I'd also question why you have stuff that you really want to access by name being accessed by position in an array. It looks to me like you want a hash of hashes. Then your snippet above would become:

if (exists $partners{$item}) { push @allmembers, $item, split / /, $partners{$item}{partners}; }
At which point you probably don't need to be bothered about abstracting the control structure.

But for completeness, I'll answer your original question. And I like talking about the technique, so I'll provide it. But I really don't recommend that you do it at this point. Focus on the basics.

The strategy is to create an anonymous function for the action. And then call it. Like this:

sub do_for_partners { my ($item, $action) = @_; if (exists $partners{$item}) { $action->($item, $partners{$item}); } } # And the above example. do_for_partners($item, sub { push @allmembers, shift; push @allmembers, (shift)->{partners}; });
But as I point out, the original control structure is simple enough that you don't really gain anything by adding this conceptual complexity. So I don't advise adding action at a distance here.

(Note: All code is untested.)

Replies are listed 'Best First'.
Re: Re: creating a subroutine for accessing hash of arrays
by jonnyfolk (Vicar) on Mar 27, 2004 at 11:44 UTC
    Great reply, tilly. Thanks very much. I have already put into action the hash of arrays solution and I shall look at implementing hash of hashes when I get my head around it. I was also pleased that you answered the original question tho' I do understand why I shouldn't use it in this case.

    I must confess that though I have read up on this sort of thing in the past and it all seemed to make sense, it didn't really click back then. Now that I have an implementation of my own to do I feel I can really make some progress with it. Cheers