in reply to Perl scoping not logical...?
I'm afraid my post will be full of don'ts.
First, don't use subroutine prototypes! They are NOT what you seem to think they are. Prototypes are NOT designed to let you specify and test the number of parameters passed to a subroutine, they are designed to let you instruct the parser to parse the code in a different way, to emulate the behaviour of some builtins or add something that looks like statements instead of normal functions. Drop them! And especialy do drop them when declaring unamed subroutines, they can't ever mean anything there.
Second, don't put one named subroutine inside another! If you need two subroutines to share a variable, you should do it like this:
In this case keep in mind that all, even recursive invocations of the subroutines share the same variable(s)!{ my $shared; sub foo { ... $shared++; .. } sub bar { ... print "Foo called $shared times.\n"; } }
If you do want a subroutine that has access to the current invocation's lexical variables, you have to use an unnamed subroutine.
Imagine this:
Now, which $i should the printFoo access? Keep in mind that if you call foo(4), then the first $i gets set to 4, the foo(3) gets called, another $i is set to 3, foo(2) is called ... so at some point you have 5 different $i variables! Also, the named procedure, even though it was written inside the curlies of another subroutine is NOT local to that subroutine! So what $i do you want to use when I call printFoo() directly?sub foo { my $i = shift; return if $i <= 0; sub printFoo { print "The \$i=$i\n"; } printFoo(); foo($i-1); }
BTW, why do you even bother declaring the do_pkg_need_from_Dist() subroutine if you call it just once? If you did declare it outside the process_need_from_Dist() I could understand that you want to simplify the code by extracting and naming one part of it, but since the body of the do_pkg_need_from_Dist() is inside the process_need_from_Dist(), this can't be the reason.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl scoping not logical...?
by perl-diddler (Chaplain) on Apr 28, 2008 at 00:08 UTC | |
by chromatic (Archbishop) on Apr 28, 2008 at 00:16 UTC | |
by Jenda (Abbot) on Apr 28, 2008 at 10:10 UTC |