greymoose has asked for the wisdom of the Perl Monks concerning the following question:

I have a small script that keeps track of how many people visit a page each day. I am sure the data is being collected correctly and the file path and permissions are ok because it is overwriting previous data whenever the test page is visited.
My sub to open and append to the file goes like this:
#write data to file $logfile = $path.$pg; open (LOG1, ">>, $logfile") or die "Can't open logfile: $!"; print LOG1 "$when\n"; close (LOG1) or die "Can't close logfile: $!";
After a bit of searching in the Monastery I tried a few variations, namely:
open (LOG1, ">>", $logfile) or die "Can't open logfile: $!"; open (LOG1, ">> $logfile") or die "Can't open logfile: $!"; open (LOG1, ">>$logfile") or die "Can't open logfile: $!";
without success.
I've carefully read and re-read the docs to see what I'm doing wrong but I guess I haven't been careful enough. Does anyone have any idea where I've gone astray?

Thanks in advance.

Replies are listed 'Best First'.
Re: Append to text file not working
by tilly (Archbishop) on Feb 21, 2008 at 23:05 UTC
    The version open (LOG1, ">>", $logfile) or die "Can't open logfile: $!"; should be correct. If it dies, then the error message is likely to give you useful information. If it doesn't die, then you may want to print to STDERR what $logfile is, because it may be logging to a file you aren't expecting. If that doesn't help, then double-check what directory you are in. If that doesn't work, then triple-check whether something is deleting the file.

    At a guess, your problem is that the data is written to a different file or directory than the one you're looking at.

Re: Append to text file not working
by ikegami (Patriarch) on Feb 21, 2008 at 22:59 UTC

    The problem is elsewhere. The three variations you found on PM work.

    >type foo.pl my $logfile = 'foo.log'; open(my $log_fh, ">>", $logfile) or die "Can't open logfile: $!\n"; print $log_fh scalar(localtime), "\n"; >type foo.log The system cannot find the file specified. >perl foo.pl >type foo.log Thu Feb 21 17:59:01 2008 >perl foo.pl >type foo.log Thu Feb 21 17:59:01 2008 Thu Feb 21 17:59:05 2008

    Note: I used a lexical ($log_fh), but using a package variable (LOG1) works too.

      I meant to mention locking. If you have multiple users (i.e. threads, processes, pieces of code) adding to the file simultaneously, you'll need to control access to the file. See flock.
        As long as your writes are below one page of data (2k is safe), then with most filesystems your writes are atomic and no locking synchronization is needed. That looks like it is true in this case.

        If locking synchronization is needed, then flock is not necessarily the right place to start looking because (depending on the filesystem) it can be highly unreliable.