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.