Massyn has asked for the wisdom of the Perl Monks concerning the following question:

#!/fellow/monks.pl

I've gone through the migration of a particular shell script to perl. To complete the migration, I need to count the number of parameters passed to the script via the command line.

In shell, it seems to be the $# command. How would I cound the number of parameters passed to @ARGV?

Thanks!

#!/massyn.pl The early worm gets caught by the bird.

Replies are listed 'Best First'.
Re: Count the number of parameters
by Anonymous Monk on Jun 02, 2003 at 03:36 UTC
    Either evaluate @ARGV in scalar context:

    $nargs = @ARGV;

    or do this:

    $nargs = $#ARGV + 1;

      $nargs = $#ARGV + 1;

      Don't do that. $#foo + 1 isn't necessarily equal to @foo, but that's not the most important reason for not using it. You shouldn't use it because it is not what you meant.

      If you want the number of elements, GET the number of elements. If you want the last index, GET the last index. Don't get the last index if you need the number of elements and don't get the number of elements to calculate the last index.

      In short: use @foo if you mean @foo, use $#foo if you mean $#foo. Don't use @foo - 1 or $#foo + 1.

      Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

      I just found scalar(@whatever) in perldata ;-) Same thing! Thanks!

        FWIW, you don't need to use scalar, as my $count = @some_array; will suffice.

        -- vek --
Re: Count the number of parameters
by Itatsumaki (Friar) on Jun 02, 2003 at 03:40 UTC

    Two points:

    1. If you have named-parameters (or would prefer to) you might benefit enormously from using either GetOpt::Std or GetOpt::Long
    2. I've never been a huge fan of using $ARGV or $#ARGV+1 for the size as AnonyMonk suggested. In my (originally C-trained) eyes it is clearer to write: scalar(@ARGV). I have no reason to suggest it is better in terms of performance, just in terms of code clarity
    Hope this helps!
    -Tats
    Update: corrected #@ to $#