简体   繁体   中英

Perl 5 OOP programming

I'm trying to port the following python program to 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

Hensuu.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;

step1.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;

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

emit(step2.pl)

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

The above program (step2.pl), I want to set the display to "81" with print($y);, but I can't. Environment is Windows 10 pro, strawberry perl PDL edition (5.32.1.1), The IDE is intellij idea community edition perl plugin (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;
  • Don't use our variables for things that don't need to be global.
  • Don't use $a as a lexical variable, it's a special variable used in sort .
  • Low level Perl OO doesn't create accessors for attributes, you need to implement them yourself (see Moo or Moose for higher level ways).
  • Kansuu is not an OO class, use a fully qualified subroutine instead of a method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM