Hacker News new | ask | show | jobs
by SwellJoe 4003 days ago
I share your confusion over that assertion. I actually miss Perl's excellent block scope capabilities when working in almost every other similar language. I imagine most other languages have gotten it, by now, but a few years ago when I was using Python for a few years for a client it didn't have block scope and I missed it. A brief googling actually hints that maybe Python still doesn't have block scope, which is pretty weird, so I assume I'm googling wrong.

But, perhaps discussion of scope problems in Perl is just when talking about very old code. Perl had some scope atrocities back in Perl 4 and some weirdness in early Perl 5 days. But, for the past 15 years or so, it's been very predictable and has improved (like the syntactic sugar of "my" declarations in foreach or while expressions).

2 comments

I seem to recall that Python not only didn't (doesn't?) have block scope, it tended (tends?) to produce a completely, blithely cryptic error message when the programmer assumes that it does have proper block scope and writes a program that fails as a result. Discovering that was memorable.
Python 3 has changed the "standard" traceback to be more readable and include more information, maybe that one is more to your liking: http://blog.ionelmc.ro/2014/08/03/the-most-underrated-featur...
One weirdness I encountered recently with nested functions:

  sub a {
    my $v;
    sub b {
      # captures only the first
      # instance of $v
    }
  }
This is because named subroutines are created once and variable captures are resolved at that time. I expected the more normal capture semantics you get with anonymous subs, like

  sub a {
    my $v;
    my $b = sub {
      # a new $b each time
      # captures each $v
    }
  }
The lexical scoping rules are precisely what causes this behaviour. The first example defines a nested function which has access to the variables in scope when defined (as you remark).

It's little different than this block defined outside of any function:

  {
  my $v;

  sub b { ... }
  }
Whereas an anonymous function is "defined" each time the enclosing scope is evaluated.

For more info, see: http://www.perlmonks.org/?node_id=389319

HTH

Thanks - useful point. But, I think that's more of an oddity of nested, named subs than anything else. The usual anonymous subs close as you'd expect (as you say).