
dsb
stranger
Apr 20, 2002, 6:15 PM
Post #6 of 10
(1191 views)
|
|
Re: [uri] A subroutine inside another subroutine (HUGE PROBLEM)
[In reply to]
|
Can't Post
|
|
1. Perl does support nested sub routines. They help provide encapsulation to scoped variables. In other words, a variable declared with my will only be accessible through the sub routine nested in the same block, whereas the sub-routines can be called(and declared) from anywhere:
{ my $x = 0; sub test2 { for (1..5) { print ++$x; } print "\n"; } } test2(); # print '12345' print $x, "\n"; # prints nothing, throws an error when using 'strict' 2. If you look closely at the output of the code you give, you will see that the second call to test1 IS working, but the output is '678910'. That is because test2 is accessing a private copy of $x which otherwise goes out of scope after the first call to 'test2'(via 'test1'). Initialize $x to '0' in the 'test2' sub and you will get the results you seem to want. 3. Try calling 'test2' with arguments(add the appropriate code to 'test2') and you will also get the results you seem to want. Doing this, 'test2' will be using the same private copy of $x that 'test1' is using, so when $x initializes $x to '0', 'test2' sees the re-initialization:
sub test1 { my $x = 0; sub test2 { my $x = shift; for (1..5) { $x++; print $x; } print "\n"; } test2($x); } test1(); test1(); Hope that helps. _______________________ dsb PerlGuy
|