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?
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.
Perl provides the repetition operator (the 'x' operator).
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 (.)
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.
$ 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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With