Rodney Wise wrote:

> I was under the impression that "subroutines" are only executed IF they're
> called.  But, it looks like subroutines will execute on there own if they
> are written in the beginning part of the PERL code and before other code
> takes over the codes sequence of events.   In other words,  if there is a
> subroutine in the beginning of your code, it will execute without being
> called.
>
> Is this true?

No.  You are probably mistaking anonymous blocks for subroutines.  The
phenomenon applies anywhere, mot just aqt the start of a script.  Good design
will generally keep global code and definitions near the top of the script,
though.  A subroutine, to be a sub, must be declared with the sub statement:

sub my_function {
}

and the code inside is run only when explicitly called by name.

An anonymous block will be run in direct sequence with the surrounding code.
Like a sub definition, it is surrounded by braces [aka curly brackets].  The
braces do not effect when the code is executed, but limit the scope of any
declarations within.

my $mood = 'joyous';
print "I am in a $mood mood\n";

# The block of the dark clouds
{
   my $mood = 'miserable';
   print "I am in a $mood mood\n";
}

# Passed through the block.  Now how're we feeling?
print "I am in a $mood mood\n";

As you can see, the $mood declared within the block exists only for the lifetime
of the block.  All lexical variable identifiers within a block dies when it
completes, BUT not necessarily the information or information structures they
refer to.

my $mood = 'joyous';
print "I am in a $mood mood\n";
my $mood_ref;

# The block of the darik clouds
{
   my $mood = 'miserable';
   $mood_ref = \$mood;
   print "I am in a $mood mood\n";
}

# Passed through the block.  Now how're we feeling?
$mood = $$mood_ref;
print "I am in a $mood mood\n";

The block above is called a closure.
perldoc -q closure
It is used to generate structures which will thereafter be accessed through
references.
perldoc perlref
perldoc perlreftut

Variables lexically scoped within subroutines can likewise be kept alive by
passing out references to them.  Generally, such functions will return a
reference to such an internal data structure.  The difference again is that a
function or sub runs only when called.

Joseph


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to