如何在 Perl 中重复一个字符串 N 次?
在 Python 中,如果我这样做:
print "4" * 4
我得到
> "4444"
In Perl,我会得到
> 16
Is there a simple way to do the previous 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
x 运算符记录在 perldoc perlop 中。 顺便说一句,这里的二进制意味着一个带有两个参数的运算符,而不是由位组成。
perl -e
旨在从命令行执行 Perl 代码:The x operator is documented in perldoc perlop. Here binary means an operator taking two arguments, not composed of bits, by the way.
perl -e
is meant to execute Perl code from the command line:在 Perl 中,您需要使用“x”运算符。
之间的区别
注意和
前者产生重复的字符串:
后者产生重复的列表:
In Perl, you want to use the "x" operator.
Note the difference between
and
The former produces a repeated string:
the latter a repeated list:
Perl 中的情况非常相似
It's very similar in Perl
FWIW,它也是 Perl 中的
print 4 x 4
。一般来说,在 Perl 中,运算符是单态的,即。 对于字符串语义、数字语义、按位语义等,您有不同的运算符集,只要有意义,操作数的类型在很大程度上并不重要。 当您将数字运算符应用于字符串时,字符串首先会转换为数字,然后您将获得所需的运算(例如乘法),而当您将字符串运算符应用于数字时,它会转换为字符串,然后您将得到所需的运算。获取您要求的操作(例如重复)。 Perl 首先关注操作符,然后才是操作数的类型——如果它确实在意的话。
这与 Python 和大多数其他语言相反,在 Python 和大多数其他语言中,您使用一组运算符,并且操作数的类型决定您实际获得的语义 - 即。 运算符是多态的。
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.
如果你想打印 10 个字符“A”,你也可以
用输出来执行此示例
If you want to print 10 character "A"s, you can also do this
Example with output
到目前为止给出的所有答案都没有提到运算符
x
不仅适用于字符串文字,而且还适用于是字符串或表达式评估为像这样的
字符串,更重要,
x
将表达式自动转换为字符串(如果还没有)(感谢 ggorlen 为我指明了这个方向!)。 因此,例如将导致类似以下内容的输出
All answers, given so far, missed mentioning that the operator
x
does not only work on string literals, but also on variables that are strings or expressions that evaluate to strings likelike this
and, even more important,
x
does an automatic conversion of expressions into strings if they aren't already (thanks to ggorlen for pointing me into that direction!). So for examplewill result in something like the following as output