Perl class

This is class of Perl

Topics

Class steps

  • Create .pm file(file name start with large letter)
  • Add package first line, the name is same as file name
  • The file should be finished by true statement 1;

Example

Person.pm

package Person;
use strict;

sub printHello {
    print("Hello World!");
}
1;

How to use that

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

Person::printHello;		# this is class method

This is in case of same directory.

Constructor

This is the simplest constructor
Actually, name is arbitrary, but new is tacit rule.

sub new { 
    my $class = shift;		# package name  copy instance to class
    my $self = {};		# create hash ref
    return bless $self, $class;	# 1, data, 2 class name
}

Usage

my $person = Person->new();

with params

sub new {
    my $class = shift;
    my $self = {
                Name => 'none',
                Age => 20,
    };
    return bless $self, $class;
}

getter/setter

We need to add getter/setter by ourselves.
This is an example

sub name {
  my $self = shift;
  if( @_ ){ $self->{Name} = shift }
  return $self->{Name};
}

sub age {
  my $self = shift;
  if( @_ ){ $self->{Age} = shift }
  return $self->{Age};
}

Testing

$person = Person->new();
print "name:" . $person->name() . "\n";
$person->name("Sato");
print "name:" . $person->name() . "\n";

Params Constructor

package Black;
use strict;
use warnings;

sub new {
    my $class = shift;
    my $name = shift;
    bless {
        name => $name,
    }, $class;
}

sub name {
  my $self = shift;
  if( @_ ){ $self->{name} = shift }
  return $self->{name};
}

sub print_name {
    my $self = shift;
    print "Name is ", $self->name, "\n";
}
1;

Use one more shift; and set parameter.


my $black = Black->new(“Rena”);
$black->print_name(%