FAQ 4.32 How do I strip blank space from the beginning/end of a string?

FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 27.07.2007 21:03:02 von PerlFAQ Server

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

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

4.32: How do I strip blank space from the beginning/end of a string?

(contributed by brian d foy)

A substitution can do this for you. For a single line, you want to
replace all the leading or trailing whitespace with nothing. You can do
that with a pair of substitutions.

s/^\s+//;
s/\s+$//;

You can also write that as a single substitution, although it turns out
the combined statement is slower than the separate ones. That might not
matter to you, though.

s/^\s+|\s+$//g;

In this regular expression, the alternation matches either at the
beginning or the end of the string since the anchors have a lower
precedence than the alternation. With the "/g" flag, the substitution
makes all possible matches, so it gets both. Remember, the trailing
newline matches the "\s+", and the "$" anchor can match to the physical
end of the string, so the newline disappears too. Just add the newline
to the output, which has the added benefit of preserving "blank"
(consisting entirely of whitespace) lines which the "^\s+" would remove
all by itself.

while( <> )
{
s/^\s+|\s+$//g;
print "$_\n";
}

For a multi-line string, you can apply the regular expression to each
logical line in the string by adding the "/m" flag (for "multi-line").
With the "/m" flag, the "$" matches *before* an embedded newline, so it
doesn't remove it. It still removes the newline at the end of the
string.

$string =~ s/^\s+|\s+$//gm;

Remember that lines consisting entirely of whitespace will disappear,
since the first part of the alternation can match the entire string and
replace it with nothing. If need to keep embedded blank lines, you have
to do a little more work. Instead of matching any whitespace (since that
includes a newline), just match the other whitespace.

$string =~ s/^[\t\f ]+|[\t\f ]+$//mg;



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

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.

--
Posted via a free Usenet account from http://www.teranews.com

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 01.08.2007 20:55:44 von dalessio

"PerlFAQ Server" wrote in message
news:64spn4-1kn.ln1@blue.stonehenge.com...
....
> 4.32: How do I strip blank space from the beginning/end of a string?
>
> (contributed by brian d foy)
>
> A substitution can do this for you. For a single line, you want to
> replace all the leading or trailing whitespace with nothing. You can do
> that with a pair of substitutions.
>
> s/^\s+//;
> s/\s+$//;

This is such a common task that I think it would be
worthwhile to have a dedicated, more efficient command
for it, similar to chomp/chop.

And what would be a good name for the command?

Mario

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 02.08.2007 11:37:39 von Jean-Baptiste Mazon

"Mario D'Alessio" writes:

> "PerlFAQ Server" wrote in message
> news:64spn4-1kn.ln1@blue.stonehenge.com...
>> s/^\s+//;
>> s/\s+$//;
>
> This is such a common task that I think it would be
> worthwhile to have a dedicated, more efficient command
> for it, similar to chomp/chop.
>
> And what would be a good name for the command?

"trim"

It's already in countless CPAN modules. Seems to me it was so
worthwhile to have a dedicated command that many authors wrote
one themselves.

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 02.08.2007 12:49:52 von Michele Dondi

On Wed, 1 Aug 2007 13:55:44 -0500, "Mario D'Alessio"
wrote:

>> s/^\s+//;
>> s/\s+$//;
>
>This is such a common task that I think it would be
>worthwhile to have a dedicated, more efficient command
>for it, similar to chomp/chop.

I don't think so. That would be much in the php philosophy. Perl is
already a "large" language, but it still provides relatively simple
tools that linked together make for a synergic effect.

And as for efficiency... is the provided solution not fast enough? I
can't imagine many situations in which this would matter.

>And what would be a good name for the command?

stripwhitespace() ?


Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^ ..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER 256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 02.08.2007 17:47:01 von dalessio

"Michele Dondi" wrote in message
news:sfd3b3lfnphuk3qa9vked52olhd108e02f@4ax.com...
> On Wed, 1 Aug 2007 13:55:44 -0500, "Mario D'Alessio"
> wrote:
>
>>> s/^\s+//;
>>> s/\s+$//;
>>
>>This is such a common task that I think it would be
>>worthwhile to have a dedicated, more efficient command
>>for it, similar to chomp/chop.
>
> I don't think so. That would be much in the php philosophy. Perl is
> already a "large" language, but it still provides relatively simple
> tools that linked together make for a synergic effect.
>
> And as for efficiency... is the provided solution not fast enough? I
> can't imagine many situations in which this would matter.

I never timed it, but I wondered if the processing of a
regex makes it less efficient than a dedicated command
similar to chomp.

Mario

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 03.08.2007 12:02:02 von Michele Dondi

On Thu, 2 Aug 2007 10:47:01 -0500, "Mario D'Alessio"
wrote:

>> And as for efficiency... is the provided solution not fast enough? I
>> can't imagine many situations in which this would matter.
>
>I never timed it, but I wondered if the processing of a
>regex makes it less efficient than a dedicated command
>similar to chomp.

The general answer is that you should not care, and if you do care
then you shouldn't program in Perl. If you're really concerned you may
try writing an XS version of your command and benchmark it along with
the regex based one.


Ciao,
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^ ..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER 256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 01.09.2007 23:42:57 von dkcombs

I'm wondering how many perl programmers have always-include
libraries of useful functions, one of them being "trim".

So, have a poll, and decide based on that.

David

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 02.09.2007 01:50:33 von Sherm Pendley

dkcombs@panix.com (David Combs) writes:

> I'm wondering how many perl programmers have always-include
> libraries of useful functions, one of them being "trim".

We all do - it's called "CPAN".

sherm--

--
Web Hosting by West Virginians, for West Virginians: http://wv-www.net
Cocoa programming in Perl: http://camelbones.sourceforge.net

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 02.09.2007 04:44:25 von Petr Vileta

Sherm Pendley wrote:
> dkcombs@panix.com (David Combs) writes:
>
>> I'm wondering how many perl programmers have always-include
>> libraries of useful functions, one of them being "trim".
>
> We all do - it's called "CPAN".
>
> sherm--
Yes, you are right sherm ;-) But, frankly speaking, the trim() is the
function which absent in Perl. Everytime I write script for string
manupulation and I plan to write more then 50 lines I write this

sub trim
{
my $t = shift;
$t =~s/^\s*|\s*$//sg;
return $t;
}

sub ltrim
{
my $t = shift;
$t =~s/^\s*//s;
return $t;
}

sub rtrim
{
my $t = shift;
$t =~s/\s*$//s;
return $t;
}

--

Petr Vileta, Czech republic
(My server rejects all messages from Yahoo and Hotmail. Send me your mail
from another non-spammer site please.)

Re: FAQ 4.32 How do I strip blank space from the beginning/end of astring?

am 02.09.2007 05:46:56 von Uri Guttman

>>>>> "PV" == Petr Vileta writes:

PV> sub trim
PV> {
PV> my $t = shift;
PV> $t =~s/^\s*|\s*$//sg;

that is known to be slower than doing left and right trim in separate
operations. google for this and you will see plenty of benchmarks

the /s modifier is useless as you don't use . in the regex.

replacing \s* will happen for every string which is wasteful. use \s+ so
you only replace when you have at least one \s.

PV> sub ltrim
PV> {
PV> my $t = shift;
PV> $t =~s/^\s*//s;
PV> return $t;
PV> }

PV> sub rtrim
PV> {
PV> my $t = shift;
PV> $t =~s/\s*$//s;
PV> return $t;
PV> }

the above comments apply to those as well except for the using two s///
ops.

if you use those subs a lot (and i never seem to need them) you might as
well write them well so they run faster.

uri

--
Uri Guttman ------ uri@stemsystems.com -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org

Re: FAQ 4.32 How do I strip blank space from the beginning/end ofa string?

am 02.09.2007 09:08:49 von Mark Clements

David Combs wrote:
> I'm wondering how many perl programmers have always-include
> libraries of useful functions, one of them being "trim".

I almost always use String::Strip for that.

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 02.09.2007 15:40:04 von Michele Dondi

On Sat, 1 Sep 2007 21:42:57 +0000 (UTC), dkcombs@panix.com (David
Combs) wrote:

>I'm wondering how many perl programmers have always-include
>libraries of useful functions, one of them being "trim".
>
>So, have a poll, and decide based on that.

First of all, please quote some context... inter alia this is a very
old thread... it would help. Coming to your question, it depends:
people use CPAN and own modules all the time, and not only for very
complex stuff that would require thousands of lines of code, but even
simpler things. One example that springs to mind is given by
List::Util's functions: I'm increasingly willing to to use the module
even if I just need one or two of them in one or two places in a tiny
script, and I'm not concerned with "efficiency". Similarly with e.g.
File::Basename. But as far as the hypothetical trim() function goes:
well, for one thing I've not needed it that often, and no, I wouldn't
probably use a library for it but stick to a plain

s/^\s+//, s/\s+$// for $string; # instead


My two eurocents,
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^ ..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER 256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 02.09.2007 15:41:09 von Michele Dondi

On Sun, 2 Sep 2007 04:44:25 +0200, "Petr Vileta"
wrote:

>Yes, you are right sherm ;-) But, frankly speaking, the trim() is the
>function which absent in Perl. Everytime I write script for string
>manupulation and I plan to write more then 50 lines I write this

I don't want to distrust you, but I'm astonished... I just happen not
to need this kinda things so often.


Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^ ..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER 256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 02.09.2007 17:42:03 von Petr Vileta

Michele Dondi wrote:
> On Sun, 2 Sep 2007 04:44:25 +0200, "Petr Vileta"
> wrote:
>
>> Yes, you are right sherm ;-) But, frankly speaking, the trim() is the
>> function which absent in Perl. Everytime I write script for string
>> manupulation and I plan to write more then 50 lines I write this
>
> I don't want to distrust you, but I'm astonished... I just happen not
> to need this kinda things so often.
>
>
> Michele
Characteristic case is web form and putting fields to database. For example
user name, address or phone number. Many users type some like
" John Doe"
"Victory str. 60, London "
"+420 220 130 150"
Before I put these data to database I want to "normalise" it for future
comparing for duplicity.

" John Doe"
and
"John Doe"
is not the same for computer but is the same for human. So I must replace
all "more spaces" with "single space", and remove leading and trailing
spaces. Phone number must be a number not a string, so
"+420 220 130 150"
must be translated to
"420220130150"

--

Petr Vileta, Czech republic
(My server rejects all messages from Yahoo and Hotmail. Send me your mail
from another non-spammer site please.)

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 03.09.2007 00:37:02 von sln

On Sat, 1 Sep 2007 21:42:57 +0000 (UTC), dkcombs@panix.com (David Combs) wrote:

>I'm wondering how many perl programmers have always-include
>libraries of useful functions, one of them being "trim".
>
>So, have a poll, and decide based on that.
>
>David
>

It would appear that a useful library may be fashioned out of
the MFC CString class, which has all the goodies. Trivial but usefull.

or try this:

TrimTheFat
{
my $string_ref = @_;
$$string_ref =~ s/^\s+//;
$$string_ref =~ s/\s+$//;
# add other fat trimming you would like
# ie: double slashes, double periods, etc..
}

my $fatstring = "This here is a fat string";
TrimTheFat ( \$fatstring);

Re: FAQ 4.32 How do I strip blank space from the beginning/end of astring?

am 03.09.2007 03:17:24 von Uri Guttman

>>>>> "s" == sln writes:

s> or try this:

why should we try it? it has a major bug. and it isn't valid perl.

s> TrimTheFat

no sub

s> {
s> my $string_ref = @_;

that doesn't assign what you think it does

s> $$string_ref =~ s/^\s+//;
s> $$string_ref =~ s/\s+$//;
s> # add other fat trimming you would like
s> # ie: double slashes, double periods, etc..

those would be options and not useful for a fast white space trimmer.

s> }

like michele said, this is too trivial to need a sub or a library.

uri

--
Uri Guttman ------ uri@stemsystems.com -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 03.09.2007 07:45:10 von Anno Siegel

On 2007-09-03 03:17:24 +0200, Uri Guttman said:

>>>>>> "s" == sln writes:
>
> s> or try this:
>
> why should we try it? it has a major bug. and it isn't valid perl.
>
> s> TrimTheFat
>
> no sub
>
> s> {
> s> my $string_ref = @_;
>
> that doesn't assign what you think it does
>
> s> $$string_ref =~ s/^\s+//;
> s> $$string_ref =~ s/\s+$//;
> s> # add other fat trimming you would like
> s> # ie: double slashes, double periods, etc..
>
> those would be options and not useful for a fast white space trimmer.
>
> s> }

Also, there's no need to use a reference:

sub trim { s/^\s+//, s/\s+$// for shift }

> like michele said, this is too trivial to need a sub or a library.

That too.

Anno
>

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 03.09.2007 09:54:14 von rvtol+news

Petr Vileta schreef:

> sub trim {
> my $t = shift;
> $t =~s/^\s*|\s*$//sg;
> return $t;
> }

Please read `perldoc -q space`.

The '*' quantifier should be '+'. The /s modifier should not be there.
The substitution is faster when split up, then the /g modifier is also
gone.


Variant:

sub trim { s/^\s+//, s/\s+$// for @_ }

but beware that this will change the parameter(s) themselves.


(the same comments go for the rest)

--
Affijn, Ruud

"Gewoon is een tijger."

Re: FAQ 4.32 How do I strip blank space from the beginning/end of a string?

am 03.09.2007 15:05:42 von Petr Vileta

Dr.Ruud wrote:
> Petr Vileta schreef:
>
>> sub trim {
>> my $t = shift;
>> $t =~s/^\s*|\s*$//sg;
>> return $t;
>> }
>
> Please read `perldoc -q space`.
>
> The '*' quantifier should be '+'. The /s modifier should not be there.
> The substitution is faster when split up, then the /g modifier is also
> gone.
>
Yes, a quantifier I had bad, but /s modifier I must use because
" abcd\n efgh\n "
must return
"abcd\n efgh"
This is for input from