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

I'm writing a sub that checks values of a hash, %foo
I'm only interested in seeing existing values, not creating new ones, so the sub works something like this :
sub check_foo { if (exists $foo{bar}) {return $foo{bar}} else {return $the_mysterious_errorcode} }
my problem is that $foo{bar} may contain undef as a value, as well as a large array of text & etc.. What can $the_mysterious_errorcode be set to so that I can differentiate between a nonexistant $foo{bar} and one that's undef?
Is it acceptable to set $! in a situation like this?

Replies are listed 'Best First'.
Re: detecting errors when a sub returns undef
by jeroenes (Priest) on May 01, 2001 at 10:54 UTC
    I would return a reference to the scalar rather than the value. Than it always is either a ref or undef.

    Jeroen

Re: detecting errors when a sub returns undef
by Rhandom (Curate) on May 01, 2001 at 11:05 UTC
    Something that is quick and light and clean...
    sub check_foo { if (exists $foo{bar}) { return $foo{bar}; }else{ die "CODE[$the_mysterious_errorcode]\n"; } } # instead of my $value = check_foo(); my $value = eval { check_foo() }; ### see if there was an error if( $@ ){ if( $@ =~ /CODE\[(.+)\]/ ){ my $code = $1; } } ### if no problem with eval, $value is set to $foo{bar}


    All this is, is try and catch (but it works and is fairly clean, and it makes sure if somebody calls your sub, they have to know what to do with the return).

    my @a=qw(random brilliant braindead); print $a[rand(@a)];
(tye)Re: detecting errors when a sub returns undef
by tye (Sage) on May 01, 2001 at 19:18 UTC

    Well, lots of ways spring to mind. I prefer to think about such problems in terms of how the caller will have to deal with things. I was going to list several examples but once I hit this one I threw the other ones away:

    if( ! check_foo("foo",\$foo) ) ) { warn "No foo present\n"; } else { do_stuff( $foo ); }

            - tye (but my friends call me "Tye")
Re: detecting errors when a sub returns undef
by converter (Priest) on May 01, 2001 at 18:51 UTC
    Perhaps a silly question, but why not just omit keys with undefined values from the hash in the first place?

    If you can't omit keys with undefined values, change your code to:

    sub check_foo { if (exists $foo{bar} and $foo{bar}) return $foo{bar}; } else { return undef; } }