脚本未运行或显示错误

时间:2013-02-13 17:31:36

标签: perl terminal

我正在编写一个脚本,该脚本查看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 个答案:

答案 0 :(得分:3)

脚本正在尝试从STDIN读取,但您提供的文件名是作为参数读取的。

“没有任何反应”因为脚本正在等待输入(因为您没有将任何内容重定向到标准输入,所以它希望您输入)。

<STDIN>更改为<>或将命令更改为perl -w access_scan.pl < access_log.1

答案 1 :(得分:3)

除了您的脚本没有按预期工作之外,您的脚本还有一些问题:

在正则表达式中,点.匹配任何非换行符。这包括字面时期,但不限于此。可以使用/google\.com/ \Q...\E转义它(/\Qgoogle.com\E/)或保护特殊字符。

有一个编程谚语“三个或更多,使用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大写下一个字符,这是产生相同输出所必需的 sayprint完全相同,但附加换行符。它在perl5 v10或更高版本中可用。

答案 2 :(得分:0)

您的脚本正在从标准输入读取,但您将输入作为文件提供。你需要redirect

perl -w access_scan.pl < access_log.1

< file构造提供文件内容作为脚本的标准输入。

答案 3 :(得分:0)

脚本运行正常(我测试过),但你需要用STDIN中的日志提供它:

cat access_log.1 | perl -w access_scan.pl
相关问题