note
tilly
A better simplification is to stop writing extra loops.
<code>
if (exists $partners{$item}) {
my ($partners, $email, $nickname, $realname, $postcode, $phone) = @{$partners{$item}};
# Do something.
}
</code>
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.<p>
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:
<code>
if (exists $partners{$item}) {
push @allmembers, $item,
split / /, $partners{$item}{partners};
}
</code>
At which point you probably don't need to be bothered about abstracting the control structure.<p>
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.<p>
The strategy is to create an anonymous function for the action. And then call it. Like this:
<code>
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};
});
</code>
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.<p>
(Note: All code is untested.)
340223
340223