Looping and concatenating multiple arrays in Perl

Saw this code while searching through something and it caught my attention. Interesting way to concatenate arrays.
use strict;
use warnings;
use Data::Dumper;

my $a = [1,2];
my $b = [3,4];

my $c = [];
push @$c, @$_ for $a, $b;

print Dumper($c);

$perl main.pl
$VAR1 = [
          1,
          2,
          3,
          4
       ];

Alternatively, you can write it as this way where we concatenate both arrays.
use strict;
use warnings;
use Data::Dumper;

my $a = [1,2];
my $b = [3,4];

my $c = [];
push @$c, $_ for (@$a, @$b);

print Dumper($c);

$perl test1.pl
$VAR1 = [
          1,
          2,
          3,
          4
       ];

However, if we have any duplicated item in both $a or $b, it will be merged as well.
use strict;
use warnings;
use Data::Dumper;

my $a = [1,2];
my $b = [1,2,3,4];

my $c = [];
push @$c, $_ for (@$a, @$b);

print Dumper($c);

$perl test2.pl
$VAR1 = [
          1,
          2,
          1,
          2, 
          3,
          4
       ];

To resolve this, we need to remove the duplicate items in the combined array by using
List::MoreUtils.
use strict;
use warnings;
use Data::Dumper;
use List::MoreUtils qw(uniq);

my $a = [1,2];
my $b = [1,2,3,4];

my $c = [];
push @$c, $_ for uniq(@$a, @$b);

print Dumper($c);

$ perl test3.pl
$VAR1 = [
          1,
          2,
          3,
          4
        ];

No comments:

Post a Comment