2

What is the best way in which to insert an element between each existing element of an array. The best I have so far is as follows:

my @array = ( 1 , 'foo', { }, [ ] );
my @new_array;
push @new_array, $_, ', ' for @array;
pop @new_array;

In reality, @array contains a mixture of HTML::Element objects and strings that are passed to HTML::Element's splice_content method with the aim of comma separating part of an elements contents.

2
  • 1
    That's not a bad way. I was thinking List::MoreUtils::zip would help, but you still have to create the array of (', ') x $#array to be the alternate items, so it doesn't look like a big saving over this. Commented Jul 12, 2015 at 0:41
  • Thank you for the zip suggestion, checking for a solution via the List::* modules hadn't crossed my mind. Commented Jul 12, 2015 at 1:10

2 Answers 2

3

How about:

my @array = ( 1 , 'foo', { }, [ ] );
(undef, my @new_array) = map {; ', ' => $_ } @array;

This takes advantage of the little known fact that you can use undef on the left-hand side of a list assignment to indicate that you don't care about that element. (The semicolon in map {; is to make the parser understand that's a block and not a hashref.)

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice alternative. I was puzzling over the resultant syntax error before your semicolon fix.
3

I think I would use a map instead of a for loop but keep your pop

my @new_array = map { $_, ', ' } @array;
pop @new_array;

1 Comment

In the back of my mind, I wanted rid of that lonesome pop, but this solution certainly keeps the intentions clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.