in reply to TRIM in Perl?

I have a problem with that one:

#!/usr/bin/env perl use strict; use warnings; my @strings = (' Test ', 'Test 2 ', ' A ', 'multi line string ',' '); foreach my $string (@strings) { $string =~ s/^\s+//m; $string =~ s/\s+$//m; print "'$string'\n"; }

Returns:

'Test' 'Test 2' 'A' 'multi line string' ''
That is almost correct, but it does remove a line break in the middle of the string it shouldn't: There should be two line breaks between "multi" and "line" but only one remains.

Replies are listed 'Best First'.
Re^2: TRIM in Perl?
by Corion (Patriarch) on Jan 12, 2011 at 10:43 UTC

    Why do you add /m to your regular expressions? See perlop - /m changes the meaning of $ and ^.

Re^2: TRIM in Perl?
by Anonymous Monk on Jan 12, 2011 at 10:42 UTC
    That is almost correct, but it does remove a line break in the middle of the string it shouldn't

    Who says it shouldn't?

    The OP wanted whitespaces removed, that is what \s means, whitespaces (\n, \r, \t, \f, and " ")

    New questions go in Seekers of Perl Wisdom (see Where should I post X?) , don't worry, yours will be moved there shortly
Re^2: TRIM in Perl?
by Anonymous Monk on Feb 10, 2011 at 10:01 UTC
    I wanted the same thing I think - remove leading and trailing space, on a per line basis, ignoring newlines. I've just done this and it seems to work, i.e. linecount remains same before and after.
    cat test.dat | perl -n -e 'chomp; s/^\s+//; s/\s+$//; print "$_\n";'