grinder wrote: Odd. If I take out the main:: prefix, and the package declaration I receive no error. In fact, I've never seen a package declaration within a subroutine. It seems strange, to say the least, and I wonder if it does what you think it does. What do you think it does?
The scope of a package declaration is from the declaration itself to the end of the enclosing block (ref: package). So, declaring the package after the opening brace of the subroutine allows me to define variables (with our) that don't pollute the main namespace, but still maintain their value outside of the scope of the current instance of the subroutine.
By prefixing the name of the subroutine with main::, I'm saying that I want to call the print_r() subroutine which is defined in the main namespace rather than the current namespace, which is print_r when it's called from the subroutine. I didn't even have this in there until the error message told me that it was necessary.
Are you sure you used the same code as me? This doesn't seem like the kind of error that would be different between different versions of Perl.
I could declare the package before the subroutine definition and remove main:: from the lines where the function calls itself, but then I would have to add print_r:: to the function call in the main body of the code. This would make it a little more annoying to use. Also, this would force the subroutine definition to appear at the end of the script because the package declaration would apply to everything after it.
I suppose that I could fix this with Exporter if I wrote a proper module, but this isn't meant to be a module, just a snippet.
If I take out the package entirely and use regular variables which are defined in the main namespace anyway, then this problem goes away, but then I have a couple of variables ($level and @level_index) which have to be defined by the user in addition to just pasting the code at the end of an existing program and calling print_r(). Another potential problem is that the user needs to know about the two variables and make sure he doesn't use them in the main namespace.
The way I wrote it, the user needs only to paste the subroutine into their own code and call print_r(), passing a variable reference as the argument.
grinder wrote: Looking more closely at the code, I suspect you want my variables and not our.
I need to use our because I need the variables to maintain their value between calls to the subroutine. If I used my it would be a new and undefined variable each time the subroutine was called and this would break the recursion. To be specific, the $level would be 0 on each recursion.
--
-- Ghodmode
Blessed is he who has found his work; let him ask no other blessedness.
-- Thomas Carlyle
|