Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I repeat a string N times in Perl?

In Python, if I do this:

print "4" * 4 

I get

> "4444" 

In Perl, I'd get

> 16 

Is there an easy way to do the former in Perl?

like image 659
izb Avatar asked Nov 10 '08 10:11

izb


People also ask

Which operation is used to repeat a string n number of times?

In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times.

Which operator is also known as string repetition operator in Perl?

Perl provides the repetition operator (the 'x' operator).

How do I concatenate in Perl?

In general, the string concatenation in Perl is very simple by using the string operator such as dot operator (.) To perform the concatenation of two operands which are declared as variables which means joining the two variables containing string to one single string using this concatenation string dot operator (.)

How do I find the length of a string in Perl?

Perl | length() Function length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Return: Returns the size of the string.


2 Answers

$ perl -e 'print "4" x 4; print "\n"' 4444 

The x operator is documented in perldoc perlop. Here binary means an operator taking two arguments, not composed of bits, by the way.

Binary "x" is the repetition operator. In scalar context or if the left operand is not enclosed in parentheses, it returns a string consisting of the left operand repeated the number of times specified by the right operand. In list context, if the left operand is enclosed in parentheses or is a list formed by "qw/STRING/", it repeats the list. If the right operand is zero or negative, it returns an empty string or an empty list, depending on the context.

       print '-' x 80;             # Print row of dashes         print "\t" x ($tab/8), ' ' x ($tab%8);      # Tab over         @ones = (1) x 80;           # A list of 80 1’s        @ones = (5) x @ones;        # Set all elements to 5 

perl -e is meant to execute Perl code from the command line:

 $ perl --help Usage: perl [switches] [--] [programfile] [arguments]      -e program     one line of program (several -e's allowed, omit programfile) 
like image 189
Vinko Vrsalovic Avatar answered Oct 08 '22 09:10

Vinko Vrsalovic


In Perl, you want to use the "x" operator.

Note the difference between

"4" x 4 

and

("4") x 4 

The former produces a repeated string:

"4444" 

the latter a repeated list:

("4", "4", "4", "4") 
like image 43
bart Avatar answered Oct 08 '22 11:10

bart