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

I need some wisdom. I have routines where information is compared between data base fields and submited CGI paramiters and need to tell the difference between when a value is submitted as blank and when the parameter wasn't specified within a subroutine. For example I will use the routine 'update_info'. In the the first case the value should be set as blank and in the second it should be ignored and left alone.

$object->update_info(value=>"");

Compared to:

$object->update_info();

I'd like to do it with a small amount of code because there are many possible values to address. Please help me find my way. I've hit a wall on it.

Mark Kenney

Replies are listed 'Best First'.
Re: Hashes and keys...
by davidrw (Prior) on Jun 28, 2005 at 01:58 UTC
    It seems like you want something along these lines, where you suck all the args of the sub into a hashref, so that you can use exists to see if a param was passed in or not.
    sub update_info { my $obj = shift; my $params = { @_ }; my $value = exists $params->{value} ? $params->{value} : undef; ... }

      davidrw, I am sure you meant $params->{value}, but I have two questions (one on personal style): why do you prefer creating a hash reference from an incoming hash (i.e., why not %params = @_?). Also, do you know that my $value = $p->{value} does the same thing as your code? (If the key doesn't exist, the hash lookup returns undef.)

        sucking the hash into ref would safe some speed and memory (because it has not to be copied). You're other point is correct. A simple way to make it "smarter" is
        sub foo { my %defaults = { param1 = 'default1', param2 = 'default2', #etc } my $self = shift; my $params = { @_ }; for ( keys %defaults ) { $params->{$_} = $defaults{$_} unless defined $params->{$_}; } }
        Also there are parameter checking modules out there.
        I can't remember the names but i'm sure someone will mention them.


        holli, /regexed monk/
        Yeah, thanks -- that was a typo -- i updated it. I guess it doesn't have to be a hasref .. mostly out of habit.
        I know that my $value = $params->{value}; does the same thing, but the point was to illustrate to OP that you can use exists $params->{value} to see if the parameter was provided or not. Consider a required param:
        sub foo { my $obj = shift; my $p = { @_ }; my $value = exists $p->{value} ? $p->{value} : die "must give 'value +', even if undef or ''"; if( exists $p->{optional_but_possibly_blank_key} ){ ... }
        Basically, depending on your data/requirements, if( $p->{value}) and if(exists $p->{value}) are not the same.