On 08/30/2007 04:32 AM, Beginner wrote:
Hi,

I want all the output plus any error messages to got to a log file. I used the BEGIN block to direct STDERR into the file:

BEGIN { open(STDERR, ">>/usr/local/myreports/report.log") || die "Can't write to file: $!\n";
}

use strict; use warnings;
...
### Start some logging ###
my $log;
my $logfile = "$dist_dir/report.log";
open($log,">>$logfile") || die "Can't write to $logfile: $!\n";
print $log "$0 called at ", &tm," with pid $$\n";


I am not massively happy with this method. I can't seem to use a scalar that I can share with the rest of the script for the log file and if I do a perl -c myscript.pl, all the messages go to the log file.

Q1) Can I use a scalar instead of having to give the full file path in the BEGIN block?

Yes,

our $logfile;
INIT {
    $logfile = '/usr/local/myreports/report.log';
    open (STDERR, '>>', $logfile) || die "Can't write to file: $!\n";
}

I think that code should also allow "perl -c myscript.pl" to send output to the console.

I haven't tried it but I suspect is would be fall within the scope of the BEGIN block and as far as I know, you cannot declare anything before a BEGIN block. Failing that, can anyone suggest a different way of doing this.

Q2) You sometimes see scripts accept the verbose/debug command line argument. How can you implement a system so that you can ask for more messages? Once you've set $debug = 1; do you have to pepper your script with
print $log "some message\n" if $debug == 1;

TIA,
Dp.


I've seen it done that way before.




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to