From "perldoc perlvar" on the $! variable:
If used numerically, yields the current value of
the C "errno" variable, with all the usual
caveats. (This means that you shouldn't depend on
the value of "$!" to be anything in particular
unless you've gotten a specific error return
indicating a system error.) If used an a string,
yields the corresponding system error string. You
can assign a number to "$!" to set errno if, for
instance, you want ""$!"" to return the string for
error n, or you want to set the exit value for the
die() operator.
The emphasis is mine, but I left it in context so you could see what's happening here. $! is a special variabl that returns slightly different information depending upon the context. Further, though not stated explicitly, you cannot assign a string to it.
Now, regarding your code: it can't be OO because the object must be a reference to something (see "perldoc -f bless" for more information. However, I'll assume for the moment that you know that and just wrote $self ne 'hm' for testing. The real point that I wanted to get to is that if you're going to use OO code, you should provide OO methods for dealing with errors:
package Foo;
use strict;
sub new {
my $class = shift;
bless {
_errno => 0,
_errmsg => '',
_foo => undef
}, $class;
}
sub set_foo {
my ( $self, $foo ) = @_;
if ( $foo <= 0 ) {
@{$self->{qw/_errno _errmsg/}} = ( 1, 'foo must be positive' );
return;
}
else {
$self->{_foo} = $foo;
return 1;
}
}
sub error { $_[0]->{_errno} }
sub errmsg { $_[0]->{_errmsg} }
With the above (untested) code, the object keeps track of errors internally. Then, you can just do something like this:
use Foo;
my $thing = Foo->new;
my $success = $thing->set_foo( -2 );
if ( $success ) {
# do something
}
else {
# you can also do if ( $thing->error ) {
die $thing->errmsg;
}
There are many different ways to handle that, but I think you get the idea. Good luck!
Cheers,
Ovid
Update: I changed the error return to a blank return (i.e., return nothing). I had it set to "return 0", but if returned into an array, this will cause the array to evaluate as true. Whoops! :)
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. |