简体   繁体   中英

PERL CGI program

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?

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; and use warnings; (and correct code based on their complaints)
  • Use the three argument call to open as per the first example in the documentation
  • When you open a file always || handle_the_error_in($!); || handle_the_error_in($!);
  • Don't use a file to store data like this, you have potential race conditions.
  • Get the name of the language correct

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.

#!/usr/bin/env perl
use strict;
use warnings;
use Fcntl qw(:DEFAULT :flock);
my $file = 'mycount';
sysopen(my $fh, $file, O_RDWR|O_CREAT) or die "Can't open '$file' $!\n";
flock($fh, LOCK_EX) or die "Can't lock $file: $!\n";
my $cnt = <$fh>;
$cnt=0 unless $cnt;
$cnt++;
seek $fh, 0, 0;
print ${fh} $cnt;
close $fh or die "Can't close $file: $\n";
print "Visitor count: $cnt\n";

The most obvious thing that you would have forgotten is to change permissions of the file count.dat Do this :

sudo chmod 777 count.dat

That should do the trick

A few potential reasons:

  • 'count.dat' is not being open ed for reading. Always test with or die $!; at minimum to check if the file opened or not

  • The code is not being executed and you think it is

You will need to close the webpage and reopen it again. Just refreshing the page won't increment the count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM