Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

remove both leading and trailing spaces

by s_mile (Acolyte)
on Sep 26, 2003 at 06:08 UTC ( [id://294343]=perlquestion: print w/replies, xml ) Need Help??

s_mile has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

Is there a "smart way" :) to remove both the leading and trailing spaces in a string?
One way I know is as below:

$val=" Smart Way "; $val=~s/^\s+//; $val=~s/\s+$//; print '>'.$val.'<'; # shld give me >Smart Way<
Is there a way to do the same in just one statement?

'Ask and ye shall recieve. Seek and ye shall find'.

Blessings

s_mile

update (broquaint): tidied up formatting + removed <br> tags from <code> tags

Replies are listed 'Best First'.
Re: remove both leading and trailing spaces
by perlmonkey (Hermit) on Sep 26, 2003 at 06:16 UTC
    Yes, you can do s/^\s+|\s+$//g but it is definaly not optimized. It is generally preferred to use the two regexes, since it is roughly 3 times faster:
    use Benchmark; my $val = " Smart Way "; timethese(1000000, { regex1 => sub { my $tmp = $val; $tmp =~ s/^\s+|\s+$//g; }, regex2 => sub { my $tmp = $val; $tmp =~ s/^\s+//; $tmp =~ s/\s+$//; } });
    Results:
    Benchmark: timing 1000000 iterations of regex1, regex2... regex1: 9 wallclock secs ( 6.43 usr + 0.02 sys = 6.45 CPU) @ 155038.76/s (n=1000000) regex2: 2 wallclock secs ( 2.65 usr + 0.00 sys = 2.65 CPU) @ 377358.49/s (n=1000000)
Re: remove both leading and trailing spaces
by davido (Cardinal) on Sep 26, 2003 at 06:18 UTC
    Welcome to the Monastery!

    If you want to do it in one statement, you can do this:

    my $val = " Smart Way "; $val =~ s/^\s+|\s+$//g; print '>', $val, '<';

    You asked for a one-line solution. That will do it. A better solution (still using s///) is two lines, since alternation is expensive if you value time efficiency.

    I feel somewhat guilty for having retyped an answer that has been provided right at our fingertips in the Q&A section under the heading, How do I remove whitespace at the beginning or end of my string?. If you look there you'll see a lot of different alternatives of which one is sure to be right for any occasion. ;) This being your first post I just want to encourage you to familiarize yourself with the more helpful aspects of the Monastery such as the Q&A section, and the Tutorials section. The Q&A section is a FAQ of sorts; not a place to post questions, but rather, a place to post answers to common questions. You'll find a wealth of information there, most good, some just ok, but all there for edification. It also is a great idea to become familiar with the perldocs. If you have Perl, you have the perldocs. If you prefer reading them online, you can find them right here in the Monastery as well. Enjoy!

    Oh, this isn't related to your question, but rather, to the presentation of your question. I wanted to mention that you don't need to use <br> tags to create new lines within <code></ code> tags. Take a look at how your original post looks and you'll see what I mean. You did preview right?

    Dave

    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein

      Hey Thanks to both of you, I presumed that one statement means less computing time,
      but your posts proved that's not always the case.
      Cool & Thanks for your inputs Davido, ..will go thru em.
      Blessings

      s_mile
        If you want to know why, then I recommend you get a copy of Jeffrey Friedl's book "Mastering Regular Expressions". It explains exactly how this sort of thing works and the how to develop regular expressions efficiently.
Re: remove both leading and trailing spaces
by Jasper (Chaplain) on Sep 26, 2003 at 11:13 UTC
    Another alternative:
    $val =~ s/^\s*(.*?)\s*$/$1/;
      That was my first thought also. I was just curious if it was faster than s/^\s+|\s+$//g;
      use Benchmark; my $val = " Smart Way "; timethese(1000000, { regex1 => sub { my $tmp = $val; $tmp =~ s/^\s*(.*?)\s*$/$1/g; }, regex2 => sub { my $tmp = $val; $tmp =~ s/^\s+//; $tmp =~ s/\s+$//; } }); __OUTPUT__ Benchmark: timing 1000000 iterations of regex1, regex2... regex1: 8 wallclock secs ( 8.10 usr + 0.00 sys = 8.10 CPU) @ 12 +3426.31/s (n=1000000) regex2: 2 wallclock secs ( 1.96 usr + 0.00 sys = 1.96 CPU) @ 50 +9164.97/s (n=1000000)

      --

      flounder

Re: remove both leading and trailing spaces
by Anonymous Monk on Sep 26, 2003 at 16:18 UTC
    $val=" Smart Way "; $val=~s/(^\s+|\s+$)//g; print '>'.$val.'<';
      I find this way to be pretty fast on windoze, can someone benchmark it?
      #!/usr/bin/perl -w use strict; my $val=" Smart Way "; $val = join (" ",split " ",$val); print '>'.$val.'<'; # shld give me >Smart Way<
        #!/usr/bin/perl -w use strict; use Benchmark; my $val=" Smart Way "; timethese(1000000, { regex1 => sub { my $tmp = $val; $tmp =~ s/^\s*(.*?)\s*$/$1/g; }, regex2 => sub { my $tmp = $val; $val = join (" ",split " ",$val); }, regex3 => sub { my $tmp = $val; $tmp =~ s/^\s+//; $tmp =~ s/\s+$//; } });

        __OUTPUT__
        Benchmark: timing 1000000 iterations of regex1, regex2, regex3...
        regex1: 6 wallclock secs ( 5.25 usr + 0.00 sys = 5.25 CPU) @ 190512.48/s (n=1000000)
        regex2: 2 wallclock secs ( 1.83 usr + 0.00 sys = 1.83 CPU) @ 547045.95/s (n=1000000)
        regex3: 2 wallclock secs ( 1.02 usr + 0.00 sys = 1.02 CPU) @ 984251.97/s (n=1000000)
Re: remove both leading and trailing spaces
by Ordinary_User (Beadle) on Sep 26, 2003 at 21:09 UTC
    Given that $val holds the text as you describe in your code, I'd be using the following:

    $val =~ s/ //g;

    This will remove all "blanks" from the string and replace them with "nothing", thus removing all blanks from the string, in one swift stroke.

    The "g" is important! Without it, it will only remove one blank from the string.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://294343]
Approved by davido
Front-paged by htoug
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2024-03-28 10:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found