1

I have the following subroutines:

sub my_sub {
    my $coderef = shift;    
    $coderef->();
}


sub coderef {
    my $a = shift;
    my $b = shift;

    print $a+$b;
}

and want to call my_sub(\coderef($a,$b)) in this manner i.e I want to provide the arguments of the code ref with it and run it on the my_sub function. Is it possible to do something like this in perl?

4

5 に答える 5

9

それらの潜水艦が額面どおりに取られる場合、my_sub何もしていません。

ここでは次の 2 つのことが行われています。

  1. コードリファレンスを定義する

    my $adder = sub { my ( $first, $second ) = @_; $first + $second };
    
    # Adds first two arguments
    
  2. 必要なパラメータで実行します

    print $adder->(2,3);  # '5'
    

my_subコードリファレンスが最初の引数として渡されるある種のファンクターであると仮定します。

sub functor {
    my $coderef = shift;  # Pull of first argument
    $coderef->( @_ );     # Rest of @_ are coderef arguments
                          # Or simply : sub functor { +shift->( @_ ) }
}

# Usage:

print functor ( $adder, 2, 3 );  # '5'
于 2011-12-04T14:41:59.227 に答える
4

私があなたの質問を正しく理解している場合は、次のように、サブルーチンへのcoderef呼び出しを別の匿名サブルーチンでラップする必要があります。

my_sub(sub { coderef(2, 3); }); # replace 2, 3 with whatever arguments 
于 2011-12-04T13:05:57.850 に答える
2

これは、あなたの望むことですか?

警告を使用します。
厳密に使用します。

&my_sub( \&coderef );

サブ my_sub {
    私の $coderef = シフト;
    $coderef->(2, 3);
}

サブコード参照 {
    私の $a= シフト;
    私の $b = シフト;

    $a+$b を印刷します。
}
于 2011-12-04T13:03:19.593 に答える
1

匿名サブルーチンを使用します。

my $coderef = sub {
    my ($aa, $bb) = @_;
    print $aa + $bb;
};

sub my_sub {
    my ($c_ref, @params) = @_;
    $c_ref->(@params);
}

my_sub($coderef, 2, 3);
于 2011-12-04T13:54:09.390 に答える
1

別のアイデア。おそらく閉鎖はあなたの問題を解決しますか?ファクトリとして記述する場合はcoderef、次のようにコーディングできます。

use strict;
use warnings;

my_sub(coderef(2,3));

sub my_sub {
  my $coderef = shift;    
  $coderef->();
}

sub coderef {
    my $a = shift;
    my $b = shift;

    return sub { print $a + $b };
}

出力

5
于 2011-12-09T01:36:44.087 に答える