Hacker News new | ask | show | jobs
by jbert 4003 days ago
I'm interested in the details of the variable scoping problems are. I'd have thought that perl's explicit declaration of lexicals with 'my' was better than "declare at first use" of javascript/python/ruby.

[There's a class of mistake where you typo a variable name which you can make in those languages which gets caught in a language where you have to declare variables.]

1 comments

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).

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).