Perl CGI 页面访问计数器不增加
我正在尝试一个基本的 Perl/CGI 脚本来跟踪访问网页的访问者。 Perl 代码如下所示:
#!/usr/bin/perl
#KEEPING COUNT OF VISITORS IN A FILE
use CGI':standard';
print "content-type:text/html\n\n";
#opening file in read mode
open (FILE,"<count.dat");
$cnt= <FILE>;
close(FILE);
$cnt=$cnt+1;
#opening file to write
open(FILE,">count.dat");
print FILE $cnt;
close(FILE);
print "Visitor count: $cnt";
问题是网页不会在每次刷新时增加访问者计数。计数保持在 $cnt
的初始值,即“1”。有什么想法问题出在哪里吗?
I was trying out an elementary Perl/CGI script to keep track of visitors coming to a web page. The Perl code looks like this:
#!/usr/bin/perl
#KEEPING COUNT OF VISITORS IN A FILE
use CGI':standard';
print "content-type:text/html\n\n";
#opening file in read mode
open (FILE,"<count.dat");
$cnt= <FILE>;
close(FILE);
$cnt=$cnt+1;
#opening file to write
open(FILE,">count.dat");
print FILE $cnt;
close(FILE);
print "Visitor count: $cnt";
The problem is that the web page does not increment the count of visitors on each refresh. The count remains at the initital value of $cnt
, ie `1``. Any ideas where the problem lies?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您永远不会测试打开文件句柄的尝试是否有效。给定一个我有权读取和写入的文件,其中包含一个数字而没有其他内容,代码的行为符合预期。如果该文件不存在,则计数将始终为
1
,如果它是只读的,则它将保留在文件开始的位置。更一般的建议:
use strict;
和use warnings;
(并根据他们的抱怨纠正代码)open
文档中的第一个示例打开
文件时,始终|| handle_the_error_in($!);
You never test if the attempt to open the file handle works. Given a file which I had permission to read from and write to that contained a single number and nothing else, the code behaved as intended. If the file did not exist then the count would always be
1
, if it was read-only then it would remain at whatever the file started at.More general advice:
use strict;
anduse warnings;
(and correct code based on their complaints)open
as per the first example in the documentationopen
a file always|| handle_the_error_in($!);
这是另一种解决方案,它仅使用一个 open() 并创建该文件(如果该文件尚不存在)。锁定消除了多个更新者之间潜在的竞争状况。
Here's an alternate solution that uses only one open() and creates the file if it doesn't already exist. Locking eliminates a potential race condition among multiple up-daters.
一些潜在的原因:
“count.dat”未
打开
进行读取。至少始终使用or die $!;
进行测试,以检查文件是否已打开代码没有被执行,而您认为它是
A few potential reasons:
'count.dat' is not being
open
ed for reading. Always test withor die $!;
at minimum to check if the file opened or notThe code is not being executed and you think it is
您可能会忘记的最明显的事情是更改文件
count.dat
的权限这样做:
应该可以解决问题
The most obvious thing that you would have forgotten is to change permissions of the file
count.dat
Do this :
That should do the trick
您需要关闭该网页并再次重新打开。仅刷新页面不会增加计数。
You will need to close the webpage and reopen it again. Just refreshing the page won't increment the count.