如何在字符串中重复 n 次字符? [英] How do I repeat a character n times in a string?
问题描述
我正在学习 Perl,所以请耐心等待这个菜鸟问题.
I am learning Perl, so please bear with me for this noob question.
如何在一个字符串中重复一个字符 n 次?
How do I repeat a character n times in a string?
我想做如下事情:
$numOfChar = 10;
s/^\s*(.*)/' ' x $numOfChar$1/;
推荐答案
默认情况下,替换将字符串作为要替换的部分.要在替换过程中执行代码,您必须使用 e
标志.
By default, substitutions take a string as the part to substitute. To execute code in the substitution process you have to use the e
flag.
$numOfChar = 10;
s/^(.*)/' ' x $numOfChar . $1/e;
这将在文本的开头添加 $numOfChar
空格.要对文本中的每一行执行此操作,请使用 -p
标志(用于快速单行处理):
This will add $numOfChar
space to the start of your text. To do it for every line in the text either use the -p
flag (for quick, one-line processing):
cat foo.txt | perl -p -e "$n = 10; s/^(.*)/' ' x $n . $1/e/" > bar.txt
或者如果它是更大脚本的一部分,请使用 -g
和 -m
标志(-g
用于全局,即重复替换和 -m
使 ^
在每一行的开头匹配):
or if it's a part of a larger script use the -g
and -m
flags (-g
for global, i.e. repeated substitution and -m
to make ^
match at the start of each line):
$n = 10;
$text =~ s/^(.*)/' ' x $n . $1/mge;
这篇关于如何在字符串中重复 n 次字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!