How do I repeat a character n times in a string?

后端 未结 3 868
难免孤独
难免孤独 2021-01-03 20:54

I am learning Perl, so please bear with me for this noob question.

How do I repeat a character n times in a string?

I want to do something like below:

3条回答
  •  梦毁少年i
    2021-01-03 21:36

    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;
    

    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
    

    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;
    

提交回复
热议问题