tags:

views:

188

answers:

3

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?

+3  A: 

$#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.

RC
@array returns the size when used in scalar context, so you may need to be careful and use scalar(@array) (or 0+@array)
Nick Dixon
Good point. Thanks.
RC
+13  A: 

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.

Sinan Ünür
Using array indexes less than $[ but >= 0 doesn't work so well - the results may not be what you expect. Though I'm not sure what you could realistically expect.
ysth
+1  A: 

Perhaps you meant to write:

@first_one = split('', $info);

to get a list of characters?

Nick Dixon