1

これはどのように機能しますか?

    use strict;
    use warnings;

    sub base {
      my $constant = "abcd";
      my ($driver_cr) = (@_);
      &$driver_cr;
    }

    base(sub {print $constant});

つまり、 $driver_cr が $constant なしでアクセスできる方法は次のとおりです。

  1. $constant を引数としてドライバーに渡す &$driver_cr($constant)
  2. $constant のスコープをグローバルに変更するour $constant = "abcd";
  3. 共通ブロックを作成し、ベースから $constant を移動:

    use strict;
    use warnings;
    
    {
      my $constant = "abcd";
      sub base {
        my ($driver_cr) = (@_);
        &$driver_cr;
      }
      base(sub {print $constant});
    }
    
4

1 に答える 1

4

それが関数の引数の目的です。

use strict;
use warnings;

sub base {
  my $constant = "abcd";
  my ($driver_cr) = (@_);
  $driver_cr->($constant);
}

base(sub {
    my $constant = shift;
    print $constant;
});

ただし、引数を渡すことに本当に反対している場合は、次のようにします。

use strict;
use warnings;
use Acme::Lexical::Thief;

sub base {
  my $constant = "abcd";
  my ($driver_cr) = (@_);
  &$driver_cr;
}

base(sub {
    steal $constant;
    print $constant;
});
于 2014-07-15T08:46:35.017 に答える