note
Tanktalus
<p>Just off the top of my head, I would do something like this:</p>
<code>
package Result;
use overload 'bool' => \&as_bool, '""' => \&stringify;
sub new
{
if ($_[0] eq __PACKAGE__)
{
shift;
}
my $self = {
as_bool => $_[0],
string => $_[1],
};
bless $self, __PACKAGE__;
$self;
}
sub as_bool
{
my $self = shift;
$self->{as_bool};
}
sub stringify
{
my $self = shift;
$self->{string};
}
1;
</code>
<p>Then you can use it like this:</p>
<code>
require Result;
sub complex_function {
# ...
if ($error_message)
{
return Result->new(undef, $error_message);
}
return Result->new(1);
}
</code>
<p>With this, the caller wouldn't change much at all:</p>
<code>
unless (my $r = complex_function())
{
print "Error received: $r\n";
}
</code>
<p>Hope that helps. (Completely untested ;->) Also, the way it is now, Result is not a class you can easily derive from ... I leave that as an excersise for other monks ;-></p>
423402
423422