Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last element of an array and show the rest?

Tags:

arrays

perl

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
like image 788
nairb Avatar asked Oct 21 '14 08:10

nairb


2 Answers

# 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;
like image 153
mpapec Avatar answered Oct 21 '22 04:10

mpapec


Сухой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
like image 39
TLP Avatar answered Oct 21 '22 05:10

TLP