Tuesday, July 1, 2008

Perl: Detect an array like is_array() of PHP


Share at Facebook

There is a function at VB I think isArray() that can say whether the passed variable is an array or not. I think there is something like is_array() function exist at PHP language to detect an array. But I didn't find this function or similar utility at Perl yet.

I have found an way to detect whether the given variable is an array or not. Here is the code block.

## This is the initial array
my @array = qw(0 1 2 3 4 5 6 7 8 9);

## Check the reference with regex whether this is an array reference or not
if(\@array =~ /array/i){
print "This is an array\n";
}

## Actually when you print array reference
print \@array . "\n";
## This will output something like ARRAY(0x225f10)

Thats why when you matching the expression 'array' with the reference, it detected as an array.

Similar for Hash. You can detect whether this is hash or not using same technique. You just need to match the reference of hash with 'hash'. Below is the example like isHash() {I never heard something like isHash :-p}
## An initial hash
my %hash = ("one" => 1, "two" => 2);
## Again checking reference using regular expression
if(\%hash =~ /hash/i){
print "This is a hash\n";
}

## Actually this print hash reference with address
print \%hash . "\n";
## And output is something like HASH(0x1830e20)

Finally if you want to do the similar kind of task for a scalar variable in Perl you can do same. Just use the below code to do your isScalar() like task.
my $string = "123";
## Matching 'scalar' using regex with reference
if(\$string =~ /scalar/i){
print "This is just a scalar variable\n";
}

For more Perl related discussions take a look here http://icfun.blogspot.com/search/label/perl




2 comments:

Anonymous said...

http://perldoc.perl.org/functions/ref.html

Anonymous said...

This doesn't make any sense. If your variable has an @ in front of it, it's an array. If it has a %, it's a hash. If it has a $ it's a scalar. Why would you need to programmatically determine whether @foo is an array? It can't possibly ever be anything else. That's the whole point of the sigils in the first place!

Now if you were dealing with references, it might be handy to look up what something is a reference to. For example:

my $foo = [1, 2, 3];

That's an array reference to a 3-element array. But by looking at $foo you can't know that it's a reference to an array or a hash or whatever.

The typical way in perl to do this is to say:

if(ref $foo eq 'ARRAY') {
print "It's an array.";
}
elsif(ref $foo eq 'HASH') {
print "It's a hash.";
}

There are other things it could be, like an instantiation of an object, but you get the picture.