如何在Perl中将字符串重复N次? [英] How can I repeat a string N times in Perl?

查看:1208
本文介绍了如何在Perl中将字符串重复N次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如果我这样做:

In Python, if I do this:

print "4" * 4

我知道

> "4444"

在Perl中,我会得到

In Perl, I'd get

> 16

在Perl中有一种简单的方法来制作前者吗?

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

推荐答案

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

x运算符记录在perldoc perlop 中.这里的二进制表示顺便说一下,一个运算符采用两个不由位组成的参数.

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

二进制"x"是重复运算符.在标量环境中,或者 左操作数未括在括号中,它返回一个包含以下内容的字符串 左操作数的重复次数由右指定的次数 操作数.在列表上下文中,如果左操作数括在括号中 或者是由"qw/STRING/"形成的列表,则重复该列表.如果正确 操作数为零或负数,它返回一个空字符串或一个空 列表,具体取决于上下文.

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

这篇关于如何在Perl中将字符串重复N次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆