[KLUG Members] Perl string trim

Buist Justin members@kalamazoolinux.org
Tue, 30 Jul 2002 11:09:58 -0400


$string =~ s/^\s+//g; # yank leading whitespace out
$string =~ s/\s+$//g; # yank trailing whitespace out

That should do it.

Justin Buist


> -----Original Message-----
> From: Tony Gettig [mailto:gettig@chartermi.net]
> Sent: Tuesday, July 30, 2002 11:05 AM
> To: members@kalamazoolinux.org
> Subject: [KLUG Members] Perl string trim
> 
> 
> Hey there,
> 
> I've looked, googled, and looked again but I must be missing something
> obvious. I have a string I need to trim all the extra spaces 
> off of. For
> instance, if the variable value is "Dude____________" (where all the
> underscores are spaces), I want to do something like 
> STR_TRIM($variable)
> and get "Dude" returned as the result. I tried writing my own function
> to do this, which is below (please remember, I'm not a perl programmer
> :)
> 
> >>>>>>>>>> SNIP <<<<<<<<<<<<<
> sub STR_TRIM()
> {
> $parm1=@_[0];
> for ($i=0; $i<length($parm1);$i++)
>    {
>       if ($parm1[$i]!=' ')
>          {
>             $strtemp=$parm1[$i];
>          }
>    }
> return $strtemp;
> } # end of STR_TRIM
> >>>>>>>>>> SNIP <<<<<<<<<<<<<
> 
> I'm calling it like this:
> 
> $myvar=&STR_TRIM(substr($line, 32, 20));
> 
> $line is one row of a fixed width data file. (Still building LDIF's!)
> Without trimming these strings, name fields end up like this:
> 
> Tony          Gettig
> 
>       ^^^^^^^       ^^^^^^^^^^
>  Note the spaces between and after!
> 
> Is there already a perl function to do what I want to do? Any ideas or
> pointers in the right direction are appreciated. Thanks!
> 
> Tony
> 
> _______________________________________________
> Members mailing list
> Members@kalamazoolinux.org
> 
>