On 4/21/09 Tue  Apr 21, 2009  11:42 AM, "Grant" <emailgr...@gmail.com>
scribbled:

> I'm trying to pull 35 or fewer characters to the nearest space
> basically.  This is what I have now:
> 
> if(length($string) <= 34) {$var1 = $string.":";}
> if(length($string) > 34) {
>   ($var1, $var2) = ($string =~ /(.{35})(.{26})/);
>   $var1 =~ s/\s+$//;
>   $var2 =~ s/\s+$//;
>   $var2 .= ":";
> }
> 
> Does that look OK?  Is the 3rd line off?

The regular expression /(.{35})(.{26})/ will only match if the string
contains at least 61 characters. For shorter lines, $var1 and $var2 will be
undefined. Therefore, if you anticipate shorter lines, you should test to
see if $var1 and $var2 are defined before proceeding.

You can make the RE more flexible by including mininum and maximum numbers:

    /(.{35})(.{0,26})/

or you can use substr:

    $var1 = substr($string,0,35);
    $var2 = substr($string,35,26);

$var2 will be shorter than 26 characters if the line is shorter than 61
characters.

If you don't want to break the line after 35 characters if characters 35 and
36 are both non-whitespace, then you have some additional work to do.



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to