Splitting Delimited Strings in Perl

Perl is very good at handling strings and one of the most useful Perl functions for string handling is 'split'. Put simply, you pass split a regular expression and a value and split returns an array formed from the value but broken at each point that the subject of the regular expression appears.

Say, for example, you wrote ...

@Result = split(/:/, "apples:oranges:pears"

then @Result would contain the elements

apples
oranges
pears

with the dividing ':' discarded. The following real example is for extracting the required item from a comma-delimited list, such as a line in a CSV file...

sub GetCsvElement
{
   my @V_ARRAY;
   my $P_ELEMENT = $_[0];
   my $P_SOURCE_STRING = $_[1];
   my $V_RESULT;

   TraceScript $Paranoid,
               "GetCsvElement",
               "Selecting element ["
                . $P_ELEMENT
                . "] from line ["
                . $P_SOURCE_STRING
                . "]";

   # -----------------------------------
   # Drop the elements into our array...
   # -----------------------------------
   @V_ARRAY = split (/,/, $P_SOURCE_STRING);

   # ----------------------------------------------------------------
   # Arrays are zero based so we pick one less than the passed value!
   # ----------------------------------------------------------------
   $V_RESULT = trim $V_ARRAY[--$P_ELEMENT];

   # ----------------------------
   # Return the requested item...
   # ----------------------------
   TraceScript $Paranoid,
               "GetCsvElement",
               "Selected element is ["
               . $V_RESULT
               . "]";
   return $V_RESULT;
}





Find out more by searching Google here...


Google