Eleonora
Eleonora

Reputation: 133

Perl: insert a "\n" every 70 characters

I have the following problem. I have a long string (1 thousand characters, more or less) and I am required to insert a "\n" every 70 characters. My idea was

my $finalstr;
    for($i=0; $i<=length($input)+1; $i=$i+70){
    $finalstr.=$finalstr.substr($input,$i,3)."\n";
    }

But it doesn't seem to work.The problem is that I don't know how to use regex in this case because the number of characters in $input could be not a multiple of 70.

Upvotes: 0

Views: 214

Answers (2)

GMB
GMB

Reputation: 222512

Consider:

$finalstr =~ s/(.{70})/$1\n/gs;

Expression (.{70}) captures 70 characters, and then $1\n substitutes with the captured part followed by a new line. Modifier g makes the search global (each and every match is replaced).

Note: If you string does not contain embedded new lines, you can remove the final s.

Example (with 4 characters instead of 70):

$ perl -we 'my $finalstr = "123456789"; $finalstr =~ s/(.{4})/$1\n/gs; print "$finalstr\n";'
1234
5678
9
$

Edit

As commented by ikegami, an alternative solution would be:

$finalstr =~ s/.{70}\K/\n/g;

Rationale:

  • the \K character class indicates that what is left of it should not be suppressed; hence no capturing is needed (this is more efficient than capturing and replacing)

  • removing the s modifier avoids counting in new lines as characters when matching; thus, if a new line is embedded in the string, the next line will accept 70 characters instead of just the remainder of the previous line.

Upvotes: 4

Holli
Holli

Reputation: 5072

Two problems: In the call to substr you specify a value of 3. That obviously should be 70. Then you are concatenating to the target string twice, first by using .= and then by repeating the $finalstr. You need to use either one, not both.

Correcting that gives you

for($i=0; $i<=length($input)+1; $i=$i+70){
    $finalstr .= substr($input,$i,70)."\n";
}

Which works as you intended. substr can also act as an lvalue though, so if you don't mind the $input being altered you can use that form:

for($i=70; $i<=length($input)+1; $i=$i+71){
    substr($input,$i,0) = "\n"; 
}

Upvotes: 2

Related Questions