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


In reply to Re: creating a subroutine for accessing hash of arrays by tilly
in thread creating a subroutine for accessing hash of arrays by jonnyfolk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.