perl closures and $_

前端 未结 2 2097
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 01:58

One of the first things I try to learn in an unfamiliar programming language is how it handles closures. Their semantics are often intertwined with how the language handles scop

2条回答
  •  旧巷少年郎
    2021-02-13 02:48

    Closures only close over lexical variables; $_ is normally a global variable. In 5.10 and above, you can say my $_; to have it be lexical in a given scope (though in 5.18 this was retroactively declared to be experimental and subject to change, so better to use some other variable name).

    This produces the output you expected:

    use strict;
    use warnings;
    use 5.010;
    my @closures;
    foreach my $_ (1..3) {
      # create some closures
      push @closures, sub { say "I will remember $_"; };
    }
    foreach (@closures) {
      # call the closures to see what they remember
      # the result is not obvious
      &{$_}();
    }
    

提交回复
热议问题