Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 see in result this: @c = ('one1', 'two2', 'three3'); Is there way I can merge these lists into one?

like image 284
vandie Avatar asked Apr 07 '26 17:04

vandie


2 Answers

Assuming that you can guarantee the two arrays will always be the same length.

my @c = map { "$a[$_]$b[$_]" } 0 .. $#a;
like image 105
Dave Cross Avatar answered Apr 09 '26 08:04

Dave Cross


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;
};
like image 35
Alan Haggai Alavi Avatar answered Apr 09 '26 06:04

Alan Haggai Alavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!