Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Problem with My New Perl Object

by dws (Chancellor)
on Jun 18, 2002 at 22:32 UTC ( [id://175528]=note: print w/replies, xml ) Need Help??


in reply to Problem with My New Perl Object

Though not the source of your problem, it's a good habit to use the class (package) name that's passed to the constructor, rather than taking the default. Using the passed package name allows you to use the inherited constructor if your class is subclassed.

That is, write

sub new { my $pkg = shift; my $self = bless {}, $pkg;
instead of
sub new { my $self = {}; bless $self;

Replies are listed 'Best First'.
Re: Re: Problem with My New Perl Object
by janx (Monk) on Jun 19, 2002 at 12:49 UTC
    To make even neater write:

    sub new { my $pkg = shift; return bless {}, ref $pkg || $pkg; }
    to be able to pull off tricks like this:

    use strict; use warnings; package BaseClass; sub new { my $pkg = shift; bless {}, ref $pkg || $pkg; } sub bar { $_[0]->{'BaseClass::bar'} = $_[1]; } package SubClass; our @ISA = qw/BaseClass/; package main; my $obj = SubClass->new; my $foo = $obj->new; printf "obj isa %s\nfoo isa %s\n", $obj, $foo;

    Using the  bless {}, ref $pkg || $pkg idiom you are writing classes that are safe to subclass.

    Do have a look at Damian Conways excellent book Object Oriented Perl

    Kay

      To make even neater write:
      return bless {}, ref $pkg || $pkg;

      This technique has been the basis of at least one recent "cargo cult" discussion. There are mixed opinions over whether overloading a class constructor is a prudent thing to do.

      In this post, merlyn points out a cleaner way to get the same effect, without overloading your class constructor.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://175528]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-04-25 06:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found