I have a hash of arrays and a normal array, depending on the circumstances (ie what options the user chooses when the program is running) only one of these will be defined.
Example code to demonstrate problem:
my %hashofarrays;
my @array;
#...
#Some code between here where either %hashofarrays or @array gets defined
#...
if (defined @array) {
foreach my $var1 (@array) {
print "var1 is: $var1\n";
call_subroutine($var1);
print "Something else is printed";
call_anothersubroutine($var1);
call_differentsubroutine($var1);
}
}
if (defined %hashofarrays) {
foreach my $key (keys %hashofarrays) {
print "the key is: $key\n";
foreach my $var1 (@{$hashofarrays{$key}}) {
call_subroutine($var1);
print "Something else is printed";
call_anothersubroutine($var1);
call_differentsubroutine($var1);
}
}
}
As you can see in the code above depending on whether the @array
is defined or whether the %hashofarrays
is defined it will run the corresponding if
statement.
The problem:
The issue with this though is that the following lines of code are duplicated in both if
statements:
call_subroutine($var1);
print "Something else is printed";
call_anothersubroutine($var1);
call_differentsubroutine($var1);
Obviously, if these foreach
loops contained a lot of code, that would mean a huge amount of code would be duplicated.
Is there any way/what is the best way this duplication of code can be avoided when it comes to the foreach
loop?
In effect, is there a way to do something like the following: (I am well aware this code will not work, but explains what I am trying to achieve)
if (defined @array) {
foreach my $var1 (@array) {
} elsif (defined %hashofarrays) {
foreach my $key (keys %hashofarrays) {
print "the key is: $key\n";
foreach my $var1 (@{$hashofarrays{$key}}) {
} #ending bracket of if statement
call_subroutine($var1);
print "Something else is printed";
call_anothersubroutine($var1);
call_differentsubroutine($var1);
} #ending bracket of whatever foreach loop is used
I may well be overlooking something obvious here but cannot see a logical way to do this?
First of all,
defined @array
anddefined %hashofarrays
is wrong. They are always defined. You wantif (@array)
andif (keys %hashofarrays)
to test if they contain elements. You should have even gotten an warningdefined(@array) is deprecated
!What you want is another subroutine.
Then:
You can also use callbacks to make your solution more flexible:
Then: