Jeg prøver at lave noget OO i perl for første gang, og har lidt
problemer.
To klasser 'Deck' og 'Card', hvor et 'Deck' skal indeholde nogle
'Card' objekter.
Problem 1:
tusk@skarbinika
/programming/perl/modern_art$ ./game.pl
kind:1, artist: G
Can't call method "print" on unblessed reference at Deck.pm line 30.
Problem 2:
Hvordan får jeg korrekt lavet nogle 'Card' objekter og lagt dem ind i
et array i et 'Deck' objekt ?
==Card.pm==
package Card;
use strict;
my $count=0;
#constructor
sub new {
my $class=shift;
my $a=shift;
my $k=shift;
my $self={};
$self->{_artist}=undef; #_L_ite metal, _K_rypto, _Y_oko, karl
_G_litter, _C_hr
istin p
$self->{_kind}=undef; # _1_ once around, _d_ouble auction, _o_pen
auction,
# _f_ixed price, _h_idden auction
if (defined($a)) {
$self->{_artist}=$a;
}
if (defined($k)) {
$self->{_kind}=$k;
}
bless($self,$class);
$count++;
return $self;
}
#destroy
sub DESTROY { --$count }
#accessor method for Card _kind
sub kind {
my $self=shift;
if (@_) { $self->{_kind}=shift }
return $self->{_kind};
}
#accessor method for Card _artist
sub artist {
my $self=shift;
if (@_) { $self->{_artist}=shift }
return $self->{_artist};
}
sub print {
my $self=shift;
printf("kind:%s, artist: %s\n",$self->kind,$self->artist);
}
1;
==Deck.pm==
package Deck;
use strict;
my $count=0;
#constructor
sub new {
my $class=shift;
my $self={};
$self->{_cards}[0]=Card->new('K','f'); #hvorfor virker
push($self->{_cards},Card->new('K','f')); ikke ?
$self->{_cards}[1]=Card->new('Y','d');
$self->{_cards}[2]=Card->new('C','h');
$self->{_cards}[3]=Card->new('G','1');
$self->{_cards}[4]=Card->new('L','o');
$count++;
bless($self,$class);
return $self;
}
#destroy
sub DESTROY { --$count }
# virker ikke
# Can't call method "print" on unblessed reference at Deck.pm line 30.
sub print {
my $self=shift;
foreach my $card ($self->{_cards}) {
$card->print();
}
}
1;
==game.pl==
#!/usr/bin/perl -w
use strict;
use Card;
use Deck;
my $a_card=Card->new('G','1');
$a_card->print();
my $a_deck=Deck->new();
$a_deck->print();