Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl - how do you extract all elements of an array except the last?

Tags:

arrays

perl

I need to extract all elements in an array except the last and store them in a scalar for later use. At first, I thought this would be possible using array slices, but it appears that you cannot count backwards. For example:

my $foo = ($bar[0..-2]);  

or

my $foo = ($bar[-2..0]);  

Any help would be greatly appreciated as this is starting to drive me insane, and I have been unable to find a solution elsewhere or by experimenting.
Oskar

like image 734
Oskar Gibson Avatar asked Aug 17 '10 15:08

Oskar Gibson


2 Answers

my $foo = join ',', @bar[0..$#bar-1];

will concatenate (by comma) all elements of the array @bar except the last one into foo.

Regards

rbo

like image 105
rubber boots Avatar answered Oct 15 '22 01:10

rubber boots


my @foo = @bar;
pop @foo;

or

my @foo = @bar[ -@bar .. -2 ];

or if it's ok to change @bar, just

my @foo = splice( @bar, 0, -1 );
like image 25
ysth Avatar answered Oct 15 '22 00:10

ysth