
japhy
Enthusiast
Jan 18, 2000, 6:44 PM
Post #2 of 6
(519 views)
|
|
Re: Creating a log file clearing sub routine?
[In reply to]
|
Can't Post
|
|
Here's my approach to a backup-generating function. You can send it filenames, or properly formatted filehandles: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> use Carp; # for proper error messages use Fcntl qw( :flock ); # for file locking # backup($file1,$file2) # backup(*FH,$file2) # backup(\*FH,$file2) # or any combo of $filename, *FH, and \*FH sub backup { # ensure correct number of arguments croak "not enough arguments to backup()" if @_ < 2; croak "too many arguments to backup()" if @_ > 2; # assign values to variables my ($in,$out) = @_; # in case we need these filehandles # they'll be closed when the subroutine ends local (*IN,*OUT); if (not ref $in and ref \$in eq "SCALAR") { # got a filename, not a filehandle open IN, "+<$in" or croak "cannot open $in for reading and writing: $!"; $in = *IN; } flock $in, LOCK_EX; if (not ref $out and ref \$out eq "SCALAR") { # got a filename (again) open OUT, ">>$out" or croak "cannot open $out for appending: $!"; $out = *OUT; } flock $out, LOCK_EX; # now we're ready { # print ALL the contents as ONE string # quickly, and efficiently local $/; print $out <$in>; } # clear $in seek $in, 0, 0; truncate $in, 0; } </pre><HR></BLOCKQUOTE> To print any debugging messages, you could use the carp() function (instead of warn(), or instead of print()ing to STDOUT). Historically, error messages, warnings, and debugging statements go to STDERR, rather than STDOUT. Your code is ok, but for security, you may want to lock the filehandles so that their data is not corrupted mid-stream. Also, you needn't say "$in", when a simple $in will do -- this is called stringification, and can get you in trouble if you work with references. As for user agent programming, have you looked the libwww-perl (LWP) bundle? It allows for simple creation and use of user agents, and easy access to files on the internet. That's all for now.
|