perl closures and $_

前端 未结 2 2095
佛祖请我去吃肉
佛祖请我去吃肉 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: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";
    }
    

提交回复
热议问题