You are not the first one who is facing a problem. That's why I always share the solution of problems on my blog those I have faced. I believe someone will find these helpful.

Friday, November 28, 2008

Perl: Duplicating a string with a particular character for N times

Duplicating a string with a particular character for N times???Means you want to declare a string that will have exactly N number of characters and all are same character as you defined. For example a string with 5 A's will be as below.

$string = "AAAAA";

What if you need 5000 A's inside the string? If you don't know the correct way, then you'll probably use for/while loop to initialize the array with that particular character.

But I have a better solution. Which is

$string="A"x5000;

This will duplicate the A's 5000 times and will put inside the string value. If anyone know other solution like this, just let me know.