Question

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?

Was it helpful?

Solution

$ perl -e 'print "4"x4; 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)

OTHER TIPS

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")

It's very similar in Perl

print "4" x 4;

FWIW, it’s also print 4 x 4 in Perl.

In general, in Perl, operators are monomorphic, ie. you have different sets of operators for string semantics, for numeric semantics, for bitwise semantics, etc., where it makes sense, and the type of the operands largely doesn’t matter. When you apply a numeric operator to a string, the string is converted to a number first and you get the operation you asked for (eg. multiplication), and when you apply a string operator to a number, it’s turned into a string and you get the operation you asked for (eg. repetition). Perl pays attention to the operator first and the types of the operands only second – if indeed it pays them any mind at all.

This is the opposite of Python and most other languages, where you use one set of operators, and the types of the operands determine which semantics you’ll actually get – ie. operators are polymorphic.

All answers, given so far, missed to mention that the operator x does not only work on string literals but also on string variables or expressions that build strings:

$msg = "hello ";
print $msg x 2;
print ($msg x 2) x 2;

If you want to print 10 character "A"s, you can also do this

perl -e 'print "A" x 10'; echo

Example with output

user@linux:~$ perl -e 'print "A" x 10'; echo
AAAAAAAAAA
user@linux:~$ 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top