Main Content

String duplication - x in Perl, * in Python and Ruby

Archive - Originally posted on "The Horse's Mouth" - 2006-12-07 02:21:58 - Graham Ellis

In Python and Ruby you can duplicate a string by running the multiply operator (*) on a string object, and in perl you can use the x operator. There have been many times when I've looked at this facility and said to myself "very nice, but isn't that a feature looking for a benefit" - in other words, something that's nice but not much use. Well ... there's always a few cases to disprove such a theory:

s/^(\s+)/" " x length()/e;

That's Perl - replace all leading spaces on a line with the same number of leading   sequences.