Search code examples
arraysperl

Replicate the array number of times in Perl


I have array which contains 5 elements (1,2,3,4,5). I want to replicate this a number of times based on the value set in the scalar $no_of_replication, e.g. 3.
So that my final array would contain (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5).

Here is what I have tried. It gives me scalar content instead of elements.

use strict;
use warnings;
use Data::Dumper;

my @array  = (1,2,3,4,5); 
print Dumper(\@array);

my $no_of_replication = 3;

my @new_array = @array * $no_of_replication;

print Dumper(\@new_array);

My array(@new_array) should be like (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5).


Solution

  • The operator for that is x and you need to be careful with the array syntax:

    @new_array = ( @array ) x $no_of_replication;
    

    Found the solution here:
    Multiplying strings and lists in perl via Archive.org