Changing Characters in Strings Using Perl Regular Expressions

This illustrates how we can use regular expressions to swap characters. This version changes any spaces in a string to underlines which is great for moving files from Windows to Unix!

sub SpaceToUnderline
{
   my @out = @_;
   TraceScript $Paranoid, "SpaceToUnderline", "About to change string";
   for (@out)
   {
       s/\s/_/g;
   }
   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)...

$ChangedString =
SpaceToUnderline $OriginalString;






Find out more by searching Google here...


Google
="" src="../../ThumbUp.gif" align="right">