in reply to How to trim a line from leading and trailing blanks without using regex or non-standard modules
G'day likbez,
I will usually reach for one of Perl's string handling functions (e.g. index, rindex, substr, and so on) in preference to a regex when that is appropriate; however, in this case, I would say that the regex makes for much cleaner code.
You could implement a trim() function using the guts of this code (which uses neither a regex nor any modules, standard or otherwise):
$ perl -E ' my @x = (" a b c ", "d e f ", " g h i", "j k l", " ", ""); say "*** Initial strings ***"; say "|$_|" for @x; for my $i (0 .. $#x) { my $str = $x[$i]; while (0 == index $str, " ") { $str = substr $str, 1; } my $str_end = length($str) - 1; while ($str_end == rindex $str, " ") { $str = substr $str, 0, $str_end; --$str_end; } $x[$i] = $str; } say "*** Final strings ***"; say "|$_|" for @x; ' *** Initial strings *** | a b c | |d e f | | g h i| |j k l| | | || *** Final strings *** |a b c| |d e f| |g h i| |j k l| || ||
If your question was genuinely serious, please Benchmark a trim() function using something like I've provided against another trim() function using a regex. You could obviously do the same for ltrim() and rtrim() functions.
[As others have either asked or alluded to, please explain phrases such as "definitely an overkill", "important special case" and "abuse of regex". Unfortunately, use of such language makes your post come across as some sort of trollish rant — I'm not saying that was your intent, just how it presents itself.]
— Ken
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: How to trim a line from leading and trailing blanks without using regex or non-standard modules
by LanX (Saint) on Aug 14, 2020 at 11:22 UTC | |
by kcott (Archbishop) on Aug 15, 2020 at 11:02 UTC |