如何在Perl中重复一次字符串N次?

前端之家收集整理的这篇文章主要介绍了如何在Perl中重复一次字符串N次?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Python中,如果我这样做:
print "4" * 4

我明白了

> "4444"

在Perl中,我会得到

> 16

在Perl中有一个简单的方法来做前者吗?

解决方法

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

在perldoc perlop中记录了x运算符.这里二进制意味着一个运算符采用两个参数,而不是由位组成.

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用于从命令行执行perl代码

$perl --help
Usage: perl [switches] [--] [programfile] [arguments]
  
  -e program     one line of program (several -e's allowed,omit programfile)

猜你在找的Perl相关文章