In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Beau E. Cox) writes: >On Thursday 06 May 2004 02:45 am, you wrote: >> Beau, >> This is coz you have defined $arg1 and $arg2 to be local, hence when u >> defined a new subroutine, a new sope is defined, and is beyond the scope of >> $arg1 and $arg2. Hence the error. >> >> srikanth > >But wait, I thought 'my' variables were 'local to the enclosing >block'. If you look at the enclosing block in my sample, it >DOES include the nested subroutine. > >I guess I still don't understand.
That's because the explanation was incorrect. Subroutines can reference lexical variables declared outside them if they are still in scope. We refer to these subroutines as being closures for those variables. More comments below. >> > sub _main >> > { >> > my $arg1 = shift @ARGV; >> > my $arg2 = shift @ARGV; >> > >> > show_results(); >> > >> > sub show_results >> > { >> > print "$arg1 and $arg2\n"; # <- line 17 >> > } >> > } >> > >> > gives the following warnings: >> > >> > [EMAIL PROTECTED]:~/src/bempl/junk$ perl ev2.pl mary jane >> > Variable "$arg1" will not stay shared at ev2.pl line 17. perldoc perldiag is your friend. Or put 'use diagnostics' in your program. You'd see: Variable "%s" will not stay shared (W closure) An inner (nested) named subroutine is referencing a lexical variable defined in an outer subroutine. When the inner subroutine is called, it will probably see the value of the outer subroutine's variable as it was before and during the *first* call to the outer subroutine; in this case, after the first call to the outer subroutine is complete, the inner and outer sub- routines will no longer share a common value for the variable. In other words, the variable will no longer be shared. Furthermore, if the outer subroutine is anonymous and references a lexical variable outside itself, then the outer and inner subrou- tines will never share the given variable. This problem can usually be solved by making the inner subroutine anonymous, using the "sub {}" syntax. When inner anonymous subs that reference variables in outer subroutines are called or refer- enced, they are automatically rebound to the current values of such variables. -- Peter Scott http://www.perldebugged.com/ *** NEW *** http://www.perlmedic.com/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>