103 lines
1.7 KiB
Markdown
103 lines
1.7 KiB
Markdown
# OOP
|
|
|
|
PERL의 클래스는 package입니다. 객체는 참조가, 메서드는 서브루틴입니다.
|
|
|
|
```perl
|
|
package Person;
|
|
|
|
use warnings;
|
|
use strict;
|
|
|
|
# 생성자
|
|
sub new {
|
|
my ($class, $args) = @_;
|
|
my $self = bless {
|
|
name => $args->{name},
|
|
age => $args->{age}
|
|
}, $class; # bless()는 객체에 대한 참조를 반환합니다.
|
|
}
|
|
|
|
sub get_name {
|
|
my $self = shift;
|
|
return $self->{name};
|
|
}
|
|
|
|
sub set_name {
|
|
my ($self, $name) = @_;
|
|
$self->{name} = $name;
|
|
}
|
|
|
|
sub get_age{
|
|
my $self = shift;
|
|
return $self->{age};
|
|
}
|
|
|
|
sub set_age{
|
|
my ($self, $age) = @_;
|
|
$self->{age} = $age;
|
|
}
|
|
|
|
sub to_string {
|
|
my $self = shift;
|
|
return "($self->{name}, $self->{age})";
|
|
}
|
|
|
|
sub DESTROY { # 파괴자
|
|
...
|
|
}
|
|
|
|
1; # 클래스 정의의 맨 끝에서 true를 반환해줘야 합니다.
|
|
```
|
|
|
|
```perl
|
|
package Employee; # Person 클래스를 상속할 겁니다.
|
|
|
|
use warnings;
|
|
use strict;
|
|
use lib '/home/elex/Workspace/perl-examples';
|
|
use Person;
|
|
|
|
our @ISA = qw(Person); # Person을 상속. IS-A 관계
|
|
|
|
sub new {
|
|
my ($class, $args) = @_;
|
|
my $self = $class->SUPER::new( $_[1], $_[2] ); # 부모 생성자 호출
|
|
$self->{id} = $args->{id};
|
|
bless $self, $class;
|
|
return $self;
|
|
}
|
|
|
|
sub get_id{
|
|
my $self = shift;
|
|
return$self->{id};
|
|
}
|
|
|
|
sub set_id{
|
|
my ($self, $id) = @_;
|
|
$self->{id} = $id;
|
|
}
|
|
|
|
sub do_work{
|
|
return "working..";
|
|
}
|
|
|
|
sub to_string {
|
|
my $self = shift;
|
|
return "($self->{name}, $self->{age}, $self->{id})";
|
|
}
|
|
```
|
|
|
|
```perl
|
|
#!/usr/bin/perl
|
|
use warnings;
|
|
use strict;
|
|
use lib '/home/elex/Workspace/perl-examples';
|
|
use Person;
|
|
|
|
# 객체 생성
|
|
my $charlie = Person->new({
|
|
name => 'Charlie', age => 14
|
|
});
|
|
# 메서드 호출
|
|
print $charlie->to_string()."\n";
|
|
``` |