如何获取数组的最后一个元素并显示其余元素?
像这样:
@myArray = (1,1,1,1,1,2);
预期产出:
SomeVariable1 = 11111
SomeVariable2 = 2
答案 0 :(得分:11)
# print last element
print $myArray[-1];
# joined rest of the elements
print join "", @myArray[0 .. $#myArray-1] if @myArray >1;
如果您不介意修改阵列,
# print last element
print pop @myArray;
# joined rest of the elements
print join "", @myArray;
答案 1 :(得分:0)
Сухой27已经给了你the answer。我想补充一点,如果你要创建一个结构化输出,那么使用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";
}
<强>输出:强>
SomeVariable1 => 11111
SomeVariable2 => 2