develooper Front page | perl.perl5.porters | Postings from April 2010

Re: trim function example for perlfaq4.pod

Thread Previous | Thread Next
From:
Aristotle Pagaltzis
Date:
April 9, 2010 16:50
Subject:
Re: trim function example for perlfaq4.pod
Message ID:
20100409234744.GA22175@klangraum.plasmasturm.org
* David Nicol <davidnicol@gmail.com> [2010-04-10 01:15]:
> diff --git a/pod/perlfaq4.pod b/pod/perlfaq4.pod
> index f671b62..8a84490 100644
> --- a/pod/perlfaq4.pod
> +++ b/pod/perlfaq4.pod
> @@ -928,6 +928,27 @@ you have to do a little more work. Instead of matching
> any
>  (since that includes a newline), just match the other whitespace.
>
>         $string =~ s/^[\t\f ]+|[\t\f ]+$//mg;
> +
> +(contributed by David Nicol)
> +
> +Here is a trim function that operates in-place in void context, in-line
> +in scalar and array contexts, takes an alternate regular expression
> +as an optional last argument,

Meaning if that happens to be in your data for some strange
reason, and you didn’t pass one yourself, this `trim` will do
something completely different from what you intended.

Admittedly this is an very edgy edge case. But it’s these that
tend to pop out and bite you at the strangest times.

Worse:

> +                              and works on C<$_> in the absence of
> +other input:

    my @foo = trim grep /bar/, ' baz ', ' quux ';

Wait, why did that trim my $_?

Oops.

> +
> +   use constant Regexp_type => ref qr/bzzt/;
> +   sub trim{
> +     my $R = (ref $_[-1] eq Regexp_type ? pop : qr/\s/ );
> +     @_ or return trim($_,$R);
> +     wantarray and return map { s/\A$R+//; s/$R+\Z//; $_ } my @copy = @_;
> +     defined wantarray and return do {
> +        my $copy = shift;
> +        @_ and Carp::croak 'too many arguments for trim in scalar context';
> +        $copy =~ s/\A$R+//; $copy =~ s/$R+\Z//; $copy;
> +     };
> +     do { s/\A$R+//; s/$R+\Z// }  for  @_;
> +   }
> +
>
>  =head2 How do I pad a string with blanks or pad a number with zeroes?

I don’t think this patch is up to perlfaq standards. Sorry. :-(

-- 
*AUTOLOAD=*_;sub _{s/(.*)::(.*)/print$2,(",$\/"," ")[defined wantarray]/e;$1}
&Just->another->Perl->hack;
#Aristotle Pagaltzis // <http://plasmasturm.org/>

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About