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

Hello wise monks, I am trying to do something very simple to humans that seems more complicated to computers :) I have a very long string of characters (for example say a 4000 character string) in a variable. I want to write this string to a file such that there are only 60 characters per line resulting in a 67 line file. Is there an easy way to do this? I tried using:
printf "%.60s\n", $big_string
but that obviously just truncates the string to 60 characters and drops the rest. I imagine I could use substring and increment the parameters by 60 but then I think I'd end up with a substring out of range error. So I'm stuck as to how I can accomplish this. Any help is appreciated.

Replies are listed 'Best First'.
Re: How to divide single string across multiple lines?
by zwon (Abbot) on Jun 29, 2009 at 19:36 UTC
    $str =~ s/(.{60})/$1\n/g;
      thank you ,that worked wonderfully.
Re: How to divide single string across multiple lines?
by toolic (Bishop) on Jun 29, 2009 at 19:28 UTC
Re: How to divide single string across multiple lines?
by johngg (Canon) on Jun 29, 2009 at 21:19 UTC

    Another way would be to use unpack.

    print "$_\n" for unpack '(A60)*', $str;

    I hope this is helpful.

    Cheers,

    JohnGG

Re: How to divide single string across multiple lines?
by mhearse (Chaplain) on Jun 29, 2009 at 23:40 UTC
    use strict; local $\ = "\n"; local $_ = 'x' x 1000; my $pat = qr/.{1,60}/; while (/($pat)/g) { print $1; }