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

Discussion in 'Perl Misc' started by Alex, Jun 17, 2004.

  1. Alex

    Alex Guest

    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
     
    Alex, Jun 17, 2004
    #1
    1. Advertisements

  2. Alex

    Paul Lalli Guest

    perldoc -f ref
     
    Paul Lalli, Jun 17, 2004
    #2
    1. Advertisements

  3. Paul answered your question. I would replace

    if (UNKNOWN TEST FOR SCALARITY) {

    with

    unless (ref $element) {
     
    Gunnar Hjalmarsson, Jun 17, 2004
    #3
  4. Alex

    Alex Guest

    perldoc -f ref

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

    Alex
     
    Alex, Jun 20, 2004
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.