<?xml version="1.0" encoding="windows-1252"?>
<node id="1007027" title="Re: split function" created="2012-12-04 03:11:52" updated="2012-12-04 03:11:52">
<type id="11">
note</type>
<author id="634253">
AnomalousMonk</author>
<data>
<field name="doctext">
&lt;p&gt;
In addition to reviewing the post and accompanying replies linked by [davido], please consider the following code. As noted in the previous discussion, [doc://split] cannot be made to throw an exception if it finds nothing on which to split. Validation of input must be done separately. If you want the process to actually abort on any of the invalid conditions in the code below, replace [doc://warn] wherever it appears with [doc://die] (and also remove the associated &lt;c&gt; and next LINE &lt;/C&gt; expressions, although leaving them in will make no difference; they are simply redundant when used with &lt;c&gt;die&lt;/C&gt;).
&lt;/P&gt;

&lt;c&gt;
&gt;perl -wMstrict -le
"my @lines = (
   'ABCD', 'A|B|C|D', 'A,B,C|D', 'A,B,C', 'A,B,C,D,E', 'A,B,C,D');
 ;;
 LINE:
 for my $line (@lines) {
   print qq{processing '$line'};
   ;;
   warn qq{'$line' has no comma} and next LINE
     if not $line =~ m{,}xms;
   warn qq{'$line' has nasty pipe} and next LINE
     if $line =~ m{ \| }xms;
   ;;
   warn qq{not exactly 4 fields in '$line'} and next LINE
     if 4 != (my ($s, $a, $c, $r) = split /,/, $line);
   ;;
   print qq{success: s '$s'  a '$a'  c '$c'  r '$r'};
   }
"
processing 'ABCD'
'ABCD' has no comma at -e line 1.
processing 'A|B|C|D'
'A|B|C|D' has no comma at -e line 1.
processing 'A,B,C|D'
'A,B,C|D' has nasty pipe at -e line 1.
processing 'A,B,C'
not exactly 4 fields in 'A,B,C' at -e line 1.
processing 'A,B,C,D,E'
not exactly 4 fields in 'A,B,C,D,E' at -e line 1.
processing 'A,B,C,D'
success: s 'A'  a 'B'  c 'C'  r 'D'
&lt;/C&gt;
</field>
<field name="root_node">
1007017</field>
<field name="parent_node">
1007017</field>
</data>
</node>
