Perl split with empty text before/after delimiters

Viewed 16549

I was noticing some curious behavior with Perl's split command, particularly in cases when I would expect the resulting array to contain empty strings '', but it actually doesn't.

For example, if I have a delimiter(s) at the end (or the beginning) of the string , the resulting array does not have an empty string(s) '' as the last (or first) element.

Example:

@s = split(/x/, 'axb')

produces 2 element array ['a','b']

@s = split(/x/, 'axbx')

produces same array

@s = split(/x/, 'axbxxxx')

produces same array

But as soon as I put something at the end, all those empty strings do appear as elements:

@s = split(/x/, 'axbxxxxc')

produces a 6 element array ['a','b','','','','c']

Behavior is similar if the delimiters are at the beginning.

I would expect empty text between, before, or after delimiters to always produce elements in the split. Can anyone explain to me why the split behaves like this in Perl? I just tried the same thing in Python and it worked as expected.

Note: Perl v5.8

1 Answers
Related