perl closures and $_

前端 未结 2 2096
佛祖请我去吃肉
佛祖请我去吃肉 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
      &{$_}();
    }
    
    0 讨论(0)
  • 2021-02-13 02:58

    $_ is a global variable and should not be used in closure. Before using it assign this to a lexically scoped variable as shown bewlow. This will produce expected o/p.

    #!/usr/bin/perl -w
    
    use strict;
    my @closures;
    
    
    foreach (1..3) {
       my $var = $_;
       push @closures, sub { print "I will remember $var"; };
    }
    
    foreach (@closures) {
      $_->();
      print "\n";
    }
    
    0 讨论(0)
提交回复
热议问题