String trim, snip, collapse in Perl
Post as a follow-up to Perl, Trim White Space from a String. I’m posting this so there is something a bit more idiomatic out there and make sure to get the message out: don’t use prototypes in Perl. Except for the rarest case the only reasonable use for them is to accept code blocks as arguments and that has nothing to do with the following.
#!/usr/bin/env perl sub trim { my @trim = @_; s/\A\s+|\s+\z//g for @trim; @trim; } sub ltrim { my @trim = @_; s/\A\s+// for @trim; @trim; } sub rtrim { my @trim = @_; s/\s+\z//g for @trim; @trim; } sub collapse { my @trim = @_; s/\A\s+|\s+\z//g for @trim; s/\s{2,}/ /g for @trim; @trim; } my @samples = ( " This is simple. ", "No leading or trailing.", "French spacing. Please.", " \t\nOH\t\t\t\n\n\nHAI \t ", ); print "TRIM:\n", join("\n", map { qq{-->$_<--} } trim(@samples) ), "\n\n"; print "LTRIM:\n", join("\n", map { qq{-->$_<--} } ltrim(@samples) ), "\n\n"; print "RTRIM:\n", join("\n", map { qq{-->$_<--} } rtrim(@samples) ), "\n\n"; print "COLLAPSE:\n", join("\n", map { qq{-->$_<--} } collapse(@samples) ), "\n\n";
Yields–
TRIM: -->This is simple.<-- -->No leading or trailing.<-- -->French spacing. Please.<-- -->OH HAI<-- LTRIM: -->This is simple. <-- -->No leading or trailing.<-- -->French spacing. Please.<-- -->OH HAI <-- RTRIM: --> This is simple.<-- -->No leading or trailing.<-- -->French spacing. Please.<-- --> OH HAI<-- COLLAPSE: -->This is simple.<-- -->No leading or trailing.<-- -->French spacing. Please.<-- -->OH HAI<--
Discussion
Comments
String::Strip
As I mentioned on the post you're replying to you might want to check out String::Strip it's faster. See this previous IronMan post http://www.illusori.co.uk/perl/2010/03/05/advanced_benchmark_analysis_1.html
By Caleb Cushing xenoterracide on 12 July 2010 · 22:22
Re: String trim, snip, collapse in Perl
It could almost be argued that a trim operator in perl ought to work like chomp; that is, mutate its argument, rather than act functionally and return a modified version. Consider perhaps
By Paul Evans on 13 July 2010 · 04:45
Re^2: String trim, snip, collapse in Perl
In fact, I have argued it. And was wrong. :( Observe–
By A is A on 13 July 2010 · 09:33
Re^3: String trim, snip, collapse in Perl
So? Thats still expected behaviour. Who in their right mind wants to modify a scalar literal?
If you're a true maniac, you can always do this:
The question is only
By Kent Fredric on 18 July 2010 · 03:58