0

我明天要考试,我被实验室实验的这一部分困住了。

实验:编写一个 Perl 程序来跟踪访问该网页的访问者数量,并以正确的标题显示访问者的数量。

#!/usr/bin/perl
use CGI':standard';
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
print "Content-type: text/html","\n\n";
open(FILE,'<count.txt');
$count=<FILE>+1;
close(FILE);
open(FILE,'>count.txt');
print FILE "$count";
print "This page has been viewed $count times";
close(FILE);
#print $count;

我已count.txt在 Fedora 中将 ' 的权限更改为 755。

在每个页面加载时,在 Windows XP 中的 XAMPP 上执行时计数成功增加(使用适当的 shebang 行)。但我无法在 Fedora 上执行它。不幸的是,在我的考试中,我必须在 Fedora 上执行。

4

2 回答 2

3

一直用use strict; use warnings;!如果您这样做,您将在错误日志中收到以下错误:

Global symbol "$count" requires explicit package name

修复缺失的my后,您将在错误日志中收到以下错误:

readline() on unopened filehandle FILE
print() on unopened filehandle FILE

您可以通过检查返回的错误来检查您的句柄未打开的原因open

open(FILE,'<count.txt') or die "Can't open count.txt: $!\n";
open(FILE,'>count.txt') or die "Can't create count.txt: $!\n";

第一个说文件不存在。如果程序走得那么远,第二个会给你一个权限错误。那是因为您正试图访问count.txt在根目录 ( /) 中命名的文件。更改 cwd 或使用绝对路径。


顺便说一句,你有一个竞争条件。如果两个请求同时进入,您最终只会计算其中一个。

 |   process 1                      process 2
 |   ----------------------------   ----------------------------
 T   Read count from the file (4)
 i   Add 1 to count (5)
 m                                  Read count from the file (4)
 e                                  Add 1 to count (5)
 |                                  Save new count to file (5)
 v   Save new count to file (5)

您需要使用锁定机制。

于 2012-12-05T17:50:02.150 回答
2

shebang ( #!) 必须是文件的第一个字符。

于 2012-12-05T17:23:57.680 回答