Counting occurences?

Counting occurences?

am 06.06.2008 00:54:43 von Barry Brevik

I can't believe this has me stymied, but here goes...

I'm processing a string of chars in a loop, and the string can contain
multiple lines; that is, the string has embedded "\n" chars in it. For
display purposes, I need to count the number of "\n" chars in each
string. Is there a simple way to do this?

Thank you,

Barry Brevik
_______________________________________________
ActivePerl mailing list
ActivePerl@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Re: Counting occurences?

am 06.06.2008 00:59:32 von Michael Ellery

Barry Brevik wrote:
> I can't believe this has me stymied, but here goes...
>
> I'm processing a string of chars in a loop, and the string can contain
> multiple lines; that is, the string has embedded "\n" chars in it. For
> display purposes, I need to count the number of "\n" chars in each
> string. Is there a simple way to do this?
>
>

scalar(split(/\n/, $string)) - 1

....does that work for you?

_______________________________________________
ActivePerl mailing list
ActivePerl@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Re: Counting occurences?

am 06.06.2008 01:38:49 von Bill Luebkert

Barry Brevik wrote:
> I can't believe this has me stymied, but here goes...
>
> I'm processing a string of chars in a loop, and the string can contain
> multiple lines; that is, the string has embedded "\n" chars in it. For
> display purposes, I need to count the number of "\n" chars in each
> string. Is there a simple way to do this?

tr returns the number of characters replaced or deleted, so you could just do:

use strict;
use warnings;
my $str = "abc\ndef\nghi\njkl\nmno\npqr\nstu\nwx\nyz\n";
my $cnt = $str =~ tr/\n/\n/;
print "cnt=$cnt\n";

__END__
_______________________________________________
ActivePerl mailing list
ActivePerl@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs