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

Here's a question..

under strict I have to compare a variable which SOMETIMES is undefined. I need to assign the number 1 to it IF it is undefined, but should it already have a value, do nothing.

use warnings; use strict; my $num; if ($num < 0) { $num = 1; } print $num;
As expected, you get the use of uninitialized warning error.

I swear once, many years ago, someone showed me something similar to $var || $var = 1; that did just what I needed. I can't seem to remember exactly what it was.

Any help would be appreciated

Replies are listed 'Best First'.
Re: Checking the value of an undefined value
by kyle (Abbot) on May 10, 2008 at 02:43 UTC

    You're looking for defined. Examples:

    defined $num or $num = 1; $num = 1 if ! defined $num;

    In Perl 5.10, there's a // operator for testing if something is defined.

    $num // $num = 1; $num //= 1;
Re: Checking the value of an undefined value
by pc88mxer (Vicar) on May 10, 2008 at 05:48 UTC
    I swear once, many years ago, someone showed me something similar to $var || $var = 1;
    Probably what they showed you was: $var ||= 1; which sets $var to 1 unless it evaluates to true.

    Note this is not the same as perl 5.10's // operator since the assignment will take place if $var is 0 or the empty string in addition to undef.

Re: Checking the value of an undefined value
by Your Mother (Archbishop) on May 10, 2008 at 04:44 UTC

    And there's also

    use warnings; no warnings "uninitialized";

    Though not always a good idea, in cases where you know what to expect and what's going on it can be much nicer than 700 if defined checks in a script.

Re: Checking the value of an undefined value
by Anonymous Monk on May 10, 2008 at 14:55 UTC
    just use this: my $n; .... $n = $n || 1;
Re: Checking the value of an undefined value
by chrism01 (Friar) on May 12, 2008 at 05:01 UTC
    $num = defined($num) ? $num : 1;