Removing White Space From the Beginning and End of Perl Strings

This is required so frequently that it's worth setting up a standard sub-routine to do it. This example is based on one found in the Perl Cookbook and all I've done is to add a few comments and a call to TraceScript...

sub trim
{
   my @out = @_;
   TraceScript $Paranoid, "trim", "About to trim string";
   TraceScript $Paranoid, "trim", "Untrimmed = " . $_[0];
   for (@out)
   {
       s/^\s+//;          # trim left
       s/\s+$//;          # trim right
   }
   return @out == 1
              ? $out[0]   # only one to return
              : @out;     # or many
}

It makes use of Perl's regular expression processing. There is a speed overhead in calling the regular expression parser but sometimes that's a cost worth bearing, as here, when the simplicity of the code outweighs the price in speed of execution.

To use this just store the result of the call in a suitable variable (or whatever)...

$TrimmedString = trim $UntrimmedString;





Find out more by searching Google here...

Google