James Kipp wrote:
> BEGIN blocks are interpreted a the first phase of compilation. eval blocks
> and constants are also evaluated at this stage. so the code in the begin
> block is run before compiling the rest of the file.
> this insures the these variables are initialized before your sub is called
>
> > -----Original Message-----
> > From: Troy May [mailto:[EMAIL PROTECTED]]
> > Sent: Thursday, August 15, 2002 10:56 PM
> > To: Perl Beginners
> > Subject: BEGIN statement in Perl?
> >
> >
> > Hello,
> >
> > I just read this in a forum and I have never heard of this
> > before. He was
> > having problems with a variable not holding it's value when
> > calling it from
> > a sub. He wrote back and said that this is what fixed it.
> > Can anybody
> > explain this to me? Here's part of his post:
> >
> > -------------
> > What I've found is that in order to initialise my static
> > variable I need to
> > have a BEGIN statement around it:
> >
> > BEGIN {
> >
> > my $static = "abc";
> >
> > sub doit() {
> > $static = $static x 2;
> > print( "$static \n" );
> > }
> >
> > } # end of BEGIN statement
> >
> > I hadn't realised that the BEGIN was required and while
> > testing this found
> > that $static was not being explicitly initalised prior to its
> > first use.
> > ---------------
> >
> >
> >
> > --
> > To unsubscribe, e-mail: [EMAIL PROTECTED]
> > For additional commands, e-mail: [EMAIL PROTECTED]
> >
> >
an example will help you see what's going on with BEGIN:
#!/usr/bin/perl
$a = "a";
BEGIN{
$a = "b";
print "$a\n"; #-- prints b
}
print "$a\n"; #-- prints a
what happen is that the BEGIN block is executed during compile time. that's
why it prints a "b" inside
the BEGIN block. now when the BEGIN block finish, Perl continue to compile
the rest of the code,
this means, the statement $a = "a" is compile and executed after the
BEGIN block. when Perl
compile and execute the $a = "a" statement, it overrides the $a = "b"
statement which is done a long
time ago during compile time. that's why "a" is printed at the second print
statement.
if you change:
BEGIN{
$a = "b";
print "$a\n";
}
to a simple block like:
{
$a = "b";
print "$a\n";
}
then both print statement will print "b" because everything is happened at
run time
david
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]