DBX has asked for the wisdom of the Perl Monks concerning the following question:

I am wondering if there is a better way to avoid the dreaded "Can't use an undefined value as a HASH reference at Class.pm line 84." error when I create an object like:
my $obj = Class->new();
With a constructor that doesn't account for no arguments being sent in. I usually use the following:
sub new{ my ($class,$data) = @_; $data ||= {}; ## avoid empty hashref errors my $attr = { %$data, }; bless $attr, $class; }
The line: $data ||= {}; always seems hackish to me. Is there a better way?

Replies are listed 'Best First'.
Re: Avoiding empty HASH ref. errors
by synapse0 (Pilgrim) on Jul 16, 2001 at 10:32 UTC
    Well, generally, using something like this would go <psuedo-code> my $thing = shift || default; </psuedo-code> which is pretty much what you are doing. So, i'd say it's a perfectly valid, reasonable, and readable method. You're not avoiding emptry hashref, you're setting a default (unless you really are avoiding an empty hashref, where the default shouldn't be an empty set, then yeah, there is probably a better way).
    -Syn0
Re: Avoiding empty HASH ref. errors
by ariels (Curate) on Jul 16, 2001 at 11:34 UTC
    Here's another way.
    my $obj = Class->new(); my $obj2 = Class->new(string => 'foo', num => 11); package Class; sub new{ my $class = shift; my $attr = { @_ }; bless $attr, $class; }

    UPDATE (UTC 0800):

    Of course, this doesn't really solve your problem -- you pass a hash reference as "prototype" when creating your object, I pass the hash itself. My "solution" would change your interface; this might not be possible for you.
Re: Avoiding empty HASH ref. errors
by nysus (Parson) on Jul 16, 2001 at 13:14 UTC
    Check out this code listing from Conway's OO Perl. As you will see, he creates encapsulated class data within the class and uses it to help set default values for the object if data is not passed to the consturctor argument. Pick up the book if you haven't already.

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop";
    $nysus = $PM . $MCF;
    Click here if you love Perl Monks