in reply to Count number of lines in a STRING

Assuming lines are defined as sequences of non-newline characters terminated by newlines, it's just a matter of counting the number of newlines. Use the tr/// operator for that.
my $nr_of_lines = $str =~ tr/\n//;
Add 1 if you want to count an incomplete last line, and the string doesn't end with a newline.

Replies are listed 'Best First'.
Re^2: Count number of lines in a STRING
by LanX (Saint) on May 12, 2010 at 09:57 UTC
    > 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

      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.
Re^2: Count number of lines in a STRING
by danj35 (Sexton) on May 12, 2010 at 09:45 UTC
    Thanks, that's a nice neat bit of working code with the brackets added. Thanks a lot.