虽然试图了解闭包,读通Perl的常见问题,并coderef在perlref发现这些例子:
sub add_function_generator {
return sub { shift() + shift() };
}
my $add_sub = add_function_generator();
my $sum = $add_sub->(4,5);
Run Code Online (Sandbox Code Playgroud)
和
sub newprint {
my $x = shift;
return sub { my $y = shift; print "$x, $y!\n"; };
}
$h = newprint("Howdy");
&$h("world");
Run Code Online (Sandbox Code Playgroud)
这里有两种调用存储在变量中的函数的形式.
&$func($arg)
$func->($arg)
Run Code Online (Sandbox Code Playgroud)
那些完全相同(只是语法上不同)或者这里有一些差异吗?
有:
package MyPath;
use strict;
use warnings;
use Moose;
has 'path' => (
is => 'ro',
isa => 'Path::Class::Dir',
required => 1,
);
1;
Run Code Online (Sandbox Code Playgroud)
但是想用两种方式创建这个对象,比如:
use strict;
use warnings;
use MyPath;
use Path::Class;
my $o1 = MyPath->new(path => dir('/string/path')); #as Path::Class::Dir
my $o2 = MyPath->new(path => '/string/path'); #as string (dies - on attr type)
Run Code Online (Sandbox Code Playgroud)
当用'Str'调用它时 - 想要在MyPath包内部将它转换为Class :: Path :: Dir,所以,两者:$o1->path并且$o2->path应该返回祝福Path::Class::Dir
当我尝试将定义扩展到下一个时:
has 'path' => (
is => 'ro',
isa => 'Path::Class::Dir|Str', #allowing both attr …Run Code Online (Sandbox Code Playgroud) 写下一个更优雅的方式是什么?
sub depend {
my($x,$y) = @_;
die "only one allowed" if( defined($x) && defined($y) );
die "one must be defined" unless ( defined($x) || defined($y) );
if( defined($x) ) {
$y = somefunc($x);
} else {
$x = somefunc($y);
}
return($x,$y);
}
Run Code Online (Sandbox Code Playgroud)
该函数应该只得到一个参数.如果get define both = error,如果定义none = error.未定义的arg是根据定义的arg计算的.
目前有这个演示代码:
use 5.012;
use Data::Dump;
my $AoH = [
{a => "aval"}, #exactly only one key-value
{b => "bval"}, #for each
{c => "cval"}, #array element
];
dd $AoH;
my @arr = map { each $_ } @$AoH;
dd @arr;
Run Code Online (Sandbox Code Playgroud)
它起作用并产生我想要的结果
[{ a => "aval" }, { b => "bval" }, { c => "cval" }]
("a", "aval", "b", "bval", "c", "cval")
Run Code Online (Sandbox Code Playgroud)
问题是:结构是否正确map { each $_ },还是可以用"另一种方式"来做到这一点?