Another way to do this is convert anything that's a scalar into an array reference. This avoids code duplication (and the risk of error that that entails).
For example, take your array:
my @array = (
[1, 2, 3, 4, 5],
['x', 'y', 'z'],
10,
11
);
One could use a temporary variable to either hold the original value ($row) if it is already an array reference or create an array reference to hold the original value (if it's a scalar). From then on you can use the cooked value in place of the original. For example:
foreach my $row (@array) {
my $cooked = ref $row eq 'ARRAY' ? $row : [ $row ];
print "@$cooked\n";
}
This outputs:
1 2 3 4 5
x y z
10
11
One can also eliminate the temporary variable:
foreach my $row (@array) {
foreach my $item ( @{ ref $row eq 'ARRAY' ? $row : [ $row ] } ) {
print "$item\n"
}
print "\n";
}
This directly evaluates the coercion code as an array (with @{ ... }) and iterates over it. The output is:
1
2
3
4
5
x
y
z
10
11
Similar code can be used, e.g., for hash references (ref $variable eq 'HASH')
use strict;anduse warnings;in EVERY script. Glad it was able to help you find this error and therefore know to ask for help.