in reply to Re: Simple Query on Operators
in thread Simple Query on Operators

What prompted this was throwing @_ to a hash, like:

my ($self, %args) = @_;

And wanting to allow variables to be optional. The little snippet I posted basically sets a variable to a default if it isn't given in the arguments.

Again, this is a pointless question in that I don't need to answer it. I'm just curious and always try to figure out how a language "thinks" when I pick it up.

Replies are listed 'Best First'.
Re^3: Simple Query on Operators
by apl (Monsignor) on Mar 04, 2008 at 16:15 UTC
    It's far from pointless. A great way of setting a default is: $foo ||= $hash{key};

    That is, if the variable $foo does not already have a value, give it the value of $hash{key}.

Re^3: Simple Query on Operators
by kyle (Abbot) on Mar 04, 2008 at 17:11 UTC

    Another way to do this is with a separate %DEFAULTS hash that gets mixed in with the arguments passed.

    use Data::Dumper; my %DEFAULTS = ( a => 'a default', b => 'b default', c => 'c default', ); my %args = ( a => 'a arg', b => undef, ); %args = ( %DEFAULTS, %args ); print Dumper \%args; __END__ $VAR1 = { 'c' => 'c default', 'a' => 'a arg', 'b' => undef };

    Notice that this method keeps a value that exists but is not defined, so somebody can explicitly pass in undef if they want to. This may or may not be what you want.