On Nov 19, Dr. Poo said:
>I'm trying to declare a variable $log that is a reference to an array that
>will contain the small amounts of data that need to be logged throughout a
>backup script i'm working on. I'd like to declare this scalar reference in
>the BEGIN function, but i can't use it outside of the BEGIN function if i
>declare 'my $log' in BEGIN.
A my() declaration happens at compile-time. The assignment to the
variable happens at run-time. That means when you write
my $x = foo();
Perl is really doing
my $x;
at compile-time, and
$x = foo();
at run-time. So your code would be somthing like:
my $log;
BEGIN { $log = ... }
The other problem is calling a function. You can't call a function in a
BEGIN block unless it has already been defined. This is because stuff in
a BEGIN block is executed at compile-time, as SOON as it is reached. That
means that code like:
BEGIN { foo() }
sub foo { ... }
fails because when you try calling foo() at compile-time, Perl hasn't seen
the definition of the function yet. Thus, you must do the BEGIN block
after the definition of the function.
my $log;
sub set_log { ... }
BEGIN { $log = set_log() }
But that can look ugly if set_log() is big. You might be tempted to put
the function definition and BEGIN block at the END of your code:
my $log;
...
...
sub set_log { ... }
BEGIN { $log = set_log() }
but then you have code at the BOTTOM of your program that happens "first".
If you're using Perl 5.6, I have the solution for you. You can use the
INIT block. It is executed immediately after compile-time.
my $log;
INIT { $log = set_log() }
...
sub set_log { ... }
Try it out.
--
Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/
RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
<stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
[ I'm looking for programming work. If you like my work, let me know. ]
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]