in reply to Breaking String

You are looking for Text::Wrap, core module since perl 5.002.

Replies are listed 'Best First'.
Re^2: Breaking String
by harishnuti (Beadle) on Oct 17, 2008 at 07:50 UTC

    Exactly , i used Text::Wrap module, indeed its solving my purpose, but i only need initial 2 lines and ignore rest of the lines..
    for this i have remove lines greater than 2 in $text as below.
    $Text::Wrap::columns = 60; my $text = wrap('', '', $smstext); print $text,"\n";
      for this i have remove lines greater than 2 in $text
      To extract just 2 lines, you can do $top2 = $text =~ /^(.*\n.*\n)/;

      You can avoid unnecessary work in Text::Wrap if you limit the string you submit to it to a bit over the absolute maximum length of 2 lines together (your text says 140 characters, indeed a bit over 2x60 + 2 for the newlines), because the rest will be cut off anyway.

      my $smstext = "This sentence will have more than 120 characters and i +want to truncate this string into two lines containing 60 characters +each and ignore characters above 140 in length" ; use Text::Wrap; local $Text::Wrap::columns = 60; my($text) = wrap('', '', substr($smstext, 0, 140)) =~ /^(.*\n.*\n)/; print $text; __END__ Output: This sentence will have more than 120 characters and i want to truncate this string into two lines containing 60
        Maybe substitute
        $smstext =~ s~^(.*\n.*\n)~wrap('', '', $1)~e;
Re^2: Breaking String
by harishnuti (Beadle) on Oct 17, 2008 at 07:54 UTC

    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.
      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";

      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.