Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd behavior with split in perl when result includes empty strings

Tags:

split

perl

This is my perl 5.16 code

while(<>) {
  chomp;
  @data = split /a/, $_;
  print(join("b",@data),"\n");
}

If I input a file with this in it:

paaaa
paaaaq

I get

p
pbbbbq

But I was expecting

pbbbb
pbbbbq

Why am I wrong to expect the latter behavior?

like image 325
Stephen Montgomery-Smith Avatar asked Dec 04 '25 13:12

Stephen Montgomery-Smith


1 Answers

It is documented that trailing empties are removed unless you specify a third, non-zero argument.

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)

You want

split /a/, $_, -1;
like image 76
ikegami Avatar answered Dec 07 '25 15:12

ikegami