in reply to Question: Is undef a valid argument?

Well, if you are just looking to check if there is anything in it or not (i.e. not checking to see the actual *number* of elements) according to defined :

"You should instead use a simple test for size:
if (@an_array) { print "has array elements\n" }
"
I suppose you could also do something like scalar(@an_array) to find out the number of elements it currently possesses.

Replies are listed 'Best First'.
Re^2: Question: Is undef a valid argument?
by jujiro_eb (Sexton) on May 06, 2009 at 21:41 UTC
    Thanks JPerl!

    This is elegent and requires same lines of code as I used before.

    Ash

Re^2: Question: Is undef a valid argument?
by jujiro_eb (Sexton) on May 06, 2009 at 21:54 UTC
    Sorry,

    Spoke too soon.

    None of what you sggested works.

    #! /usr/bin/perl use strict; use warnings; sub p1 { my $n1; $n1=scalar(@_); if (@_) { print "Has elements\n"; } print "1. Parameters to the sub p1 $n1\n"; my $p1=shift; if (@_) { print "Has elements\n"; } else { print "Has no elements\n"; } print "2. p1=$p1\n"; } p1 $ARGV[0];
    Try passing nothing to the script you will see it still states one argument.

      Like I already said, $ARGV[0] always evaluates to a scalar. As long as you keep using $ARGV[0], you'll always get a scalar. If you want to pass zero when @ARGV is empty, you'll need to pass something different when @ARGV is empty. In general, you'd do

      p1( @ARGV ? $ARGV[0] : () );

      In this case, the following suffices:

      p1(@ARGV);
      You are still explicitly passing the first, non existent element of your array to your subroutine. If instead call your subroutine with

      p1 @ARGV;

      you will get your expected result.