Ole Tange
Ole Tange

Reputation: 33685

split does not return empty elements

Why do these not all return bbb?

$ perl -e '$a="  "; print map { "b" } split / /, $a;'
<<nothing>>
$ perl -e '$a=",,"; print map { "b" } split /,/, $a;'
<<nothing>>
$ perl -e '$a="  a"; print map { "b" } split / /, $a;'
bbb
$ perl -e '$a=",,a"; print map { "b" } split /,/, $a;'
bbb

I would have expected split to return an array with 3 elements in all cases.

$ perl -V
Summary of my perl5 (revision 5 version 24 subversion 1) configuration:

Upvotes: 1

Views: 212

Answers (1)

ysth
ysth

Reputation: 98388

split's third parameter says how many elements to produce:

split /PATTERN/,EXPR,LIMIT

... 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).

It defaults to 0, which means as many as possible but leaving off any trailing empty elements.

You can pass -1 as the third argument to split to suppress this behavior.

Upvotes: 9

Related Questions