[sf-perl] amusing bug

Joe Brenner doom at kzsu.stanford.edu
Tue May 4 15:25:51 PDT 2010

> > Joe Brenner <doom at kzsu.stanford.edu>

> > > The one I like is
> > >
> > >   $line =~ s{ ^ \s+ (.*?) \s+ $ }{ $1 }x;
> > >
> > > It always takes me awhile to figure out why the leading and
> > > trailing spaces aren't all going away.

Steve Fink <sphink at gmail.com> wrote:

> You might want to also make those +s into *s... (you're requiring
> lines to have whitespace on *both* sides before you'll fix 'em.)

Good point.

Garth Webb <garth.webb at gmail.com> wrote:

> Or just match the bits you care about:
>   $line =~ s/^\s+|\s+$//g;

Which works because of the /g, of course.  I think readbility
suffers a bit though (at first glance it looks like it'll only
do one side or the other).

Incidentally, there's some talk on the perl5porters list about
adding a "trim" function to the perl core.

And there is, of course, a CPAN module to do this:


This might seem like overkill, except that it'll prevent you from
making bonehead mistakes with using \s+ instead of \s*.

More information about the SanFrancisco-pm mailing list