in reply to Re^2: Breaking String
in thread Breaking String

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

Replies are listed 'Best First'.
Re^4: Breaking String
by Anonymous Monk on Oct 17, 2008 at 09:25 UTC
    Maybe substitute
    $smstext =~ s~^(.*\n.*\n)~wrap('', '', $1)~e;

      I think you should try that on the sample input in the post to which you replied.

      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

      The wrap has to come first because you don't know what your newlines will look like until then. And to normalize it, newlines could be taken out before the wrap. That way you don't end up with messages like-

      Hi, it's really important that you
      Nope... there are several things wrong with your code.

      First, you're not truncating the string. You're only wrapping the original first two lines. You likely forgot a trailing (?s:.*) after the part you capture. Still, I very much dislike the idea of using s/// to delete the bulk of a string. That's a very inefficient way to do it.

      And second, even if you got rid of everything after those lines, you still may end up with more than 2 lines. You see, Text::Wrap will not unwrap existing newlines, but instead, it may add more newlines, if the runlength of the line is too long. You'll always end up with at least as many lines as you started from. So if you start out with 2 lines, you still may end up with 5...