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

I want to print out text, but only the first words if the string is under 50 letters long. If it is over 45, then the next word is added unless it is too long, like 10. How would I do this?

Replies are listed 'Best First'.
Re: Rounding to the nearest word
by Roy Johnson (Monsignor) on Dec 23, 2004 at 00:02 UTC
    Are you looking for Text::Wrap?

    Caution: Contents may have been coded under pressure.
Re: Rounding to the nearest word
by Joost (Canon) on Dec 23, 2004 at 00:27 UTC
    How about this:
    #!/usr/local/bin/perl -w use strict; my $string = <<END; Lorem Ipsum is simply dummy text of the printing and typesetting indus +try. Lorem Ipsum has been the industry's standard dummy text ever since the + 1500s, when an unknown printer took a galley of type and scrambled it to make + a type specimen book. It has survived not only five centuries, but also the l +eap into electronic typesetting, remaining essentially unchanged. It was popula +rised in the 1960s with the release of Letraset sheets containing Lorem Ipsum p +assages , and more recently with desktop publishing software like Aldus PageMa +ker including versions of Lorem Ipsum. END my $trunk = substr($string,0,50); # cut to 50 chars $trunk =~ s/\S+$//; # remove ending non-whitespace $trunk =~ s/\s+$//; # remove ending whitespace print "'",$trunk,"'\n";

    It guarantees a maximum of 50 chars, but it cuts off the last word if it ends on the 50th char.

      It guarantees a maximum of 50 chars, but it cuts off the last word if it ends on the 50th char.

      substring to 51 characters should solve that, shouldn't it?
Re: Rounding to the nearest word
by simonm (Vicar) on Dec 23, 2004 at 17:09 UTC
    Joost's suggestion is good; the only problem with such solutions is if you occasionally have strings which don't have any/much whitespace, in which case the result can be shorter than desired. I've got a function in String::Escape on CPAN that checks for that:
    use String::Escape qw( elide $Elipses ); local $Elipses; print elide( $mystring, 50 );