The problem with your code is that expression (5 .. 0)
does not return anything, since it means the starting number is greater than the end.
You can run the following code snippet to see the issue (nothing prints out):
print for (5 .. 0);
For this to do what you want, you would need to use list operator reverse
:
print for (reverse 0 .. 5);
Another thing to consider: in Perl, the first element of an array has index 0
. So the list you are looking for is (0 ..4)
instead of (0 .. 5)
.
Here is your updated code:
my @array = (1 .. 10);
for my $k (reverse 0 .. 4) {
print "$array[$k]\n";
}
Side note: always use strict
and use warnings
. Under these pragmas, your code would fail Variable $k
is not declared in the code: it should be for my $k ...
instead of for $k ...
.
This can also be expressed in this shorter form:
my @array = (1 .. 10);
print "$array[$_]\n" for (reverse 0 .. 4);
Side note #2: it is possible to modify the code so it dynamically computes which items should be printed depending on the length of the array. For this, you can use expression $#array
, which returns the value of the highest index in the array.
Consider:
print "$array[$_]\n" for (reverse 0 .. $#array/2);
If your array is (1 .. 11)
(ie has an uneven nombre of elements), this prints:
6
5
4
3
2
1