Multiplying strings and lists in perl

I've known for a while that you can "multiply" (aka: repeat) a string in perl using the "x" operator, but I've just heard that you can do the same for lists.

For strings, you can say something like..

print "hello " x 3;

And get "hello hello hello" as output.

It seems you can do something similar with lists - but there is a wrinkle.

Consider this script..

@a = (10,20,30);
@b = @a x 4;
print "@b\n";

What is a little unexpected, given the new understanding, is that this outputs "3333". But why? It seems that the "x" operator turns the @a into a scalar (the value of which is the length of the array) and has then repeats that 4 times.

So how do we get to the promised repeating of the array?

A little trial and error indicates that just adding "(" and ")" around the array part of the expression solves the problem. Like this..

@a = (10,20,30);
@b = ( @a ) x 4;
print "@b\n";

This outputs the expected "10 20 30 10 20 30 10 20 30 10 20 30".

Scroll to Top