[KLUG Members] Perl string trim

Tony Gettig members@kalamazoolinux.org
30 Jul 2002 11:04:41 -0400


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