in reply to Re^2: Count number of lines in a STRING
in thread Count number of lines in a STRING

Two problems with scalar split: 1) pre-5.12, it will globber @_. 2) it's incorrect:
print scalar split /\n/ for "1\n2\n3\n\n"; # Prints 3 instead of 4
Using a negative third argument doesn't solve the problem:
print scalar split /\n/, $_, -1 for "1\n2\n3\n\n"; # Prints 5
you'd have to subtract 1, but only if the string ends in a new line - so you end up looking at the end as well.

As for the complexity:

print tr/\n// + !/\n\z/;
even gives the correct results in list context.

Replies are listed 'Best First'.
Re^4: Count number of lines in a STRING
by LanX (Saint) on May 12, 2010 at 10:48 UTC