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

后端 未结 3 865
难免孤独
难免孤独 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条回答
  • 2021-01-03 21:28

    You're right. Perl's x operator repeats a string a number of times.

    print "test\n" x 10; # prints 10 lines of "test"
    

    EDIT: To do this inside a regular expression, it would probably be best (a.k.a. most maintainer friendly) to just assign the value to another variable.

    my $spaces = " " x 10;
    s/^\s*(.*)/$spaces$1/;
    

    There are ways to do it without an extra variable, but it's just my $0.02 that it'll be easier to maintain if you do it this way.

    EDIT: I fixed my regex. Sorry I didn't read it right the first time.

    0 讨论(0)
  • 2021-01-03 21:34

    Your regular expression can be written as:

    $numOfChar = 10;
    
    s/^(.*)/(' ' x $numOfChar).$1/e;
    

    but - you can do it with:

    s/^/' ' x $numOfChar/e;
    

    Or without using regexps at all:

    $_ = ( ' ' x $numOfChar ) . $_;
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题