Perl5OOP编程

我正在尝试将以下 python 程序移植到 perl5:

import numpy as np


class Hensuu:
    def __init__(self, data):
        self.data = data


class Kansuu:
    def __call__(self, input):
        x = input.data
        y = x ** 2
        output = Hensuu(y)
        return output

x = Hensuu(np.array(9.0))
f = Kansuu()
y = f(x)

print(type(y))
print(y.data)

<class ' main .Hensuu'> 81.0

亨苏.pm

package Hensuu;
use strict;
use warnings FATAL => 'all';
our $version = 1.0.0;
sub new {
    our ($class,$data) = @_;
    my $self = {data=>$data};
    bless $self,$class;
    return $self;
}
1;

步骤1.pl

#!perl
use strict;
use warnings FATAL => 'all';
use Hensuu;
use PDL;
use PDL::Matrix;
my $datas = mpdl [[1.0,2.0],[3.0,4.0]];
my $x = Hensuu->new($datas);
print($x=>$datas);

Kansuu.pm

package Kansuu;
#use strict;
use warnings FATAL => 'all';
use Hensuu;
sub call {
    my ($self,$input) = @_;
    my $x = {$input => $data};
    #print($x);
    my $y = $x ** 2;
    my $output = Hensuu->new($y);
    return($output);
}
1;

步骤2.pl

#!perl
#use strict;
use warnings FATAL => 'all';
use PDL;
use PDL::Matrix;
use Hensuu;
use Kansuu;

my $a = mpdl [9.0];
my $x = Hensuu->new($a);
#my $f = Kansuu;
#my $y = $f->call($x);
my $y = Kansuu->call($x);
print($x=>$a);
print(ref($y));
print($y);

发射(step2.pl)

Hensuu=HASH(0x1faf80)
[
 [9]
]
HensuuHensuu=HASH(0x25b71c0)
Process finished with exit code 0

上面的程序(step2.pl),我想用print($y);将显示设置为“81”,但我不能。环境为Windows 10 pro,草莓perl PDL版(5.32.1.1),IDE为intellij idea社区版perl插件(2020.3)。

回答

Hensuu.pm:

package Hensuu;
use strict;
use warnings;

sub new {
    my ($class, $data) = @_;
    return bless {data => $data}, $class
}

sub data {
    my ($self) = @_;
    return $self->{data}
}

1

Kansuu.pm:

package Kansuu;
use strict;
use warnings;

use Hensuu;

sub call {
    my ($input) = @_;
    my $x = $input->data;
    my $y = $x ** 2;
    my $output = Hensuu->new($y);
    return $output->data
}

1

step2.pl:

#!perl
use strict;
use warnings;
use feature qw{ say };

use PDL;
use PDL::Matrix;
use Hensuu;
use Kansuu;

my $p = mpdl [9.0];
my $x = Hensuu->new($p);
my $y = Kansuu::call($x);
say $y;
  • 不要将our变量用于不需要全局的事物。
  • 不要$a用作词法变量,它是sort 中使用的特殊变量。
  • 低级 Perl OO 不会为属性创建访问器,您需要自己实现它们(有关更高级别的方法,请参阅Moo或Moose)。
  • Kansuu 不是 OO 类,使用完全限定的子程序而不是方法。
  • @ikegami: Yes, but if there's no instance and no class attribute, I tend not to include OO at all (kind of Occam's razor). Also, I'd use `$class` instead of `$self` for a class method.

以上是Perl5OOP编程的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>