To get the last element in an array in Perl, you can use array indexing similar to other languages.
In this example,
@numbers
with some elements.$numbers[-1]
and store it in the scalar variable $last_number
.@numbers = (1, 2, 3, 4, 5);
$last_number = $numbers[-1];
print "Last number is: $last_number\n";
Last number is: 5
In this example,
@fruits
with some elements.$fruits[-1]
and store it in the scalar variable $last_fruit
.@fruits = ("apple", "banana", "cherry");
$last_fruit = $fruits[-1];
print "Last fruit is: $last_fruit\n";
Last fruit is: cherry
In this tutorial, we learned How to get Last Element in Array in Perl language with well detailed examples.