in reply to Re: Hashes and keys...
in thread Hashes and keys...

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.)

Replies are listed 'Best First'.
Re^3: Hashes and keys...
by holli (Abbot) on Jun 28, 2005 at 06:51 UTC
    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', @_ }; }
Re^3: Hashes and keys...
by davidrw (Prior) on Jun 28, 2005 at 12:06 UTC
    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.