in reply to Re: Use of 'our' considered harmful
in thread Use of 'our' considered harmful

how about a closure where you want to use a var declared outside of the closure

Well, by definition, a closure does operate on variables outside itself... that's the whole point.

As for a closure that is based on a global variable (lexical or otherwise), I can only ask "Why would you want to do a thing like that?" If the variable is global, it sort of defeats the purpose of wrapping it up in a closure. (Otherwise you would just use local).

So yes, you could do so, but I don't think it qualifies as a Real World Example™ as per the OP. I think anything you could come up with could be wrapped up in a sub and use lexical mys, and I think it would be better that way.

- another intruder with the mooring of the heat of the Perl

Replies are listed 'Best First'.
Re^3: Use of 'our' considered harmful
by tantarbobus (Hermit) on Sep 24, 2004 at 10:44 UTC
    sub whatever_its_called { our ($dbh) = DBI->connect(...); sub do_hit { $dbh->prepare("stuff"); } }

      I don't use our, so I'm not sure if there's some subtlety going on here that I am missing. With that in mind, I fail to see how your sub differs from:

      sub whatever_its_called { my ($dbh) = DBI->connect(...); sub do_hit { $dbh->prepare("stuff"); } }

      Look ma! no our! That's the whole point.

      - another intruder with the mooring of the heat of the Perl

        Actually, your code closes the $dbh before you ever execute the query! Where as the our version doesn't. With the our version, the user can use $dbh in other functions, because $dbh is a global.

        I'm not saying our is required to do this -- it isn't -- I'm just saying you broke the program by blindly switching to my.

        You don't want to try to define a named sub inside of another named sub! You can get away with it if you only use global variables, but you never want to do it with lexicals.

        You have just triggered the infamous puzzling, "variable will not stay shared" warning. See Re (tilly) 9: Why are closures cool? which tries to explain what Perl is trying to warn you about and why there is no good resolution to the problem.

      But surely my would be more appropriate here - $dbh is still a global variable, it is only the effect of our that is lexical.

      /J\