Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

check for existing value, else set to default

by nmerriweather (Friar)
on Apr 26, 2004 at 04:51 UTC ( [id://348078]=perlquestion: print w/replies, xml ) Need Help??

nmerriweather has asked for the wisdom of the Perl Monks concerning the following question:

this is a style question, i guess. I'd love to know of better ways to do the following:
$a = 'text'; $b = $a ? $a : ''; $c = $a->{KEY} ? \$a->{KEY} : 0;
basically, I just want to see if a variable is assigned a value and, if so, keep that value. if not, i'd like to set it to a default value (in case $b, an empty string). In case $c, i'm checking a key in an object, and returning a ref if it exists. I'm wondering if there's another way to write that, or approach that, that is more efficient/clean/better regarded.. i was wondering if there were something like - so i could save typing for the repeat of the var when the names are long
$abcdefghijklmnopqrstuvwxyz = 'text'; $d = $abcdefghijklmnopqrstuvwxyz ? $_ : 0;

Replies are listed 'Best First'.
Re: check for existing value, else set to default
by saintmike (Vicar) on Apr 26, 2004 at 06:08 UTC
    Checking if a scalar has a defined value (and assigning a default value if it hasn't) is quite common. Unfortunately, the constructs
    $a = $a ? $a : "default_value";
    or
    $a ||= "default_value";
    don't work if the value of $a is something that returns false in a boolean context, like 0 or "". For now,
    $a = defined $a ? $a : "default_value";
    is the best way to write this, and since it's such a common idiom, Perl 6 will allow you to say
    $a //= "default_value";
    whenever Perl6 will come out.
      but its available right now as a patch => defined or: // and //=

      MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
      I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
      ** The third rule of perl club is a statement of fact: pod is sexy.

Re: check for existing value, else set to default
by tkil (Monk) on Apr 26, 2004 at 06:54 UTC

    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 ); }
Re: check for existing value, else set to default
by pbeckingham (Parson) on Apr 26, 2004 at 04:54 UTC

    Is this what you meant? Taken literally, $a has a defined value, and the tertiary operator is unnecessary, so I presume you are looking for a default value kind of operation.

    $a = 'text'; $b = $a || '';
    Your third example is not reducible. At least, not by me.

      $a = 0; $a = $a || "1024"; if ($a == 1024) { print "ack $a = 1024 rm -rf ~\n"; }
      whoops.


      -Waswas
Re: check for existing value, else set to default
by ph0enix (Friar) on Apr 26, 2004 at 10:05 UTC
    $a = defined $a ? $a : 'default;
Re: check for existing value, else set to default
by tinita (Parson) on Apr 26, 2004 at 10:36 UTC
    additionally:
    so i could save typing for the repeat of the var when the names are long
    use a good editor that can do variable name / word extension. like vim.
    =)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://348078]
Approved by davido
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2024-07-20 08:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.