in reply to Re: Breaking String
in thread Breaking String


The below will take first lines in the string.
print "Now using Wrap method \n"; $Text::Wrap::columns = 60; my $text = wrap('', '', $smstext); my @chunks = split(/\n/,$text); # split $text into chunks print $chunks[0]."\n".$chunks[1],"\n"; #take first two lines

Any other methods are welcome.

Replies are listed 'Best First'.
Re^3: Breaking String
by brsaravan (Scribe) on Oct 17, 2008 at 10:52 UTC
    Using Text::Wrap module is the better way. Here is the solution without using that module.
    #! /usr/bin/perl my @arr = split("", $ARGV[0]); my ($i, $len) = 0; my $newlines=''; my $maxlen = 60; while ($i <= length($ARGV[0])) { $str1 = $str1 . $arr[$i]; my $len = length($str1); if ($len == $maxlen) { if ($str1 =~ /\S+$/) { $str1 =~ s/\s+(\S+)$//; $newlines .= $str1 . "\n"; $i = length($newlines)-2; $str1= "";$len=0 } else { $newlines .= $str1 . "\n"; $str1 = "";$len=0 } } $i++; } print "$newlines\n";
Re^3: Breaking String
by LxP (Novice) on Oct 19, 2008 at 03:46 UTC

    Since other modules might be using Text::Wrap, it's a good idea to localise your change to $Text::Wrap::columns. This ensures that other modules aren't affected by your change to this variable.

    local $Text::Wrap::columns = 60;

    Kudos to bart for already mentioning this in their response.