First of all, defined @array
and defined %hashofarrays
is wrong. They are always defined. You want if (@array)
and if (keys %hashofarrays)
to test if they contain elements. You should have even gotten an warning defined(@array) is deprecated
!
What you want is another subroutine.
sub loop_body { # just use some better name!
my ($var) = @_;
call_subroutine($var);
print "Something else is printed";
call_anothersubroutine($var);
call_differentsubroutine($var);
}
Then:
if (@array) {
foreach my $var1 (@array) {
print "var1 is: $var1\n";
loop_body($var1);
}
} elsif (keys %hashofarrays) {
foreach my $key (keys %hashofarrays) {
print "the key is: $key\n";
foreach my $var1 (@{$hashofarrays{$key}}) {
loop_body($var1)
}
}
}
You can also use callbacks to make your solution more flexible:
sub loop_with_cb {
my $cb = shift;
for my $var (@_) {
if ($cb) {
local $_ = $var; # make $_ visible to the callback
$cb->($var);
}
call_subroutine($var);
print "Something else is printed";
call_anothersubroutine($var);
call_differentsubroutine($var);
}
}
Then:
if (@array) {
loop_with_cb(
sub { print "var1 is: $_\n" },
@array,
);
} elsif (keys %hashofarrays) {
foreach my $key (keys %hashofarrays) {
print "the key is: $key\n";
loop_with_cb(undef, @{ $hashofarrays{$key} });
}
}