Note that you have a two different issues here: has a scalar (either a stand-alone scalar, or a value in an array or hash) has ever been assigned to; or, for hashes in particular, whether a key/value pair has ever been created.
Perl has two keywords that answer these questions: defined and exists, respectively. If you actually want to assign or create those values, a good idiom is to use unless:
$a = "default" unless defined $a; $h{key} = "value" unless exists $h{key};
If you know that valid values do not include the values that perl considers false (undef, empty string, and 0), you can generally just test the value directly. As an added amusement, you can use the ||= operator to "assign unless true":
$a = "default" unless $a; $h{key} ||= "value";
Finally, if you want to extract a value or a default without modifying the original, the tinary arithmetic conditional operator is a nice fit:
my $a_val = defined $a ? $a : "default"; my $h_key_val = exists $h{key} ? $h{key} : "value";
Again, if you know the values are never "false" in the perl sense, you can dispense with the specific tests and use the || operator:
my $a_val = $a || "default"; my $h_key_val = $h{key} || "value";
Finally, there is a useful idiom for assigning default values into hashes, overriding only keys that are explicitly mentioned. This takes advantage of the fact that, when assigning into a hash from a list, later key/value pairs overwrite the same key seen earlier:
sub do_stuff { # get args from the call my ( %raw_args ) = @_; # build up hash of default arg values my %default_args = ( foo => 'bar', baz => 'quux' ); # now join the two, giving precedence to %raw_args my %args = ( %default_args, %raw_args ); }
In reply to Re: check for existing value, else set to default
by tkil
in thread check for existing value, else set to default
by nmerriweather
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |