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

Hi, I have the following code. With my basic understanding of split, i thought that the o/p would be an array with 4 elements as : (,allon,native,).

But the result array after split contains only 3 elements. Why does it not have the 4th(empty) element.

my $str = ";allon;native;;"; my @arr = split /;/, $str; my $indx = 0; foreach (@arr){ print "$indx:$_\n"; $indx++; }

Replies are listed 'Best First'.
Re: Question regarding split
by BrowserUk (Patriarch) on Jan 20, 2014 at 07:03 UTC

    Because:

    Splits the string EXPR into a list of strings and returns that list. By default, empty leading fields are preserved, and empty trailing ones are deleted.

    The first paragraph of split.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      And the fourth paragraph elaborates:
          If LIMIT is specified and positive, it represents the maximum
          number of fields the EXPR will be split into, though the actual
          number of fields returned depends on the number of times
          PATTERN matches within EXPR.  If LIMIT is unspecified or zero,
          trailing null fields are stripped (which potential users of
          "pop" would do well to remember).  If LIMIT is negative, it is
          treated as if an arbitrarily large LIMIT had been specified.
      
Re: Question regarding split
by sn1987a (Curate) on Jan 20, 2014 at 16:15 UTC
    Highlighting a different sentence in the section quoted by Anonymous Monk at Re^2: Question regarding split
    If LIMIT is specified and positive, it represents the maximum
    number of fields the EXPR will be split into, though the actual
    number of fields returned depends on the number of times
    PATTERN matches within EXPR. If LIMIT is unspecified or zero,
    trailing null fields are stripped (which potential users of
    "pop" would do well to remember). If LIMIT is negative, it is
    treated as if an arbitrarily large LIMIT had been specified.

    Just add at LIMIT of -1 to your split. Note: if the last ';' is a terminator instead of a separator, you will have one extra (empty) element at the end of your array:

    my @arr = split /;/, $str, -1; # pop @arr; # to drop the last element

      Beautiful. This is what i wanted.

      Thanks a lot guys...

Re: Question regarding split
by Lennotoecom (Pilgrim) on Jan 20, 2014 at 07:24 UTC
    an option?
    $_ = ';allon;native;;";'; print ">$1<\n" while(s/(?!^)([\w|"]*);//);
    output
    >allon< >native< >< >"<