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

How to eliminate white spaces,tabs,new lines at the start and end of a long string ??
For example,I have a string

"         Sugarkannan is a smart guy            "
I need to get the get the output as

"Sugarkannan is a smart guy"

-Sugar

Replies are listed 'Best First'.
Re: How to eliminate white spaces,tabs,new lines at thestart and end of a long string ??
by sauoq (Abbot) on Nov 24, 2005 at 03:09 UTC
    $string =~ s/^\s+//; $string =~ s/\s+$//;
    -sauoq
    "My two cents aren't worth a dime.";
    

      Or, as I prefer,

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

      Makeshifts last the longest.

        why is that better ?

        Whatever floats your boat... I think that's somewhat less readable, though. But not so much so that I'd complain. I'd expect that doing it without the for would probably be more efficient, so if I found your code in a long loop, I'd likely change it for the more verbose form.

        -sauoq
        "My two cents aren't worth a dime.";
        
Re: How to eliminate white spaces,tabs,new lines at thestart and end of a long string ??
by GrandFather (Saint) on Nov 24, 2005 at 03:28 UTC
    use strict; my $str = "\n Sugarkannan is a smart guy \n"; $str =~ s/^\s*(.*?)\s*$/$1/; print ">$str<\n";

    Prints:

    >Sugarkannan is a smart guy<

    Update: s/printf/print/


    DWIM is Perl's answer to Gödel
      Any particular reason you used printf instead of print? Or just force of habit from C? Just curious.

        Naughty slip of the finger! 'twould be much better as print.


        DWIM is Perl's answer to Gödel
Re: How to eliminate white spaces,tabs,new lines at thestart and end of a long string ??
by secret (Beadle) on Nov 24, 2005 at 09:14 UTC

    Or if you wanted to keep the original string for later :

    $nospace = $1 if $string=~m/^\s*(\w+)\s*$/ ; print $nospace ;

Re: How to eliminate white spaces,tabs,new lines at thestart and end of a long string ??
by metaperl (Curate) on Nov 28, 2005 at 18:47 UTC