Re: TRIM in Perl?
by jmcnamara (Monsignor) on Sep 10, 2002 at 14:05 UTC
|
| [reply] [Watch: Dir/Any] |
Re: TRIM in Perl?
by samurai (Monk) on Sep 10, 2002 at 15:36 UTC
|
No, that will NOT drop the leading and trailing spaces. Only the leading spaces (you are anchored by "^").
There's no sub for trimming strings in perl. The best way is probably to just go ahead and bite the bullet:
my $temp = " Hello ";
$temp =~ s/^\s+//;
$temp =~ s/\s+$//;
You can write your own trim() function to automate this if you wish.
--
perl: code of the samurai | [reply] [Watch: Dir/Any] [d/l] |
|
| [reply] [Watch: Dir/Any] [d/l] |
|
| [reply] [Watch: Dir/Any] |
Re: TRIM in Perl?
by charnos (Friar) on Sep 10, 2002 at 16:31 UTC
|
Since with all the suggestions here we're just eliminating all spaces in the string, wouldn't simple transliteration ($temp =~ tr/ //d;) be faster/simpler?
Update: EEK! *bangs head* Nevermind, I retract that, $temp =~ s/^\s+|\s$/ would be the best way to do it.
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
| [reply] [Watch: Dir/Any] |
Re: TRIM in Perl?
by Rabenschwinge (Novice) on Jan 12, 2011 at 10:34 UTC
|
#!/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. | [reply] [Watch: Dir/Any] [d/l] [select] |
|
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
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
| [reply] [Watch: Dir/Any] [d/l] |
|
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";'
| [reply] [Watch: Dir/Any] [d/l] |