私はこのパターンをperlでよくやっていることに気づきました
sub fun {
my $line = $_[0];
my ( $this, $that, $the_other_thing ) = split /\t/, $line;
return { 'this' => $this, 'that' => $that, 'the_other_thing' => $the_other_thing};
}
明らかに、与えられた変数の配列をキーが変数と同じ名前であるマップに変換する関数の出力を返すことで、このパターンを単純化できます。
sub fun {
my $line = $_[0];
my ( $this, $that, $the_other_thing ) = split /\t/, $line;
return &to_hash( $this, $that, $the_other_thing );
}
要素の量が大きくなるにつれて役立ちます。どうすればいいですか?PadWalker とクロージャを組み合わせることができるように見えますが、コア言語のみを使用してこれを行う方法が欲しいです。
編集: thb はこの問題に対する巧妙な解決策を提供しましたが、多くの難しい部分 (tm) をバイパスするため、チェックしていません。コア言語の分解セマンティクスに依存して、実際の変数から反映を追い出したい場合はどうしますか?
EDIT2:PadWalkerとクロージャーを使用することをほのめかしたソリューションは次のとおりです。
use PadWalker qw( var_name );
# Given two arrays, we build a hash by treating the first set as keys and
# the second as values
sub to_hash {
my $keys = $_[0];
my $vals = $_[1];
my %hash;
@hash{@$keys} = @$vals;
return \%hash;
}
# Given a list of variables, and a callback function, retrieves the
# symbols for the variables in the list. It calls the function with
# the generated syms, followed by the original variables, and returns
# that output.
# Input is: Function, var1, var2, var3, etc....
sub with_syms {
my $fun = shift @_;
my @syms = map substr( var_name(1, \$_), 1 ), @_;
$fun->(\@syms, \@_);
}
sub fun {
my $line = $_[0];
my ( $this, $that, $other) = split /\t/, $line;
return &with_syms(\&to_hash, $this, $that, $other);
}