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

Dear Monks, I have a list which I need to print to a file. The thing is that I want every line to have 80 characters BUT, I dont want to chop the items in my list. For example, if I print an item and now I'm at column 77 and the next item is 5 characters long, I want to continue printing at the beginning of the next line. Example, lets say that my limit is column 10 (10 characters):
my list = (abcd efghi jkl mnop qrst uvwxyz) abcd efghi jkl mnop qrst uvwxyz
I didnt exceed beyond column 10. Can you please advise? Thanks!

Replies are listed 'Best First'.
Re: Print to file options (Text::Wrap)
by toolic (Bishop) on Jan 08, 2009 at 18:16 UTC
    The core module Text::Wrap seems to do what you want:
    use strict; use warnings; use Text::Wrap; $Text::Wrap::columns = 11; my $list = 'abcd efghi jkl mnop qrst uvwxyz'; print wrap('', '', $list); print "\n"; __END__ abcd efghi jkl mnop qrst uvwxyz
Re: Print to file options
by lostjimmy (Chaplain) on Jan 08, 2009 at 20:40 UTC
    Just for fun and because I feel like procrastinating...
    sub print_wrap { my ($wrap_len, @list) = @_; my $pos = 0; for my $item (@list) { my $len = length $item; if ($len + $pos > $wrap_len) { print "\n"; $pos = 0; } print "$item "; $pos += $len + 1; } } my @list = qw/abcd efghi jkl mnop qrst uvwxyz/; print_wrap 10, @list;