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:
menuAdd('A really long string that I want to add to the awesome menu s
+ystem',20);
produces
+------------------+
| This is my menu |
+------------------+
| |
| A really long st |
| ring that I want |
| to add to the aw |
| esome menu syste |
| m |
+------------------+
I want it to produce
+------------------+
| 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";
}
}