conversecorollary has asked for the wisdom of the Perl Monks concerning the following question:

I have some uncomplicated CSV records to parse and thought the split function would be just fine to use. But I have encountered some oddities that I cannot find an explanation for...

here is the first example:

my $test = "25/May/2011 16:19:02,0,0,4,0.04,5,1,0.08,8.5,,,,,,,,"; my @test = split /,/, $test; foreach (@test){printf "!%s!\n", $_;}

which yields: !25/May/2011 16:19:02! !0! !0! !4! !0.04! !5! !1! !0.08! !8.5! Now if I change the code to:

my $test = "25/May/2011 16:19:02,0,0,4,0.04,5,1,0.08,8.5,,,,,,,,4"; my @test = split /,/, $test; foreach (@test){printf "!%s!\n", $_;}

I now get... !25/May/2011 16:19:02! !0! !0! !4! !0.04! !5! !1! !0.08! !8.5! !! !! !! !! !! !! !! !4! And finally, with a trailing comma:

my $test = "25/May/2011 16:19:02,0,0,4,0.04,5,1,0.08,8.5,,,,,,,,4,"; my @test = split /,/, $test; foreach (@test){printf "!%s!\n", $_;}

The results are: !25/May/2011 16:19:02! !0! !0! !4! !0.04! !5! !1! !0.08! !8.5! !! !! !! !! !! !! !! !4!

So my question is how do I get split to recognize the "trailing" empty fields of the string, when there is only one or multiple, if at all possible?

thanks, gary

Replies are listed 'Best First'.
Re: split ignores "fields"
by moritz (Cardinal) on Jun 09, 2011 at 13:02 UTC

      Thank You!

      Sometimes it just takes a swift kick to point out that which is stated in the docs, but is overlooked and did not register the first few times around.

      Again thank you very much!