G'day Rolf,
That's a valid point.
My main intent with that code was really to show the complexity of the solution when a regex or module were not used.
Anyway, adding a little more complexity, you can trim whatever blanks you want:
$ perl -E '
my @blanks = (" ", "\n", "\r", "\t");
my @x = (
" a b c ", "d e f \r ", " \t g h i",
"j k l", " ", "\n", "\n\nXYZ\n\n", ""
);
say "*** Initial strings ***";
say "|$_|" for @x;
for my $i (0 .. $#x) {
my $str = $x[$i];
while (grep { 0 == index $str, $_ } @blanks) {
$str = substr $str, 1;
}
my $str_end = length($str) - 1;
while (grep { $str_end == rindex $str, $_ } @blanks) {
$str = substr $str, 0, $str_end;
--$str_end;
}
$x[$i] = $str;
}
say "*** Final strings ***";
say "|$_|" for @x;
'
*** Initial strings ***
| a b c |
| e f
| g h i|
|j k l|
| |
|
|
|
XYZ
|
||
*** Final strings ***
|a b c|
|d e f|
|g h i|
|j k l|
||
||
|XYZ|
||
You're quite correct about "The OP should be clearer ...".
The word 'blank' is often used to mean various things:
a single space, multiple consecutive spaces, a whitepace character, multiple consecutive whitepace characters,
and I have also seen it used to refer to a zero-length string.
Similarly, the word 'space' can mean a single space, any gap between visible characters, and so on.
So, as with many posts, we're left with guessing the most likely meaning from the context.
My belief, that a regex is a better option, strengthens
as the complexity of the non-regex and non-module code increases. :-)
|