Reputation: 305
The code below is to display the number of arguments entered in the command line.
#!/usr/bin/perl –w
$myVar = $#ARGV + 1;
print "Hi " , $ARGV[0] , "\n";
print "You have $myVar arguments\n";
From the perlintro, $#ARGV
is a special variable which tells you the index of the last element of an array.
If this is the case, when I don't enter any value in the command line, how does $myVar
value end up with 0 ?
Is it because when there is no element in the array, the index of "no element" is -1 ? As -1 + 1 = 0.
Upvotes: 1
Views: 242
Reputation: 1005
Is it because when there is no element in the array, the index of "no element" is -1 ? As -1 + 1 = 0
Almost. It is not "the index of 'no element'" but rather the following rule applies:
The following is always true:
scalar(@whatever) == $#whatever + 1;
Upvotes: 0
Reputation: 37146
You are right.
$#ARGV
is scalar @ARGV - 1
, as squiguy points out.
But there are less-noisier alternatives to count the number of arguments passed to your program that you should consider using instead:
my $count = scalar @ARGV; # Explicit using of 'scalar' function
my $count = 0+@ARGV; # Implicitly enforce scalar context
my $count = @ARGV; # Since the context is already set by LHS
Upvotes: 2
Reputation: 1958
$#ARGV
means "the index of the last element of ARGV" - not just any array as the perlintro sentence seems to imply.
For any array, if it's empty, $#array
will be -1 and scalar @array
will be 0.
CAVEAT: If someone has modified $[
("Index of first element"), that'll change $#
as well. You should probably always use scalar @array
if you're after the length, and $array[-1]
to get the last element.
> cat demo.pl
my @array = ();
print "Size=", scalar @array, " items, last=", $#array, "\n";
$[ = 2;
print "Size=", scalar @array, " items, last=", $#array, "\n";
> perl demo.pl
Size=0 items, last=-1
Size=0 items, last=1
Upvotes: 5
Reputation: 33370
According to the perlvar page:
@ARGV The array @ARGV contains the command-line arguments intended for the script. $#ARGV is generally the number of arguments minus one, because $ARGV[0] is the first argument, not the program's command name itself. See $0 for the command name.
Upvotes: 2