in reply to How to remove trailing space ?

since this is such a commonly done affair... its best to define small functions, say trim (to remove leading and trailing whitespace), trimstart (to remove leading whitespace only ), and trimend (to remove trailing whitespace only), and use them again and again. I have had to do this quite often and find these functions quite useful...Here are the functions, as I use them, as part of a module where I keep my commonly used functions.
use strict; use Data::Dumper; my $line1 = " first "; my $line2 = " second "; print "\nlines to be trimmed...\n"; print Dumper $line1; print Dumper $line2; $line1 = trim ($line1); $line2 = trim ($line2); print "\nafter trimming start and end both...\n"; print Dumper $line1; print Dumper $line2; # in case u have an array.. you can use the map function # say my @array; # and stuff with spaces at the beginning or end or both $line1 = " first "; $line2 = " second "; print "\nlines to be trimmed...\n"; print Dumper $line1; print Dumper $line2; push (@array,$line1); push (@array,$line2); print "\narray to be trimmed...\n"; print Dumper @array; my @array2 = map { trim ($_) } @array; print "\ntrimmed array\n"; print Dumper @array2; # using trimstart and trimend $line1 = " first "; $line2 = " second "; print "\nlines to be trimmed...\n"; print Dumper $line1; print Dumper $line2; $line1 = trimstart ($line1); $line2 = trimend ($line2); print "\ntrimming the start using trimstart...\n"; print Dumper $line1; print "\ntrimming the end using trimend...\n"; print Dumper $line2; sub trim { # remove both leading and trailing whitespace my $line = shift; $line=~s/^\s+|\s+$//g; return $line; } sub trimstart { # remove leading whitespace my $line = shift; $line=~s/^\s+//g; return $line; } sub trimend { # remove trailing whitespace my $line = shift; $line=~s/\s+$//g; return $line; }

perliff

----------------------

-with perl on my side

Replies are listed 'Best First'.
Re^2: How to remove trailing space ?
by Anonymous Monk on Jun 22, 2009 at 13:21 UTC
      cool...now why didn't I look for it before?.. oh well... I guess once I'd coded these trim functions I never looked for a module to do this... as I was already importing these from my own module all the time anyway...

      perliff

      ----------------------

      -with perl on my side