piyush.shourie has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks,

I am writing an application wherein I need to accept a string, and insert a line break (\n) after every 64 characters. Can anyone please let me know a way to do this?

Thanks in advance,
Piyush

Replies are listed 'Best First'.
Re: line break after 64 characters
by Zaxo (Archbishop) on Jan 07, 2005 at 06:47 UTC

    Sure,

    my $newstring = do { local $_ = $string; my @foo; push @foo, substr($_, 0, 64, '') . "\n" while length; join '', @foo; }
    That's just one of many ways.

    $string =~ s/(.{1,64})/$1\n/g; is another. Untested.

    After Compline,
    Zaxo

Re: line break after 64 characters
by rev_1318 (Chaplain) on Jan 07, 2005 at 09:29 UTC
    An alternative could be Text::Wrap:

    use Text::Wrap; $Text::Wrap::columns = 65; print wrap("", "", $string);
    HTH,
    Paul
Re: line break after 64 characters
by gopalr (Priest) on Jan 07, 2005 at 07:21 UTC
    $string="This is sample text This is sample text This is sample text T +his is sample text This is sample text This is sample text This is sa +mple text This is sample text "; $string =~ s/(.{64})/$1\n/g; print $string;
Re: line break after 64 characters
by gube (Parson) on Jan 07, 2005 at 10:13 UTC

    Hi, Just try this

    $x = "piyushpiyushpiyushpiyushpiyushpiyushpiyushpiyushpiyushpiyushpiyu +shpiyushpiyushpiyushpiyush"; $x =~ s#(.{64})#$1\n#gsi; print $x; o/p: piyushpiyushpiyushpiyushpiyushpiyushpiyushpiyushpiyushpiyushpiyu shpiyushpiyushpiyushpiyush

    Regards,

    Gubendran.L

Re: line break after 64 characters
by johnnywang (Priest) on Jan 07, 2005 at 06:49 UTC
    This should work:
    $string =~ s/(.{64})/$1\n/g;
Re: line break after 64 characters
by perlsen (Chaplain) on Jan 07, 2005 at 10:11 UTC

    if u wish u can try this

    regexp

    $input="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; $input =~ s#(.{64})#\1\n#gs; print $input;

    output:

    ***************

    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    Regards,

    Senthil Kumar.k