how to determine whether variable is a scalar or an array?

A

Alex

I need the perl equivalent to a function like PHP's is_array() to check
the type of a perl variable.

Imagine this:

Let's define an array which can be either
@arr = (1, 2, 3);
or
@arr = ( [ 1, 2], [3, 4], [5, 6] );

ie, a list or an array of arrays (strictly speaking, a list of array
references).

Now I want to dump the array (whether it is a list or an array of
arrays) with a code block like this:

-----------------------------------------
for $element ( @arr) {
if (UNKNOWN TEST FOR SCALARITY) {
# one dimensional list
print "next scalar: $element\n";
} else {
# two dimensional list
print "next list of elements: (";
for $e (@$element) {
print "$e, ";
}
print")\n";
}
}
-----------------------------------------

My problem: which functionality provides the information whether
$element is a scalar or a reference to an array which in turn contains
the elements of interest? This functionality should replace the string
"UNKNOWN TEST FOR SCALARITY".

In PHP this would be is_array() or is_string() or is_xxxx...:

if (is_array($element)) {
print "is an array";
} else {
print "is a scalar";
}

And in Perl?

Alex
 
G

Gunnar Hjalmarsson

Alex said:
which functionality provides the information whether $element is a
scalar or a reference to an array which in turn contains the
elements of interest?

Paul answered your question. I would replace

if (UNKNOWN TEST FOR SCALARITY) {

with

unless (ref $element) {
 
A

Alex

perldoc -f ref

Thank you both (Paul and Gunnar)! Silly me! *look_ashamed_to_the_ground*
Never met this function before...

Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top