3

Imagine this subroutine:

sub test(&&)
{
    my $cr1 = shift;
    my $cr2 = shift;
    $cr1->();
    $cr2->();
}

I know I can call it like: test(\&sub1,\&sub2), but how can I call it like:

test { print 1 },{ print 2 };

If I say that the subroutine takes only one &, than sending a block will work. I don't know how to make it work with 2.

If I try to run it like that, I get:

Not enough arguments for main::test at script.pl line 38, near "},"

EDIT: is there no way of invoking without sub?

4

4 に答える 4

12

はっきり言う必要があります

test( sub { print 1 }, sub { print 2 } );

また

test { print 1 } sub { print 2 };

暗黙の「サブ」は、最初の引数でのみ使用できます。 http://perldoc.perl.org/perlsub.html#Prototypes :

& には無名サブルーチンが必要です。これを最初の引数として渡す場合、sub キーワードや後続のコンマは必要ありません。

いくつかのものは、それを偽造するためにそこに余分な単語を使用しています:

test { print 1 } against { print 2 };

sub against (&) { $_[0] }
sub test (&@) { ... }

しかし、私はそれほど好きではありませんでした。

于 2009-10-25T18:16:17.980 に答える
8

あなたはこれを行うことができます:

test(sub { print 1 }, sub { print 2 });
于 2009-10-25T18:12:21.003 に答える
1

本当に構文をもっと曲げたい場合は、以下を見てください。Devel::Declare

使用するモジュールの例Devel::Declare

Devel::Declareに依存するCPANのモジュールの完全なリストはCPANTS

これがTest::Class :: Sugar podの例です:

use Test::Class::Sugar;

testclass exercises Person {
    # Test::Most has been magically included

    startup >> 1 {
        use_ok $test->subject;
    }

    test autonaming {
        is ref($test), 'Test::Person';
    }

    test the naming of parts {
        is $test->current_method, 'test_the_naming_of_parts';
    }

    test multiple assertions >> 2 {
        is ref($test), 'Test::Person';
        is $test->current_method, 'test_multiple_assertions';
    }
}

Test::Class->runtests;


そして、ここにPerlX :: MethodCallWithBlockポッドからのセクシーなものがあります:

use PerlX::MethodCallWithBlock;

Foo->bar(1, 2, 3) {
  say "and a block";
};


Devel :: Declareは、のようなソースフィルターを使用する場合と比較して、Perlコードをゆがめるためのはるかに堅牢で賢明な方法ですFilter::Simple

これは、もう少し役立つかもしれないその作者からのビデオです。

/ I3az /

于 2009-10-26T10:01:07.040 に答える
1

プログラムの 1 つに次のコードがあります。

sub generate($$$$)
{
    my ($paramRef, $waypointCodeRef, $headerRef,
        $debugCodeRef) = @_;
...
   &$headerRef();
...
       my $used = &$waypointCodeRef(\%record);

そして、私はそれを

CreateDB::generate(\%param, \&wayPointCode, \&doHeader, \&debugCode);
于 2009-10-25T18:14:52.840 に答える