How can I join two lists using map?
I have such code in Perl:
#!/usr/bin/perl -w
my @a = ('one', 'two', 'three');
my @b = (1, 2, 3);
I want to 开发者_如何学Gosee in result this: @c = ('one1', 'two2', 'three3');
Is there way I can merge these lists into one?
Assuming that you can guarantee the two arrays will always be the same length.
my @c = map { "$a[$_]$b[$_]" } 0 .. $#a;
As an alternative, you can use pairwise
from List::MoreUtils
:
#!/usr/bin/env perl
use strict;
use warnings;
use List::MoreUtils qw( pairwise );
my @a = ( 'one', 'two', 'three' );
my @b = ( 1, 2, 3 );
my @c = do {
no warnings 'once';
pairwise { "$a$b" } @a, @b;
};
For completeness, and to make Tom happy, here is a pure perl implementation of pairwise
that you can use:
use B ();
use List::Util 'min';
sub pairwise (&\@\@) {
my ($code, $xs, $ys) = @_;
my ($a, $b) = do {
my $caller = B::svref_2object($code)->STASH->NAME;
no strict 'refs';
map \*{$caller.'::'.$_} => qw(a b);
};
map {
local *$a = \$$xs[$_];
local *$b = \$$ys[$_];
$code->()
} 0 .. min $#$xs, $#$ys
}
Since that is a bit involved, it is probably easier to just use map
as davorg shows.
精彩评论