2015-12-23 120 views
5

我覺得必須有一種更好的方法來統計出現的情況,而不是在Linux中的perl,shell中編寫子文件。有沒有更好的方法來計算字符串中char的出現?

#/usr/bin/perl -w 
use strict; 
return 1 unless $0 eq __FILE__; 
main() if $0 eq __FILE__; 
sub main{ 
    my $str = "ru8xysyyyyyyysss6s5s"; 
    my $char = "y"; 
    my $count = count_occurrence($str, $char); 
    print "count<$count> of <$char> in <$str>\n"; 
} 
sub count_occurrence{ 
    my ($str, $char) = @_; 
    my $len = length($str); 
    $str =~ s/$char//g; 
    my $len_new = length($str); 
    my $count = $len - $len_new; 
    return $count; 
} 
+1

羅伯特,謝謝你,我會補充語法檢查向前發展。 – Gang

回答

2

美麗 *擊/ Coreutils的/ grep的一行代碼:

$ str=ru8xysyyyyyyysss6s5s 
$ char=y 
$ fold -w 1 <<< "$str" | grep -c "$char" 
8 

或許

$ grep -o "$char" <<< "$str" | wc -l 
8 

的第一個作品只有當子只是一個字符長;第二個僅在子串不重疊時才起作用。

*不是。

+0

兩者都很好,我把它們加到了我的工具箱中,第一次聽到了cmd fold,很感謝! – Gang

+1

@gliang:這有點像Bash的split split,我最近才發現它。很高興你發現它們很有用! –

2

toolic已經給出了正確的答案,但您可能會考慮不硬編碼您的值以使程序可重用。

use strict; 
use warnings; 

die "Usage: $0 <text> <characters>" if @ARGV < 1; 
my $search = shift;     # the string you are looking for 
my $str;        # the input string 
if (@ARGV && -e $ARGV[0] || [email protected]) { # if str is file, or there is no str 
    local $/;       # slurp input 
    $str = <>;       # use diamond operator 
} else {        # else just use the string 
    $str = shift; 
} 
my $count =() = $str =~ /\Q$search\E/gms; 
print "Found $count of '$search' in '$str'\n"; 

這將允許您使用該程序計算字符串,文件或標準輸入內字符或字符串的出現次數。例如:

count.pl needles haystack.txt 
some_process | count.pl foo 
count.pl x xyzzy 
+0

gms是什麼? g - 對於所有發生,m爲匹配,s爲? – Gang

+1

@gliang:「將字符串視爲單行」,即'.'匹配換行符,通常不會,請參閱http://perldoc.perl.org/perlre.html#Modifiers –

+0

本傑明,謝謝,它是不是我認爲的那樣。我會再次閱讀文檔。 – Gang

4

如果字符是恆定的,下面是最好的:

my $count = $str =~ tr/y//; 

如果字符是可變的,我會用以下內容:

my $count = length($str =~ s/[^\Q$char\E]//rg); 

我如果我想與5.14以前版本的Perl兼容(因爲它比較慢並且使用更多內存),所以只使用以下內容:

my $count =() = $str =~ /\Q$char/g; 

下不使用的內存,但可能會有點慢:

my $count = 0; 
++$count while $str =~ /\Q$char/g; 
+0

你們很棒,perl總是給我驚喜!謝謝。 – Gang

相關問題