如何使用地图加入两个列表?

| 我在Perl中有这样的代码:
#!/usr/bin/perl -w

my @a = (\'one\', \'two\', \'three\');
my @b = (1, 2, 3);
我想在结果中看到:
@c = (\'one1\', \'two2\', \'three3\');
有什么办法可以将这些列表合并为一个?     
已邀请:
假设您可以保证两个数组的长度始终相同。
my @c = map { \"$a[$_]$b[$_]\" } 0 .. $#a;
    
或者,您可以使用
List::MoreUtils
中的
pairwise
#!/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;
};
    
为了完整起见,并使Tom感到高兴,这是您可以使用的
pairwise
的纯perl实现:
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
}
由于涉及到这一点,因此如davorg所示,仅使用
map
可能会更容易。     

要回复问题请先登录注册