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

$ perl -E'say scalar( split( /\./, q{.} ));' 0 $ perl -E'say scalar( split( q{.}, q{.} ));' 0

Why don't I get an array of two empty strings?

Replies are listed 'Best First'.
Re: Bug in split?
by haukex (Archbishop) on Sep 27, 2017 at 13:53 UTC

    From split (emphasis mine):

    If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced. If LIMIT is omitted (or, equivalently, zero), then it is usually treated as if it were instead negative but with the exception that trailing empty fields are stripped (empty leading fields are always preserved); if all fields are empty, then all fields are considered to be trailing (and are thus stripped in this case).
    $ perl -E'say scalar( split( /\./, q{.}, -1 ));' 2 $ perl -E'say scalar( split( q{.}, q{.}, -1 ));' 2

    Update: BTW, your two patterns are not identical:

    $ perl -MData::Dump -e 'dd split( /\./, q{.x.} )' ("", "x") $ perl -MData::Dump -e 'dd split( q{.}, q{.x.} )' () $ perl -MData::Dump -e 'dd split( /\./, q{.x.}, -1 )' ("", "x", "") $ perl -MData::Dump -e 'dd split( q{.}, q{.x.}, -1 )' ("", "", "", "")

      In other words, it's backward. This is what you get when you inherit from othe languages. Sigh.

        "...what you get when you inherit from other languages..."

        My predecessors already pointed out that split works as designed. So just for curiosity: May i ask which other languages you mean?

        Regards, Karl

        «The Crux of the Biscuit is the Apostrophe»

        perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help

Re: Bug in split?
by Corion (Patriarch) on Sep 27, 2017 at 13:44 UTC

    Because that's what split is documented to do?

    Splits the string EXPR into a list of strings and returns the list in list context, or the size of the list in scalar context. (Prior to Perl 5.11, it also overwrote @_ with the list in void and scalar context. If you target old perls, beware.)