How do I get the last element of an array and show the rest of the elements?
Like this :
@myArray = (1,1,1,1,1,2);
Expected output :
SomeVariable1 = 11111
SomeVariable2 = 2
# print last element
print $myArray[-1];
# joined rest of the elements
print join "", @myArray[0 .. $#myArray-1] if @myArray >1;
If you don't mind modifying the array,
# print last element
print pop @myArray;
# joined rest of the elements
print join "", @myArray;
Сухой27 has given you the answer. I wanted to add that if you are creating a structured output, it might be nice to use a hash:
my @myArray = (1,1,1,1,1,2);
my %variables = (
SomeVariable1 => [ @myArray[0 .. $#myArray -1] ],
SomeVariable2 => [ $myArray[-1] ]
);
for my $key (keys %variables) {
print "$key => ",@{ $variables{$key} },"\n";
}
Output:
SomeVariable1 => 11111
SomeVariable2 => 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With