> -----Original Message-----
> From: Johnson, Shaunn [mailto:[EMAIL PROTECTED]]
> Sent: Thursday, May 02, 2002 10:37 AM
> To: '[EMAIL PROTECTED]'
> Subject: passing local value between sub functions
> 
> 
> Howdy:
> 
> Have a question about trying to pass the result
> of a sub function to another sub function.
> 
> Let's say I have some code like this:
> 
> [snip]
> 
> sub firstPart {
>       while (<>) {
>       print "Stuff here is: $_\n";
>       }
> 
> [/snip]
> 
> I'd like to know how can I make $_ available
> for OTHER sub functions if not the entire program.
> I'm trying to get snips of code so I can show 
> you what I'm working with (apologies since it
> isn't my code); I was under the impression that
> I could use my() and pass that info OUTSIDE
> the sub function.

$_ is one of Perl's "special" variables and is always global.

So, if you have:

sub foo
{
   $_ = "Hello, world\n";
   bar();
}

sub bar
{
   print $_;
}

foo();          # call sub foo

Then when foo() is called, sub bar will print "Hello, world\n",
since $_ is a global variable.

Consider this:

sub foo
{
   $hello = "Hello, world\n";
   bar();
}

sub bar
{
   print $hello;
}

foo();          # call sub foo

The same situation holds. $hello is a global variable, because by
default, all variables in Perl are global. Using "my" makes a
local (lexical) variable:

sub foo
{
   my $hello = "Hello, world\n";        # $hello now lexical var
   bar();
}

sub bar
{
   print $hello;                        # prints nothing, why?
}

foo();          # call sub foo

The addition of "my" turns $hello into a "private" or lexcial
variable. It now is limited to a "scope" consisting of the point
at which it is defined until the end of the innermost enclosing
block { } or file. In this case, $hello can only be accessed by
lines of code that lie between the "my" line and the closing brace
(}) two lines later. When we try to print $hello in sub bar,
nothing prints, because we are actually using the "global" $hello.
When we are outside of the scope of the "private" $hello, we
default to using the global $hello.

This is usually a problem that should be brought to our attention,
so perl has a "use strict" pragma that will raise an error if we
try to access a global variable (such as $hello inside sub bar)
without previously delaring our intention to do so. ($_ and the
other "special" globals are exempted from this, however.)

There's *lots* more to be said about this in:

   perldoc perlsub
   perldoc perlvar  (about the "special" variables)
   perldoc strict



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


Reply via email to