nekolik dotazu na pouziti OOP v Perlu

Michal Polák michal.polak na turboconsult.cz
Pátek Březen 1 12:43:06 MET 2002


Dobry den,

mam nekolik dotazu na pouziti OOP v Perlu.
Na konci dopisu pripojuji zdrojak.

1) Jak zjistim jmena predku objektu ?
Metoda isa se mi nehodi, protoze obecne neznam jmeno predka a tak se ani
nemuzu ptat, zda je dany objekt jeho potomkem.
Existuje snadnejsi cesta nez ta, ktera je v mem zdrojaku ? Tj. pomoci ref
zjistit jmeno tridy objektu a pak pres eval sahnout pro @ISA ?
Je takovyto zpusob "cisty" ?

2) Jak je to s prototypy ? U konstruktoru new jsem uvedl ($) a u metody
toString prototyp (). Presto ale kompilace probehne OK a tvorba objektu $b
neselze. Proc ?

Verze Perlu je 5.6.1.
Uvedeny program by mel zobrazit:

Metoda toString(): cz::tconsult::temp::xmp::test::potomek=ARRAY(0x1623f94) -
Tukan
Je $a potomek 'cz::tconsult::temp::xmp::test::predek' ? Ano
Predci pres tridu natvrdo: cz::tconsult::temp::xmp::test::predek
Predci z instance $a: cz::tconsult::temp::xmp::test::predek
Jaktoze tvorba $b neselhala ? Metoda toString():
cz::tconsult::temp::xmp::test::potomek=ARRAY(0x162f74c) - Hoko

Dekuji za pripadne rady a vas cas.

S pozdravem
--
Michal Polak
system programmer, TurboConsult s.r.o.
mpolak na email.cz, michal.polak na turboconsult.cz
ICQ: 106342077
Tel: +420 5 32 161 111

Everyone should hold strong convictions, I am convinced I will have another
glass.


package cz::tconsult::temp::xmp::test::predek;
use strict;
use English;
use fields qw(name);
sub new($) {

  my cz::tconsult::temp::xmp::test::predek $this = shift @ARG;
  my ($aName) = @ARG;
  unless (ref $this) {
    $this = fields::new($this);
  };

  $this->{name} = $aName;
  return $this;
}

sub toString() {

  my $this = shift @ARG;
  return "Metoda toString(): $this - " . $this->{name};
}

package cz::tconsult::temp::xmp::test::potomek;
use base 'cz::tconsult::temp::xmp::test::predek';
use strict;
use English;
use fields qw();
sub new($) {

  my cz::tconsult::temp::xmp::test::potomek $this = shift @ARG;
  my ($aName) = @ARG;
  unless (ref $this) {
    $this = fields::new($this);
  };

  $this->SUPER::new($aName); # init base fields
  return $this;
}

package main;

use strict;
use English;

my $a = new cz::tconsult::temp::xmp::test::potomek('Tukan');
print $a->toString(), "\n";
my $superClaaName = 'cz::tconsult::temp::xmp::test::predek';
print "Je \$a potomek '$superClaaName' ? ", (($a->isa($superClaaName)) ?
"Ano" : "Ne"), "\n";
print "Predci pres tridu natvrdo: ", join (', ',
@cz::tconsult::temp::xmp::test::potomek::ISA), "\n";

my $aClassName = ref($a);
print "Predci z instance \$a: ", join (', ', eval "\@${aClassName}::ISA"),
"\n";

my $b = new cz::tconsult::temp::xmp::test::potomek('Hoko', 'dalsi
parametr');
print 'Jaktoze tvorba $b neselhala ? ', $b->toString('jiny parametr',
'dalsi', 'a jeste jeden'), "\n";





Další informace o konferenci Perl