Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Should a constructor ever return undef?

by Zaxo (Archbishop)
on Jul 11, 2003 at 01:36 UTC ( [id://273211]=note: print w/replies, xml ) Need Help??


in reply to Should a constructor ever return undef?

That's the convention in perl. One way to use it is like this,

my $foo = MaybeADirectoryObject->new(@args) or die 'No object', $!; # ...
A blessed reference does not evaluate false, so defined is not needed in the logic.

The eval {die 'No Object' if $error} with $@ handling is really no cleaner. In fact, eval returns undef if block exit is by die-ing or other trappable error, and can be handled the same as the more direct code above.

Update: I previously had the constructor wrapped in defined, but changed it and the description just as ++ctilmes posted his useful comment.

The big difference between perl and C++ exception handling is that, in C++, catch clauses are the responsibility of the try block, while in perl they are the responsibility of the caller. That is a large conceptual gap, but is not so different in application.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: Should a constructor ever return undef?
by ctilmes (Vicar) on Jul 11, 2003 at 01:39 UTC
    I like simply:
    my $foo = MaybeADirectoryObject->new(@args) or die "No object: $!";
    eval() catching exceptions seems more awkward to me.

    I would probably carp() instead of print in the constructor.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-03-29 00:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found