Main Content

x operator in Perl

Archive - Originally posted on "The Horse's Mouth" - 2005-03-22 17:20:47 - Graham Ellis

So often, newcomers to programming try to use an "x" operator to multiply - and it doesn't work; they should use "*" in most languages. In Perl ... "x" means something different ... "replicate the string on the left the number of times on the right".

I've frequently been asked for a good example of where "x" is useful. Here's one - printing out the corret number of "-" signs to underline a title in a fixed width font.

print "who are you";
$name = <STDIN>;
chop $name;

print "$name\n";
print "-" x length ($name),"\n";

Further details in our Initial String Handling module