On 11/03/2006 02:23 AM, Muttley Meen wrote:
Hi!
Sorry if I double post, but the maillserver seems to have something against
perl scripts attachements, so my first email was droped by the MTA : /
Maybe if I put the code inline will be ok

In the attached script I implement two packages:
Package1 and Package2.

Package2 is derived from Package1, which I guess I dont well.
Now Package1 has a method called IncErr which increments a variable named $err.

If I call something like:

$a = Package1::new();
$a->IncErr();
print "ERR1: $a->{err}\n"; # should print 1

all goes well, but if I call something like:

$a = Package1::new();
$a->Package2->Create(); # this should call IncErr too

This is not allowed because "Package2" is not a method within the class Package1. You want this:

my $b = Package2->new();
$b->Create();
print "ERR(\$b): $b->{err}\n";

print "ERR1: $a->{err}\n"; # should print 1
doent't work as I expected.

Is there something wrong with the way I `bless`-ed the class Package2 ?



------>8-----------
#! /usr/bin/perl

use strict;
use warnings;
# Modify your program to work with these.

package Package1 ;
sub new {
   my ($class) = @_;
   $class  = __PACKAGE__ ;

   print "Call new [".$class."]\n" ;
   $r      = [];
   $this   = {};
   $class->{err} = 0 ;

   $r->[0] = Package2::new($this->{sock_fd} );

   bless $this, $class;
   return $this ;
}

sub IncErr {
   my $this = shift ;
   $this->{err} += 1 ;
}

sub Package2 {
   my $this = shift ;
   @_ ? ($r->[0] = shift) : $r->[0];
}






package Package2 ;
@ISA = ("Package1");
sub new {
   my ( $this, $sock ) = @_ ;
   $class = __PACKAGE__ unless @_;
   $this->{sock_fd}    = $sock ;
   bless $this;
   return $this ;
}

sub Create {
   my $this = shift;
   print "Call Create\n" ;
   print "ERR2: $this->{err} ( this should print 2 )\n" ;
   $this->IncErr() ;
   print "ERR2: $this->{err} ( this should print 3 )\n" ;
}

my $a = Package1::new();
$a->IncErr();
$a->IncErr();
$a->Package2->Create();
print "ERR1: $a->{err} ( this should print 3 )\n" ;

------------------->8--------------------


I didn't look in detail at your program, but I also see that you use a suboptimal syntax for creating objects; don't use "::"; use "->", e.g.

my $a = Package1->new();

Using "::" will work, but it creates problems that will make you
sad--such as preventing inheritance.

Using "use strict" and "use warnings" will help you catch errors like the one above where you do "$a->Package2->Create()"



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to