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