How does $#array work in Perl?
In the following example:
my $info = 'NARIKANRU';
my @first_one = split /,/, $info;
print "$first_one[$#first_one]$first_one[$#first_one-1]\n";
The output is:
NARIKANRUNARIKANRU
I am not sure if this is correct because there is only one element in @first_one
and $#first_one
is the index of that element.
Given 开发者_开发技巧that $#first_one
is not equal to $#first_one - 1
, why is the single element in @first_one
being printed twice?
The output is correct. There are no commas in $info
so split
returns a list consisting of a single element.
$#first_one
is the index of the last (and in this case also first and only) element of @first_one
. With a single element, $#first_one
is 0
. Therefore, $first_one[$#first_one]
is $first_one[0]
.
Also, $first_one[$#first_one-1]
is $first_one[-1]
, i.e. the short hand way of referring to the last element of an array.
Of course, things would not have worked out this way had $[ been set to some other value than the default. Apparently, things work unless $[
is negative.
See also perldoc perldata.
Finally, you ask if there is anything wrong in your code. From what I can see, you are not using strict and warnings. You should.
$#array
just gives you the last index in the array that contains a value where @array
returns you the size of the array when used in a scalar context, which would return you 1 greater than that.
For example:
#!/usr/bin/perl
@array = ();
push(@array,10);
push(@array,11);
print $#array, "\n"; # Prints 1
print scalar(@array), "\n"; # Prints 2
print $array[$#array], "\n"; # Prints 11 (i.e. the last element)
Having stated that, you're split is creating a list of only one element. So $#array
is going to provide you 0. Accessing an array with the subscript -1 will also give you the last element in your array, which b/c you only have one in your array, the expression $#info - 1
equates to -1
(i.e. the last item in your array)
If you were to have 2 elements in your array, say: dog, cat. Then $#array
would yield cat while $#array - 1
would yield dog because you wouldn't be producing -1
with your expression $#info - 1
.
Perhaps you meant to write:
@first_one = split('', $info);
to get a list of characters?
精彩评论