Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: trim() magic

by dragonchild (Archbishop)
on Mar 30, 2005 at 14:21 UTC ( [id://443464]=note: print w/replies, xml ) Need Help??


in reply to trim() magic

On the theory that storing the return from wantarray is always faster than computing it between 2 and 4 times, I was going to suggest the following:
sub trim { if (defined my $w = wantarray) { @_ = ( @_ ? @_ : $_ ); for (@_) { s/^\s+//, s/\s+$// if $_ } return $w ? @_ : $_[0]; } else { for (@_ ? @_ : $_) { s/^\s+//, s/\s+$// if $_ } } }
The if $_ is to protect against warnings for undefined values.

Unfortunately, it turns out that I was wrong. Your version is usually faster than mine. The only place I'm faster is my $x = trim();. I'm not sure that case is worth making the code harder to read. (Though, if this were added to something like Scalar::Util, I would code it my way.)

cmpthese( -1, { japhy => sub { $_ = ' asdf '; trim1(); }, dchild => sub { $_ = ' asdf '; trim2(); }, }); Rate dchild japhy dchild 82708/s -- -3% japhy 85163/s 3% -- cmpthese( -1, { japhy => sub { $_ = ' asdf '; my $n = trim1(); }, dchild => sub { $_ = ' asdf '; my $n = trim2(); }, }); Rate japhy dchild japhy 42766/s -- -12% dchild 48873/s 14% -- cmpthese( -1, { japhy => sub { my $x = ' asdf '; my $n = trim1( $x ); }, dchild => sub { my $x = ' asdf '; my $n = trim2( $x ); }, }); Rate dchild japhy dchild 47733/s -- -5% japhy 50243/s 5% -- cmpthese( -1, { japhy => sub { $_ = ' asdf '; my @n = trim1( ); }, dchild => sub { $_ = ' asdf '; my @n = trim2( ); }, }); Rate japhy dchild japhy 39628/s -- -8% dchild 43115/s 9% -- cmpthese( -1, { japhy => sub { my @l = (' asdf '); my @n = trim1(@l); }, dchild => sub { my @l = (' asdf '); my @n = trim2(@l); }, }); Rate dchild japhy dchild 39628/s -- -3% japhy 40959/s 3% --

Being right, does not endow the right to be rude; politeness costs nothing.
Being unknowing, is not the same as being stupid.
Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-23 13:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found