nairb
nairb

Reputation: 474

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

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

Upvotes: 8

Views: 33305

Answers (2)

TLP
TLP

Reputation: 67920

Сухой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

Upvotes: 1

mpapec
mpapec

Reputation: 50677

# 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;

Upvotes: 26

Related Questions