Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Code review: function to trim whitespace from all items in a list

by McA (Priest)
on Nov 21, 2014 at 09:41 UTC ( [id://1107983]=note: print w/replies, xml ) Need Help??


in reply to Code review: function to trim whitespace from all items in a list

Hi,

to emphasis the two aspects of the function you could do a grep (removing totally empty list elements) with a map (removing leading and trailing whitespace).

UPDATE: Taste is hardly debatable, but performance often not:

use strict; use warnings; use Data::Dumper; use Benchmark qw(cmpthese); # Returns non-empty strings with leading and trailing spaces removed. sub mytrim_nonempties { grep { $_ ne '' } map { s/^\s+//; s/\s+$//; $_ } @_; } sub trim_nonempties { ## no critic (ProhibitMutatingListFunctions) grep { !/^\s*$/ && s/^\s*|\s*$//g } @_; ## use critic } my @x = ( ' hello ', "\thello again\t", '', " ", " \t", 'jock', "\t ab +c", "def \t " ); cmpthese(1000000, { 'myfunc' => sub { my @y = mytrim_nonempties(@x); }, 'yourfunc' => sub { my @y = trim_nonempties(@x); }, });

McA

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1107983]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-25 20:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found