tags:

views:

118

answers:

4

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

+2  A: 
@foo = @bar[0 .. $#foo - 1];

If you want to create a head-scratcher:

my @x = (1, 2, 3);
print "@x[-@x .. -2]";
Sinan Ünür
+7  A: 

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

rubber boots
thank you for the quick answer, you have saved me a lot of time and frustration.
Oskar Gibson
+2  A: 

This will store all array elements, except for the last, into a scalar. Each array element will be separated by a single space.

use strict;
use warnings;

my @nums = 1 .. 6;
my $str = "@nums[0 .. $#nums - 1]";
print $str;

__END__

1 2 3 4 5

Don't you really want to store the elements into another array? If you store them in a scalar, it can be problematic to retrieve them. In my example above, if any element of the array already had a single space, you would not be able to properly reconstruct the array from the scalar.

toolic
thanks for the good reply but no I would like to store them as a scalar as i want to turn "forename initial(s) surname" into "surname, forename initial(s)" and have already extracted surname and added a comma to it, just couldn't get forename and initial(s).
Oskar Gibson
+5  A: 
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 );
ysth
thanks for the quick reply, i will remember the examples for later, they could come in handy
Oskar Gibson
I think pop is a bit nicer than splice for removing the last element :)
brian d foy
@brian d foy: I think you're right :)
ysth