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

> Add 1 if you want to count an incomplete last line, and the string doesn't end with a newline.

better use scalar split, counting the delimiter is unnecessary complexity.

DB<1> $a="1\n2\n3";$b=$a."\n" DB<2> print scalar split /\n/ for $a,$b 33 DB<3> print scalar tr/\n// for $a,$b 23

Cheers Rolf

Replies are listed 'Best First'.
Re^3: Count number of lines in a STRING
by JavaFan (Canon) on May 12, 2010 at 10:10 UTC
    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.