我的功能是
use 5.028;
use strictures;
use Kavorka qw(fun);
fun foobar(:$foo, :$bar) { say $foo, $bar; }
我需要传递命名参数,而不是位置参数。
foobar('quux', 'quuuux');
# Unknown named parameter: quux at … line 5.
# main::foobar("quux", "quuuux") called at … line 7
但是
foobar(foo => 'quux', bar => 'quuuux');
# ok
Hash
或HashRef
也被接受。
my %args = (foo => 'quux', bar => 'quuuux');
foobar(%args);
my $args = {foo => 'quux', bar => 'quuuux'};
foobar($args);
ES6中存在一个快捷方式,其中扩展了对象文字中的变量(ed:MDN链接?):
function foobar({foo, bar}) { console.log(foo, bar); }
foobar({foo: 'quux', bar: 'quuuux'});
const foo = 'quux';
const bar = 'quuuux';
foobar({foo: foo, bar: bar});
foobar({foo, bar}); // NB!
In Perl 6 a :
prefixed variable in a parameter signature will create a key of the same name:
use v6;
sub foobar(:$foo, :$bar) { say $foo, $bar; }
foobar(foo => 'quux', bar => 'quuuux');
my $foo = 'quux';
my $bar = 'quuuux';
foobar(foo => $foo, bar => $bar);
foobar(:$foo, :$bar); # NB!
如何实现与Perl 5相当的效果?
my $foo = 'quux';
my $bar = 'quuuux';
foobar(???);
答案 0 :(得分:3)
我有两种方法可以使用PadWalker(感谢建议暴民)或Hash Slices:
use strict;
use warnings;
use Data::Dumper;
use PadWalker qw/ var_name /;
sub test_sub { print Dumper [ @_ ] }
my %vars;
$vars{foo} = "foo_data";
$vars{bar} = "var_data";
test_sub( %{vars}{qw/ foo bar/} );
# nv = named variables ( rename as needed )
sub nv { map { ( substr( var_name(1, \$_), 1) => $_ ) } @_ }
my $foo = 'foo_stuff';
my $bar = 'bar_stuff';
test_sub( nv( $foo, $bar ) );
哪个给:
$VAR1 = [
'foo',
'foo_data',
'bar',
'var_data'
];
$VAR1 = [
'foo',
'foo_stuff',
'bar',
'bar_stuff'
];
必须在nv中进行替换,否则会显示出印记,但这就是我不考虑更深层次的魔术就能想到的最好的东西。
如果不使用nv,则需要进行更深入的魔术操作...
也使用您的Kavorka代码:
use 5.020;
use strictures;
use Kavorka qw(fun);
use PadWalker qw/ var_name /;
fun foobar(:$foo, :$bar) { say $foo, $bar; }
my %vars;
$vars{foo} = "foo_data";
$vars{bar} = "var_data";
foobar( %{vars}{qw/ foo bar/} );
# nv = named variables ( rename as needed )
sub nv { map { ( substr( var_name(1, \$_), 1) => $_ ) } @_ }
my $foo = 'foo_stuff';
my $bar = 'bar_stuff';
foobar( nv( $foo, $bar ) );
给予:
foo_datavar_data
foo_stuffbar_stuff
不幸的是,我没有在本地安装5.28