- 你把你的论点拆开包装弄乱了
Values
。您将第一个参数分配给$num
,然后shift
将第一个参数分配给$last
,因此$num
和$last
将始终具有相同的值。
- 您与 进行比较
$last
,$last
这没有用。
- 您将闭包放入
$hashtable->{compare}
,但执行该check
字段的内容,即undef
.
- 您的闭包将数据打印到当前选定的文件句柄,但不返回任何有用的信息。打印返回值似乎并不明智。
$num1
并且$num2
是闭包,而不是数字。将参数传递给闭包不会做任何事情,因为您的闭包不会解压缩任何参数。
这是一个应该解决您的问题的实现:
use strict; use warnings;
use Test::More;
sub create_closure {
my ($x) = @_;
my $operations = {
compare => sub { my ($y) = @_; return $x <=> $y },
add => sub { my ($y) = @_; return $x + $y },
value => $x,
};
return $operations;
}
# some tests
my $ops = create_closure(15);
ok( $ops->{compare}->(15) == 0, "compare to self" );
ok( $ops->{compare}->(20) < 0, "compare to larger");
ok( $ops->{add}->(5) == 20, "add");
ok( $ops->{value} == 15, "value");
my $ops1 = create_closure(150);
ok( $ops1->{compare}->($ops->{value}) > 0, "compare to smaller value");
done_testing;
编辑
您不能直接比较两个$ops
,但我们可以创建一个返回原始值的字段。
但是,如果您打算更频繁地执行此类操作,则可能需要使用对象和运算符重载:
use strict; use warnings; use Test::More;
{
package Ops;
sub new {
my ($class, $val) = @_;
if (ref $val eq __PACKAGE__) {
($val, $class) = ($$val, __PACKAGE__);
}
bless \$val => $class;
}
use overload
# overload numeric coercion
'0+' => sub { ${ $_[0] } },
# overload addition. Take care to dereference to avoid infinite loops.
'+' => sub {
my ($self, $other) = @_;
Ops->new($$self + $other);
},
# overload numeric comparision. Take care to swap the args if neccessary.
'<=>' => sub {
my ($self, $other, $swapped) = @_;
(my $val, $other) = $swapped ? ($other, $$self) : ($$self, $other);
Ops->new($val <=> $other);
}
}
my $ops1 = Ops->new( 15);
my $ops2 = Ops->new(150);
# some tests
ok( ($ops1 <=> 15) == 0, "compare to self" );
ok( ($ops1 <=> 20) < 0, "compare to larger");
ok( ($ops1 + (5)) == 20, "add");
ok( $ops1 == 15, "value");
ok( ($ops2 <=> $ops1) > 0, "compare to smaller value");
done_testing;