Default value of $#ArrayName when there is no element (Perl) -
the code below display number of arguments entered in command line.
#!/usr/bin/perl –w $myvar = $#argv + 1; print "hi " , $argv[0] , "\n"; print "you have $myvar arguments\n";
from perlintro, $#argv
special variable tells index of last element of array.
if case, when don't enter value in command line, how $myvar
value end 0 ?
is because when there no element in array, index of "no element" -1 ? -1 + 1 = 0.
$#argv
means "the index of last element of argv" - not array perlintro sentence seems imply.
for array, if it's empty, $#array
-1 , scalar @array
0.
caveat: if has modified $[
("index of first element"), that'll change $#
well. should probably use scalar @array
if you're after length, , $array[-1]
last element.
> cat demo.pl @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
Comments
Post a Comment