On 5/2/06, Charles K. Clarkson <[EMAIL PROTECTED]> wrote:
Anthony Ettinger wrote:

: #!/usr/bin/perl -w
:
: use vars qw($foo); #globals;
: use strict;
:
: sub foo {
:         $foo = 'foo';
:         my $baz = 'baz';
: }
:
: my $baz = 'pre-baz';
: foo();
:
: print $foo, "\n";
: print $baz, "\n";

    I think the problem we are having is why use a solution
which resorts to global variables when lexical variables get
the job done fine?

use strict;
use warnings;

my $baz = 'pre-baz';
my $foo = foo();

print $foo, "\n";
print $baz, "\n";


sub foo {
    my $foo = 'foo';
    my $baz = 'baz';
    return $foo;
}

__END__


Correct, I should've provider a better example of what I'm trying to do.

I need to require("logger.pl"); at the top of a bunch of scripts (ie -
"tool.pl"), and I want to log start/end times without touching
"tool.pl". So I accomplish this with BEGIN/END blocks from within
logger.pl, which set the start time when the tool.pl is executed, and
then calls log_time(); from the END block when the tool.pl is
finished.

The tools are such that there is no "use strict; or -w" in use (and
I'd rather avoid touching these beasts if I can help it at all).

Here's a clearer example of "logger.pl" that I will be including in my tools:

----
#!/usr/bin/perl -w

use vars qw($start_time $end_time);
use strict;

BEGIN {
       $start_time = time();
}

sub log_time {
       my $exit_code = shift;
       my $elapsed_time = $end_time - $start_time;

       print $elapsed_time, "\n";
}

END {
       $end_time = time();
       &log_time($?);
}

__END__

I had originally posed the question using "our" inside log_time(); to
import the globals defined in BEGIN/END blocks (which works by the
way); however I have since discovered that one of my systems is using
a version of Perl < 5.6, inwhich "our" is not supported, so the above
method, although deprecated, works across the board for my
environment. (I'm not the admin, and getting Perl upgraded is not a
viable option at this time).

The only change I have to make to each tool-N.pl is:
require("logger.pl"); at the top.

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


Reply via email to