Search code examples
perlsubstr

Perl adding CR at end of substr()


I am doing this line to limit the size of text lines. $Line=substr($_,0,12). But if truncation happened the returned strings lack the CR at the end. Without truncation all is OK. Thus when I print my lines the truncated ones don't have a CR and the line continues and gets garbled. Is there anything built-in to do this automatically or will it require extra if-clause to fix this? Thanks Gert.


Solution

  • I think you mean Line Feed (0A) rather than Carriage Return (0D).

    The solution is to remove the existing line feed before truncating the line, and re-adding it afterwards.

    chomp;
    $_ = substr($_, 0, 12);
    say;
    

    You could also use concatenation ($_ .= "\n";), of course.