in reply to Hashes and keys...

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; ... }

Replies are listed 'Best First'.
Re^2: Hashes and keys...
by kaif (Friar) on Jun 28, 2005 at 04:25 UTC

    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/

        Sucking the hash into a ref would be smarter if it were passed as a ref:

        # Call as $obj->foo( { keys => values } ) sub foo { my( $obj, $params ) = @_; # .. }

        but here it is not called like that. Indeed, davidrw's code $params = { @_ } copies the hash, as it must, since it is passed that way.

        Your other idea is good.

        You can just provide the defaults in the my $params = { @_ } declaration (unless as discussed in my parallel post):
        sub foo { my $self = shift; my $params = { param1 => 'default1', param2 => 'default2', @_ }; }
      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.