I think the advice of choroba and Tux to base your solution on Text::CSV is well taken. But I'm a hopeless regex junky, so here's that approach (requires Perl verion 5.10 or greater):
c:\@Work\Perl\monks>perl -wMstrict -le
"use 5.010;
;;
my @records = (
',P,Q,R,S',
'A,,D,E,F',
'L,T,,G,Q',
'C,D,E,,L',
'V,W,X,Y,',
' , , , ,',
',,,,',
',',
' , ',
'',
' ',
);
;;
for my $rec (@records) {
print qq{'$rec'};
$rec =~ s{
(?: \A | ,) \K \s* (?= ,) | (?<= ,) \s* (?= , | \z) | \A \s* \z
}{NULL}xmsg;
print qq{'$rec' \n};
}
"
',P,Q,R,S'
'NULL,P,Q,R,S'
'A,,D,E,F'
'A,NULL,D,E,F'
'L,T,,G,Q'
'L,T,NULL,G,Q'
'C,D,E,,L'
'C,D,E,NULL,L'
'V,W,X,Y,'
'V,W,X,Y,NULL'
' , , , ,'
'NULL,NULL,NULL,NULL,NULL'
',,,,'
'NULL,NULL,NULL,NULL,NULL'
','
'NULL,NULL'
' , '
'NULL,NULL'
''
'NULL'
' '
'NULL'
The only problematic case is the '' or ' ' empty/blank string, but if you don't like how that's handled, it's easy to take the \A \s* \z term out of the alternation or change it.
Give a man a fish: <%-{-{-{-<
|