Pacific-Design.com

    
Home Index

1. Perl5

2. Class

+ Object

Perl5 / Class /

Basic Perl Class

package FooClass;

sub new
{
    my $class = shift;
    my $self   = {};
    bless $self, $class;
    return $self;
}

Class with private methods

package Person;
use strict;

#------------------------------------------------------#
my $private_method = sub {
    my $self = shift;
    print "Executing private method\n";
};

#------------------------------------------------------#
sub new
{
    my $class = shift;
    my $self = bless({}, ref $class || $class);
    $self->init();
    $self->$private_method();
    return $self;
}

#------------------------------------------------------#
sub init
{
    my $self = shift;
    $self->name("unnamed");
    $self->prog("unknown");
    $self->age(0);
    $self->aliases([]);
}

#------------------------------------------------------#
for my $field (qw(name prog age aliases))
{
    my $slot = __PACKAGE__ . "::$field";
    no strict "refs";
    *$field = sub {
        my $self = shift;
        $self->{$slot} = shift if @_;
        return $self->{$slot};
    };
}

#------------------------------------------------------#
1;


#!/usr/bin/perl
use strict;
use warnings;
use Person;

my $obj = new Person();

$obj->name("Kevin Thomas Duraj");
$obj->prog("perl");
$obj->age(32);
$obj->aliases( ["Perl", "Miska", "NLP"] );

print "\n--------- Variable GET Accessor ---------\n";
print "name="    . $obj->name . "\n";
print "prog="    . $obj->prog . "\n";
print "age="     . $obj->age  . "\n";
print "aliases=", join(", ", @{$obj->aliases}),  "\n";
print "\n--------- Initialize Object -------------\n";
$obj->init();
print "name="    . $obj->name . "\n";
print "prog="    . $obj->prog . "\n";
print "age="     . $obj->age  . "\n";

__END__
Output

--------- Variable GET Accessor ---------
name=Kevin Thomas Duraj
prog=perl
age=32
aliases=Perl, Miska, NLP

--------- Initialize Object -------------
name=unnamed
prog=unknown
age=0