Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^5: OUR declaration

by perrin (Chancellor)
on Sep 25, 2006 at 15:34 UTC ( [id://574756]=note: print w/replies, xml ) Need Help??


in reply to Re^4: OUR declaration
in thread OUR declaration

I'll bring this up on the mod_perl dev list. I don't think we should advise people to use such a crazy construct.

The problems people encounter with ModPerl::Registry are usually not caused by inner subroutines, but rather by closures. The closures were always there, but were never noticed before in a non-persistent environment. Consider this:

my $q = CGI->new; show_name(); sub show_name { print $q->param('name'); }

This code will break when run in mod_perl because it forms a closure around $q, making it a private variable for the show_name() sub after compilation.

This problem can be fixed by making $q an our variable, but that's a poor programming practice, giving $q a large scope and persistence that it should not have. The correct fix is to pass the variables that the sub requires:

my $q = CGI->new; show_name($q); sub show_name { my $q = shift; print $q->param('name'); }

Replies are listed 'Best First'.
Re^6: OUR declaration
by ikegami (Patriarch) on Sep 25, 2006 at 15:51 UTC
    Replacing my $q with local our $q would give $q neither a larger scope nor a greater persistance, and would also solve the problem.
      Sure it does. The $q created here is persistent and is part of the symbol table. It will get reset to the value it had before the local was applied to it at the end of the file, but it's still a global variable. Are you really saying you don't think passing variables to subs is a cleaner solution?

        If you think my variables are freed, you're wrong. Neither the variable (on the pad) nor the SV assigned to it are freed at the end of the function.

        Are you really saying you don't think passing variables to subs is a cleaner solution?

        I agree that the number of global variables should be limited, and I find few reason to use them. However, the author thought it acceptable and/or desirable for $q to be a global variable, so I just pointed out a way to make that possible.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://574756]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2024-04-23 10:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found