Replicating elements of a list in Perl

So, I noticed a question titled Smallest way to expand a list by n on Stackoverflow because it appeared in the hot questions list.

The OP had requested an answer in Python, so an answer in Perl would have been rude to post there, but this question once again made me appreciate Perl’s syntax.

The task, given a tuple (1, 2, 3, 4), is to replicate individual elements so that each appears n times in the transformed tuple.

my @x = (1 .. 4);
my @y = map +($_) x 3, @x;

Putting everything in a subroutine, we have:

#!/usr/bin/env perl

use strict; use warnings;
use YAML;

print Dump replicate_tuple_elements([1 .. 4], 3);

sub replicate_tuple_elements {
    my ($tuple, $n) = @_;
    return [ map +($_) x $n, @$tuple ];

If the + in front of the first argument to map bothers you, you can replace that invocation with map { ($_) x $n } @$tuple. However, AFAIK, there is a performance penalty to using a code block instead of an expression as the first argument to map.