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

Hi guys, I have a sentence and I want to split it according to spaces and store in an array. I did  @sen = split(/ /, $sent); But what I sometimes get is  @sen = ('I', 'want', '', 'chocolate', 'and', '', 'icecream') How can I remove the empty scalar values from the array, while keeping it ordered. The above array should become: ('I', 'want', 'chocolate', 'and', 'icecream'). Keep in mind that the array is shifted. Thanks.

Replies are listed 'Best First'.
Re: array problem - splitting array
by Happy-the-monk (Canon) on Nov 25, 2005 at 10:16 UTC

    Allow it so split on more than one blank with the + quantifier as explained in perldoc perlre:

            @sen = split(/ +/, $sent);

    Cheers, Sören

Re: array problem - splitting array
by wfsp (Abbot) on Nov 25, 2005 at 10:29 UTC

    or...

    @sen = split ' ', $str;

    See split

    As a special case, specifying a PATTERN of space (' ') will split on white space...

    hth

Re: array problem - splitting array
by secret (Beadle) on Nov 25, 2005 at 10:29 UTC

    When splitting on space you can use :

    split " ", $sent
    The " " expression does some extra magic which is usualy what you want :)

Re: array problem - splitting array
by GrandFather (Saint) on Nov 25, 2005 at 10:14 UTC
    use strict; use warnings; my @sen = ('I', 'want', '', 'chocolate', 'and', '', 'icecream'); print join '/', @sen; @sen = grep {length} @sen; print "\n" . join '/', @sen;

    Prints:

    I/want//chocolate/and//icecream I/want/chocolate/and/icecream

    DWIM is Perl's answer to Gödel
Re: array problem - splitting array
by Moron (Curate) on Nov 25, 2005 at 14:39 UTC
    The "sometimes" is not an accident without a cause - it happens whenever there is more than one space between words. To split on the pattern that matches the actuality:
    @sen = split( /\s+/, $sent );

    -M

    Free your mind

Re: array problem - splitting array
by tirwhan (Abbot) on Nov 25, 2005 at 10:32 UTC
    for my $word (@sen) { next if ($word =~m/\A\s*\z/); do_something(word); }
    or
    my @clean_sen = grep { !m/\A\s*\z/ } @sen;
    Or split on arbitrary whitespace while generating the array:
    @sen=split(/\s+/,$sent);

    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan