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

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/

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

    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.

Re^4: Hashes and keys...
by davidrw (Prior) on Jun 28, 2005 at 12:10 UTC
    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', @_ }; }