lists in perl

Discussion in 'Perl' started by eanair, Dec 12, 2006.

  1. eanair

    eanair New Member

    Joined:
    Dec 9, 2006
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Is the correct syntax to check if a list is empty in perl:

    if(@list == 0)

    thanks
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    If that doesn't work, use this

    Code:
    if(scalar(@list) == 0)
    {
      #empty
    }
    
     
  3. thillai_selvan

    thillai_selvan New Member

    Joined:
    Feb 20, 2010
    Messages:
    13
    Likes Received:
    0
    Trophy Points:
    0
    You can use the following way also.
    Code:
    my @arr ;
    if ( @arr )
    {
        print "Array not empty\n";
    }
    else
    {
        print "Array empty\n";
    }
    
    There is no need to use the scalar function.
    By default this will be treated as scalar context
     
  4. thillai_selvan

    thillai_selvan New Member

    Joined:
    Feb 20, 2010
    Messages:
    13
    Likes Received:
    0
    Trophy Points:
    0
    Another way to test whether a list is empty is as follows

    Code:
    
    my @arr ;
    if ( $#arr== -1 )
    {
        print "Array not empty\n";
    }
    else
    {
        print "Array empty\n";
    }
    
    $# will contain the index value of a list.
    If a list is not having any value means this will be -1.
    If a list is having only one element means this will be 0 and so on.
     
  5. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Code:
    unless(@arr)
    {
      ## empty
    }
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice