perl closures and $_

前端 未结 2 1094
刺人心
刺人心 2021-02-13 02:10

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:32

    $_ 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";
    }
    

提交回复
热议问题