#!C:/perl/bin/perl -w
use strict;
my $str = 'abcsfsaf#sdagasdga#sdgaghoiiopjh#dsfjkopahkl;fjh#dsjfklpafj
';
my $count = $str =~ tr/#/#/;
使用转换运算tr 简单,迅速 可以参考大骆驼书模式匹配一章.
遍历统计好了
#!/usr/bin/perl -w
use strict;
my $str = "abcsfsaf#sdagasdga#sdgaghoiiopjh#dsfjkopa hkl;fjh#dsjfklpafj";
my $count = 0;
while( $str =~ /#/g ) {
$count++;
}
print "num of # is: $count\n";
要统计其他字符,把pattern替换即可了
perl -e '$a="abcsfsaf#sdagasdga#sdgaghoiiopjh#dsfjkopa hkl;fjh#dsjfklpafj"; print $a=~s/#/$&/g;'
结果是4
三个方法如下:
#!/bin/perl
-w
use
strict;
my
$str
=
"abcsfsaf#sdagasdga#sdgaghoiiopjh#dsfjkopa
hkl;fjh#dsjfklpafj";
###########
方法一
my
$pos
=
-1;
my
$num
=
0;
while
(($pos
=
index($str,
"#",
$pos))
>
-1)
{
print
"Found
at
$pos\n";
$pos++;
$num
++;
}
print
"找到$num个!\n";
###############################################################
#
方法二
my
$count
=
0;
while(
$str
=~
/#/g
)
{
$count
++;
}
print
$count,"\n";
##########################################
#
方法3
my
$cc
=
0;
my
$tmp
=
0;
if(
$tmp
=
()
=
($str
=~
/#/g
)
)
{
$cc
+=
$tmp;
}
print
"$cc\n";