-1

你好我正在尝试编写一个简单的子程序,它将比较两个数字,看看一个是否大于另一个,小于或等于。到目前为止,我有以下代码:

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);

有没有人建议我如何让它正常工作?谢谢!

4

2 回答 2

3
  1. 你把你的论点拆开包装弄乱了Values。您将第一个参数分配给$num,然后shift将第一个参数分配给$last,因此$num$last将始终具有相同的值。
  2. 您与 进行比较$last$last这没有用。
  3. 您将闭包放入$hashtable->{compare},但执行该check字段的内容,即undef.
  4. 您的闭包将数据打印到当前选定的文件句柄,但不返回任何有用的信息。打印返回值似乎并不明智。
  5. $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;
于 2013-03-23T18:53:43.913 回答
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");
于 2013-03-23T17:47:45.773 回答