1

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.

4 Answers 4

5

$#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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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

2 Comments

$#ARGV won't always be scalar @ARGV-1 though. $# is an unreliable mistress and should be treated as if there's a sharp axe in play.
@rjp : You're right that $#ARGV == @ARGV - 1 + $[;. The only thing stopping me from mentioning it is that $[ was deprecated in 5.12. As it stands, I would venture to say that 99.9% of the time $[ == 0, if not more
0

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:

perldata

The following is always true:

scalar(@whatever) == $#whatever + 1;

1 Comment

That won't be true if some (evil) person has changed $[.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.