Im working with some code that has a subroutine which includes an array reference as one of the parameters. The elements in this incoming array can be either small arrays or strings.
I want to determine what type each element is in order to do something specific (i.e. if the element is an array, drill into it further via indexing, if the element is a string, use the string)
I have tried using the ref
function to interrogate each array element. It seems to work for elements that are ARRAYs, but if the element is a string, I was expecting the ref
to return SCALAR. However ref()
seems to return nothing. What am I doing wrong? I would think ref()
would return something.
Here is some sample code:
my @array = ("string1",
["ele1_arraystr1", "ele1_arraystr2"],
"string2",
["ele4_arraystr1", "ele4_arraystr2"],
"etc");
my $tmp;
&foobar( 30, 20, \@array);
sub foobar {
my($var1, $var2, $array_ref) = @_;
foreach $element (@$array_ref) {
my $tmp = ref($element);
print "Array element type: $tmp\n";
if ($tmp eq 'ARRAY') {
print " ARRAY: $element->[1]\n";
} elsif ($tmp eq 'SCALAR') {
print " SCALAR: $element\n";
} else {
print " Unexpected type: $tmp\n";
}
}
}
The output looks something like this:
ARRAY element test:
Array element type:
Unexpected type:
Array element type: ARRAY
ARRAY: ele1_arraystr2
Array element type:
Unexpected type:
Array element type: ARRAY
ARRAY: ele4_arraystr2
Array element type:
Unexpected type: