开发者

How can I print the first to the fifth from last array elements in Perl?

开发者 https://www.devze.com 2022-12-15 15:41 出处:网络
I\'m running the following code and I\'m attempting to print the first element in the @rainbow array through the fifth-from-last element in the @rainbow array. Th开发者_运维百科is code works for any p

I'm running the following code and I'm attempting to print the first element in the @rainbow array through the fifth-from-last element in the @rainbow array. Th开发者_运维百科is code works for any positive indices within the bounds of the array, but not for negative ones:

@rainbow = ("a".."z");
@slice = @rainbow[1..-5];
print "@slice\n";


You want

my @slice = @rainbow[0 .. $#rainbow - 5];

Be careful, 1 is the second element, not the first.


The .. operator forms a range from the left to right value - if the right is greater than or equal to the left. Also, in Perl, array indexing starts at zero.

How about this?

@slice = @rainbow[0..$#rainbow-5];

$#arraygives you the index of the last element in the array.


From the first two sentences for the range operator, documented in perlop:

Binary ".." is the range operator, which is really two different operators depending on the context. In list context, it returns a list of values counting (up by ones) from the left value to the right value. If the left value is greater than the right value then it returns the empty list.

When the code doesn't work, decompose it to see what's happening. For instance, you would try the range operator to see what it produced:

 my @indices = 1 .. -5;
 print "Indices are [@indices]\n";

When you got an empty list and realized that there is something going on that you don't understand, check the documentation for whatever you are trying to do to check it's doing what you think it should be doing. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消