In Perl, if I split a string containing newlines, like this;
@fields = split /\n/, "\n\n\n";
@fields is empty.
More examples:
@fields = split /\n/, "A\nB\nC"; # 3 items ("A","B","C") as expected
@fields = split /\n/, "A\n\nC"; # 3 items ("A","","C") as expected
@fields = split /\n/, "A\nB\n"; # 2 items ("A","B" ) NOT as expected
@fields = split /\n/, "\nB\nC"; # 3 items ("","B","C") as expected
@fields = split /\n/, "A\n\n"; # 1 items ("A") NOT as expected
It's acting like trailing newlines are ignored.
If my string contains 3 newlines, and I'm splitting on the newline character, why doesn't my array always contain 3 items?
Is there a way I can do this?
btw, I get the same results on all versions of Perl that I have (5.34.0, 5.30.3, 5.22.1 and 5.18.2)
@fields = split /\n/, "\n\n\n", -1;
andprint scalar @fields . "\n";
shows the expected4
. – Hertahertberg