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

Hi Monks,
I thought it was obvious enough, but apparently I am doing something wrong here:
Say you have the line:
my $string='nick,1,2,,56,88';

I want to capture all elements, including the missing one (between 2 and 56).But if I do this:
my @array = split(/\,/, $string);

it returns 4 and not 5 elements in the array.What am I missing here?
Thanks!

Replies are listed 'Best First'.
Re: Proper way to split a line with the "," delimiter
by Eily (Monsignor) on Aug 17, 2018 at 15:49 UTC

    perl -E "my $string='nick,1,2,,56,88'; my @array = split(/\,/, $string +); my $size = @array; say 'Size: ', $size; say for @array" Size: 6 nick 1 2 56 88
    So it returns 6 elements, not 4 or 5. How do you test the size?

Re: Proper way to split a line with the "," delimiter
by pryrt (Abbot) on Aug 17, 2018 at 15:52 UTC

    as ++Eily said while I was typing this up: unless you throw away the 'nick' element somehow, it's 6 elements. I tried on an ancient linux perl and on a recent windows strawberry perl, and both gave the counts (6) I would expect:

    perl -le 'print $]; @a = split/,/,"nick,1,2,,56,88"; print scalar @a' +; perl -V:osname 5.008005 6 osname='linux';

    and

    perl -le "print $]; @a=split/,/,'nick,1,2,,56,88'; print scalar @a" & +perl -V:osname 5.026002 6 osname='MSWin32';

    edit: and I also meant to say, the proper way to parse CSV is with Text::CSV

Re: Proper way to split a line with the "," delimiter
by thanos1983 (Parson) on Aug 17, 2018 at 16:38 UTC

    Hello Anonymous Monk,

    Just to add something minor here. I My personal preference that helps me a lot to debug my code is Data::Dumper.

    Sample code:

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @array = split(/\,/, 'nick,1,2,,56,88'); print Dumper \@array, scalar @array; __END__ $ perl sample.pl $VAR1 = [ 'nick', '1', '2', '', '56', '88' ]; $VAR2 = 6;

    Hope this helps, BR.

    Seeking for Perl wisdom...on the process of learning...not there...yet!
Re: Proper way to split a line with the "," delimiter
by roboticus (Chancellor) on Aug 17, 2018 at 16:13 UTC

    If I recall correctly, the split function should only remove missing values from the end of your input string:

    $ perl -e 'print scalar(split /,/,"1,2,3,4")' 4 $ perl -e 'print scalar(split /,/,",2,3,4")' 4 $ perl -e 'print scalar(split /,/,"1,,3,4")' 4 $ perl -e 'print scalar(split /,/,"1,2,,4")' 4 $ perl -e 'print scalar(split /,/,"1,2,3,")' 3 $ perl -e 'print scalar(split /,/,"1,2,,")' 2

    You'd best check perldoc -f split to see what it does in detail.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      Hi all, thank you for your answers. I am maybe doing something else wrong then, I will double-check!