use fields

Im Pet-Modul:

package Pet;
use strict;
use fields qw(name weight _Pet_pid);
my $PID = 0;
sub new {
    my Pet $self = shift;
    unless (ref $self) {
        $self = fields::new($self);
        $self->{_Pet_pid} = "this is Pet's secret ID";
    }
    $self->{name} = "Hey,you!";
    $self->{weight} = 20;
    return $self;
}
1;

Im separaten Programm demopet:

use Pet;
my Pet $rock = new Pet;            # lex. Geltungsbereich

$rock->{nanie}    = "quartz";
$rock->{weight}   = "2kg";
$rock->{_Pet_pid} = 1233;       # privates Attribut

$rock->{color}   = "blue";      # erzeugt Fehler während der Kompilierung

Im Dog-Modul:

package Dog; use strict; use base 'Pet'; # Felder und Methoden von Pet erben use fields qw(name pedigree); # Pet-Namensattribut überschreiben # neues pedigree-Attribut aufnehmen use fields qw(wag ...

Get Programmieren mit Perl now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.