11

別の投稿への回答でこのコードを見ました: Why would I use Perl anonymous subroutines instead of a named one? 、しかし、何が起こっているのか正確に把握できなかったので、自分で実行したかったのです。

sub outer
{
  my $a = 123;

  sub inner
  {
    print $a, "\n"; #line 15 (for your reference, all other comments are the OP's)
  }

  # At this point, $a is 123, so this call should always print 123, right?
  inner();

  $a = 456;
}

outer(); # prints 123
outer(); # prints 456! Surprise!

上記の例では、「変数 $a は 15 行目で共有されません。明らかに、これが出力が「予期しない」理由ですが、ここで何が起こっているのかまだよくわかりません。

sub outer2
{
  my $a = 123;

  my $inner = sub
  {
    print $a, "\n";
  };

  # At this point, $a is 123, and since the anonymous subrotine 
  # whose reference is stored in $inner closes over $a in the 
  # "expected" way...
  $inner->();

  $a = 456;
}

# ...we see the "expected" results
outer2(); # prints 123
outer2(); # prints 123

同じように、この例でも何が起こっているのかわかりません。誰か説明してくれませんか?

前もって感謝します。

4

2 に答える 2

13

これは、サブルーチンのコンパイル時と実行時の解析に関係しています。diagnosticsメッセージの通り、

内側のサブルーチンが呼び出されると、外側のサブルーチンの変数の値が、外側のサブルーチンへの最初の 呼び出しの前と呼び出し中に表示されます。この場合、外側のサブルーチンへの最初の呼び出しが完了すると、内側と外側のサブルーチンは変数の共通の値を共有しなくなります。つまり、変数は共有されなくなります。

コードに注釈を付ける:

sub outer
{
  # 'my' will reallocate memory for the scalar variable $a
  # every time the 'outer' function is called. That is, the address of
  # '$a' will be different in the second call to 'outer' than the first call.

  my $a = 123;


  # the construction 'sub NAME BLOCK' defines a subroutine once,
  # at compile-time.

  sub inner1
  {

    # since this subroutine is only getting compiled once, the '$a' below
    # refers to the '$a' that is allocated the first time 'outer' is called

    print "inner1: ",$a, "\t", \$a, "\n"; 
  }

  # the construction  sub BLOCK  defines an anonymous subroutine, at run time
  # '$inner2' is redefined in every call to 'outer'

  my $inner2 = sub {

    # this '$a' now refers to '$a' from the current call to outer

    print "inner2: ", $a, "\t", \$a, "\n";
  };

  # At this point, $a is 123, so this call should always print 123, right?
  inner1();
  $inner2->();

  # if this is the first call to 'outer', the definition of 'inner1' still
  # holds a reference to this instance of the variable '$a', and this
  # variable's memory will not be freed when the subroutine ends.

  $a = 456;
}
outer();
outer();

典型的な出力:

inner1: 123     SCALAR(0x80071f50)
inner2: 123     SCALAR(0x80071f50)
inner1: 456     SCALAR(0x80071f50)
inner2: 123     SCALAR(0x8002bcc8)
于 2013-05-07T17:57:25.163 に答える
1

\&inner; を印刷できます。最初の例 (定義後) では、 $inner; を出力します。秒で。

表示されるのは、最初の例では等しく、2 番目の例では異なる16 進コード参照です。したがって、最初の例では、inner は 1 回だけ作成され、outer() の最初の呼び出しから常に $a レキシカル変数にクロージャされます。

于 2013-05-07T17:54:29.917 に答える