bcarroll has asked for the wisdom of the Perl Monks concerning the following question:
I am trying to figure out how to split a string based on length, while also keeping words together (word boundary). I have the split based on length part worked out, but can't figure out how to not split a word.
More info...
I am building a menu system. I have a subroutine for adding menu items that splits strings based on length, to maintain the width of the menu, but if I pass a string that contains a bunch of words, that exceed the menu's width, words get cut and makes the menu look very bad.
Example:
+------------------+ | This is my menu | +------------------+ | | +------------------+
The menuAdd() subroutine adds the pipes at the left and right side of the menu and either pads a short string with spaces or splits a long string into multiple lines.
My dilema:
producesmenuAdd('A really long string that I want to add to the awesome menu s +ystem',20);
I want it to produce+------------------+ | This is my menu | +------------------+ | | | A really long st | | ring that I want | | to add to the aw | | esome menu syste | | m | +------------------+
+------------------+ | This is my menu | +------------------+ | | | A really long | | string that I | | want to add to | | the awesome menu | | system | +------------------+
This is what I have for the menuAdd() subroutine
sub menuAdd{ my $text = shift; my $menuWidth = shift; my $textLength = length($text); $menuWidth-=4; #shorten $menuWidth to leave room for | and a space + on left and right sides of the menu if ( $textLength <= $menuWidth ){ #add spaces to end of $text to maintain menuWidth print "| " . padSpaces($text,$menuWidth) . " |\n"; } elsif( $textLength > $menuWidth ){ #split $text into separate lines to maintain menuWidth my @textArray = split(/(.{$menuWidth})/, $text); print @textArray; foreach my $line (@textArray){ print "| " . padSpaces($line,$menuWidth) . " |\n"; #print "| $line |\n"; } } else { print "******SHOULD NEVER GET HERE******\n"; } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: How to split a string based on length or word boundary
by BrowserUk (Patriarch) on Dec 21, 2012 at 02:40 UTC | |
by Athanasius (Archbishop) on Dec 21, 2012 at 02:54 UTC | |
by BrowserUk (Patriarch) on Dec 21, 2012 at 03:04 UTC | |
by bcarroll (Pilgrim) on Dec 21, 2012 at 03:08 UTC | |
by BrowserUk (Patriarch) on Dec 21, 2012 at 03:27 UTC | |
Re: How to split a string based on length or word boundary
by Anonymous Monk on Dec 21, 2012 at 03:28 UTC |
Back to
Seekers of Perl Wisdom