您好我正在尝试编写一个简单的子程序,它将比较两个数字,看一个是否大于另一个,小于或等于。 到目前为止,我有以下代码:
sub Value
{ my $num = $_[0];
my ($last) = shift;
my $compare = sub {
if ($last < $last) {print "Less than \n"; } else {print "Greater than \n";};};
my $hashtable;
$hashtable->{"compare"} = $compare;
$hashtable; }
#Execute Statement
my $num1 = Value(57.8);
my $num2 = Value(129.6);
print "Check: ", $num1->{"compare"}->($num2);
有没有人建议我如何让它正常工作?谢谢!
答案 0 :(得分:3)
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;
答案 1 :(得分:1)
这样做:
our $last;
sub compare
{
my ($x, $y) = @_;
if( $x > $y )
{
print("$x is greater than $y\n");
}
elsif( $x == $y )
{
print("$x is equal to $y\n");
}
else
{
print("$x is less than $y\n");
}
$last = ($x, $y);
};
my $lastValues = compare(3, 4); # pass numbers which you want to compare instead of 3 and 4
print("last compared value = $lastValues");