Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I've written some clumsy code to copy a file to stdout (to a web page), and line-wrap it. Some lines in the file are purposefully very long. But we don't want to word-wrap (ala Text::wrap). No, I definitely want to line-wrap at column 80. There must be a more elegant way to do this that this:
sub display_email { my ($fn) = @_; print "<center>file <i>$fn</i></center>\n"; if ( open( EMAIL, $fn ) ) { print "<hr width=600><br>\n<pre>"; while( $_ = <EMAIL> ) { if ( /^Message-Id:/ || /^Content-Type:/ || /^Content-Disposition:/ || /^Content-Transfer/ || /^X-[-\w]*:/ || /^Status: RO/ || /^Mime-Version:/ ) { next; } if ( /^\s/ && $rcvdflag ) { next; } if ( /^Received:/ ) { $rcvdflag = 1; next; } if ( /^[^ ]/ ) { $rcvdflag = 0; } if ( length($_) > 80 ) { chop; do { print substr( $_, 0, 80 ) . "\n"; if (length($_) > 80) { $_ = substr( $_, 80, length($_) - 80 ); } else { $_ = ""; } } while length($_); } else { print $_; } } print "</pre>\n"; close( EMAIL ); } }
Also, in this sub, the code to not copy all the email header noise lines is also somewhat inelegant. Any sugestions? Criticisms? Regards, -allan

Replies are listed 'Best First'.
Re: how do I line-wrap while copying a file to stdout?
by nardo (Friar) on Apr 20, 2001 at 11:14 UTC
    chomp; print join("\n", grep(/./, split(/(.{80})/))), "\n";
    The chomp is to get rid of the newline, since we don't really want to count it as a character (i.e. 80 chars + a newline should go on one line even though it's more than 80 chars).
      How about: print "$_\n" for /.{1,80}/g;
      this seems to drop (not print) the first 80 characters of the very long lines. -allan
      I think you had it except for the grep command. I'm not sure what that's there for. I have:
      chomp $string; print join( "\n", split( /(.{80})/, $string ) ), "\n";
        Sorry. For a drop in replacement, you can use:
        chomp; print join( "\n", split( /(.{80})/ ) ), "\n";
(tye)Re: how do I line-wrap while copying a file to stdout?
by tye (Sage) on Apr 20, 2001 at 19:53 UTC

    Since it is a web page, I suspect I would like your interface much better if you, instead of wrapping lines at what you think is a good width, you let me and my browser pick a good width and wrap the stuff ourselves.

    For example, by encoding HTML entities and turning multiple newlines into <p /> and/or newlines into <br />.

            - tye (but my friends call me "Tye")
Re: how do I line-wrap while copying a file to stdout?
by busunsl (Vicar) on Apr 20, 2001 at 11:22 UTC
    Try:

    print join "\n", unpack("A80" x (length($l) / 80 + 1), $l);
      this seems to be missing one newline per group of lines. And lines short than 80 characters also print, missing the newline.
      -allan