Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
What is the most efficient (or most elegant, for that matter) way of interleaving lists in Perl? For example, let's say I have two lists:
( 'blorke', 'gromble', 'poomba' ) and ( 'snork', 'dumble', 'gronke' ). I'd like to end up with:
( 'blorke', 'snork', 'gromble', 'dumble', 'poomba', 'gronke' )
In my case, I'm filling a hash, but I can think of other reasons to do this as well.
I'd prefer if it were self-contained (i.e. had no need for temporary or index variables).
One obvious solution:
my @list1 = ( 'blorke', 'gromble', 'poomba' ); my @list2 = ( 'snork', 'dumble', 'gronke' ); my %index = map { $_ => pop @list2 } (@list1);
...but that's destructive of @list2 (and I rather feel like it violates the spirit of map ... should probably have used for). Are there better (maybe non-destructive) ways?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: interleaving lists
by chipmunk (Parson) on Jan 23, 2001 at 02:52 UTC | |
|
Re (tilly) 1: interleaving lists
by tilly (Archbishop) on Jan 23, 2001 at 05:34 UTC | |
|
(tye)Re: interleaving lists
by tye (Sage) on Jan 23, 2001 at 04:32 UTC | |
|
Re: interleaving lists
by Fastolfe (Vicar) on Jan 23, 2001 at 05:15 UTC | |
by Anonymous Monk on Jan 23, 2001 at 22:31 UTC | |
by rmgiroux (Initiate) on Jan 23, 2001 at 18:32 UTC | |
|
Re: interleaving lists
by Coyote (Deacon) on Jan 23, 2001 at 03:13 UTC | |
|
Re: interleaving lists
by InfiniteSilence (Curate) on Jan 23, 2001 at 19:44 UTC |