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

trim function example for perlfaq4.pod

Thread Next
From:
David Nicol
Date:
April 9, 2010 16:13
Subject:
trim function example for perlfaq4.pod
Message ID:
t2v934f64a21004091612hb8095399q63d43deeb92c1a5a@mail.gmail.com
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, and works on C<$_> in the absence of
+other input:
+
+   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?

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