2013-02-13 78 views
0

我正在編寫一個腳本,查看access_log文件以查看每個搜索引擎的訪問次數並查看哪個訪問最多。我確信我的一些語法存在問題,但我甚至無法分辨,因爲我在運行時沒有收到任何信息。任何幫助,將不勝感激!腳本未運行或顯示錯誤

代碼:

#!/usr/bin/perl 

use 5.010; 

$googleCount = 0; 
$msnCount = 0; 
$yahooCount = 0; 
$askCount = 0; 
$bingCount = 0; 


while (<STDIN>) 
{ 
    if (/(google.com)/) 
    { 
     $googleCount++; 
    } 

    if (/(msn.com)/) 
    { 
     $msnCount++; 
    } 

    if (/yahoo.com/) 
    { 
     $yahooCount++; 
    } 

    if (/ask.com/) 
    { 
     $askCount++; 
    } 

    if (/bing.com/) 
    { 
     $bingCount++; 
    } 
} 



print "Google.com was accessed $googleCount times in this log.\n"; 
print "MSN.com was accessed $msnCount times in this log.\n"; 
print "Yahoo.com was accessed $yahooCount times in this log.\n"; 
print "Ask.com was accessed $askCount times in this log.\n"; 
print "Bing.com was accessed $bingCount times in this log.\n"; 

我運行MacOS的。在我輸入的終端中:

perl -w access_scan.pl access_log.1 

當我按回車時,什麼也沒有發生。

+4

不要編寫Perl 4風格的代碼。 '使用v5.10;嚴格使用;使用警告;'。 – Quentin 2013-02-13 17:35:09

回答

3

旁事實上,你的腳本沒有按照你的預期工作,你的腳本有幾個錯誤:

在正則表達式中,點.匹配任何非換行符。這包括一個文字時期,但不限於此。或者通過\Q...\E/\Qgoogle.com\E/逃脫它(/google\.com/)或保護特殊字符。

有一個編程諺語「三個或更多,使用for」。你的循環內的所有條件都是,除了正則表達式。你計數實際上是一個變量。最後的報告多次是同一行。

您可以使用哈希來緩解疼痛:

#!/usr/bin/perl 
use strict; use warnings; use feature 'say'; 

my %count; # a hash is a mapping of strings to scalars (e.g. numbers) 
my @sites = qw/google.com msn.com yahoo.com ask.com bing.com/; 

# initialize the counts we are interested in: 
$count{$_} = 0 foreach @sites; 

while (<>) { # accept input from files specified as command line options or STDIN 
    foreach my $site (@sites) { 
    $count{$site}++ if /\Q$site\E/i; # /i for case insensitive matching 
    } 
} 

foreach my $site (@sites) { 
    say "\u$site was accessed $count{$site} times in this log"; 
} 

\u將轉換爲大寫下一個字符,這需要產生相同的輸出。
say完全像print,但附加換行符。它在perl5 v10或更高版本中可用。

0

您的腳本正在從標準輸入讀取,但您將輸入作爲文件提供。您需要redirect這樣的:

perl -w access_scan.pl < access_log.1 

< file構造提供的文件的內容爲你的腳本標準輸入。

3

腳本試圖從STDIN中讀取,但是您提供的文件名作爲參數讀取。

「沒有任何反應」,因爲腳本正在等待輸入(這是因爲您沒有將任何內容重定向到標準輸入,所以您希望輸入)。

變化<STDIN><>或更改命令以perl -w access_scan.pl < access_log.1

+0

完美工作,我甚至沒有語法錯誤!當這只是一個愚蠢的錯誤,這樣的解脫哈哈。感謝您的幫助:) – JLott 2013-02-13 17:42:15

+0

@jlot:讓您可以選擇現有答案之一。 – smartmeta 2013-02-13 18:20:59

+0

+1爲鑽石操作員! – Axeman 2013-02-13 23:43:54

0

該腳本工作正常(我測試了),但你需要在日誌中STDIN餵它:

cat access_log.1 | perl -w access_scan.pl 
+0

這是對'cat'的無用使用,詳情請參閱[術語文件](http://catb.org/jargon/html/U/UUOC.html)。 – amon 2013-02-13 19:33:25