* Ovid <[EMAIL PROTECTED]> [2005-08-12 22:15]:
>   sub foo {
>     my $args = shift;
>     croak $message unless is_deeply [sort keys %$args], [EMAIL PROTECTED];
>     foreach (@default) {
>       $args->{$_} = $some_default unless exists $args->{$_};
>     }
>     croak if extra_keys($args);
>     # do stuff
>   }

I don’t know if this is just a silly example, but I’m not sure it
makes sense… why `die if extra_keys` when you’ve already made
sure that the set of keys can only be exactly @some_keys? Why set
a for all keys *unless* they exist, when you’ve already required
exactly the set of @some_keys to exist? And why use the same
default for all of these?

The code I use for such occasions is

    sub foo {
        my ( $args ) = @_;
        my %default = ( foo => 1, bar => 1, baz => 'quux' );
        my @optional_keys = qw( wibble wobble );
        my %args = ( %default, map {
            exists $args->{ $_ } ? ( $_ => delete $args->{ $_ } ) : ()
        } keys %default, @optional_keys;
        croak "I have no idea what you mean by @{[ keys %$args ]}" if %$args;
        # ...
    }

And I guess that could stand to be encapsulated for

    sub foo {
        my ( $args ) = @_;
        my %args = defaultify_hash(
            $args,
            { foo => 1, bar => 1, baz => 'quux' },
            [ qw( wibble wobble ) ],
            sub { croak "I have no idea what you mean by @_" },
        );
        # ...
    }

But I’d be unlikely to ever depend on a module that provides
nothing but `defaultify_hash` unless it’s in core. Otherwise I’d
just copypaste the function…

But then, the likely candidate is Hash::Util, and if you’re going
to require that, you can already rewrite the code as

    sub foo {
        my ( $args ) = @_;
        my %args = ( foo => 1, bar => 1, baz => 'quux' );
        Hash::Util::lock_keys( %args, keys %args, qw( wibble wobble ) );
        eval { %args = ( %args, $%args ) };
        croak $@ if $@;
        # ...
    }

at which point trying to reuse this little code gets kind of
silly. Thinking about it, this may be how I’ll implement this
henceforth… I don’t like < 5.8.1 anyway because Unicode is too
important to me…

Regards,
-- 
#Aristotle
*AUTOLOAD=*_=sub{s/(.*)::(.*)/print$2,(",$\/"," ")[defined wantarray]/e;$1};
&Just->another->Perl->hacker;

Reply via email to