我发现自己在 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);
}