How to call a subroutine that accepts 2 subroutine references?

Imagine this routine:

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

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

test { print 1 },{ print 2 };

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

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

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

EDIT: Is there no way to call without sub?

+3
source share
4 answers

You can do it:

test(sub { print 1 }, sub { print 2 });
+8
source

You need to explicitly say

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

or

test { print 1 } sub { print 2 };

"" . http://perldoc.perl.org/perlsub.html#Prototypes:

An , , , sub .

:

test { print 1 } against { print 2 };

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

.

+12

:

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

CreateDB::generate(\%param, \&wayPointCode, \&doHeader, \&debugCode);
+1

, Devel::Declare

, Devel::Declare:

CPAN Devel:: Declare 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 pod:

use PerlX::MethodCallWithBlock;

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


Devel :: Declare is a much more reliable and more robust way to distort your Perl code compared to using a source filter, for example Filter::Simple.

Here is a video from its author, which can help a little more.

/ I3az /

+1
source

Source: https://habr.com/ru/post/1721023/


All Articles