in reply to query on hash understanding

The $hash{key} = $value || 0 construct avoids a value of undefined. It is like setting a default value, or if you are familiar with SQl, like the NVL() function. If you are going to test the value of a variable later in the program, and the value might be undefined, this is used to avoid "Use of uninitialized value" warnings.

use strict; use warnings; my (%hash, $value); print "Without\n"; $hash{key} = $value; if ($hash{key} == 42) { print "taking appropriate action\n" } print "With\n"; $hash{key} = $value || 0; if ($hash{key} == 42) { print "taking appropriate action\n" }

Output:

/wlsedi/howard$: perl pm.pl Without Use of uninitialized value in numeric eq (==) at pm.pl line 10. With /wlsedi/howard$:
1 Peter 4:10

Replies are listed 'Best First'.
Re^2: query on hash understanding
by Athanasius (Archbishop) on Sep 24, 2014 at 15:37 UTC

    This is an excellent point, but note that where the intent is to avoid an undefined value, the defined-or operator // is a better choice than the logical-or operator ||, because:

    1. It will not override a false value (such as the empty string) in an already-defined variable.
    2. It makes the intention of the code clearer.

    Hope that’s of interest,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,