3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

処理中の関数に成り代わるSub関数

Posted at

Perlで再帰処理のあるSub関数の名前を変えるときに、再帰部分も変更する手間を省きたい

再帰関数の中でその関数に成り代わるSub関数

sub current_function {
    my $function_name = (caller 1)[3];
    $function_name =~ s/.*:://;
    return @{[&$function_name(@_)]};
}

解説

(caller 1)[3]
callerは引数0で実行中の関数、1で呼び出し元の関数の情報を取得する
[3]はパッケージと関数名が "package::function" 形式で入っている

$function_name =~ s/.*:://;
パッケージ部分があれば消す

@{[&$function_name(@_)]}
関数名からの実行は変数配列ハッシュのように &{'関数名'} ではできないが、
上記のように無名配列リファレンスの要素とすると実行できる

3
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?