[kw-pm] conditionals and the comma operator
Cees Hek
ceeshek at gmail.com
Mon Jan 5 08:56:25 PST 2009
On Mon, Jan 5, 2009 at 9:39 AM, Robert P. J. Day <rpjday at crashcourse.ca> wrote:
> ah, i remember the idiom that i was thinking of:
>
> $var = $var || new_value;
>
> as in (from my example above):
>
> $vm_output ||= cwd . '/vmlinux'; (the short form)
>
> isn't that the idiom? if the variable is set, it stays set to that
> value. if it's not set, it will be assigned the given value. am i
> remembering that right?
Hi Robert,
That is a very common way of conditionally assigning a variable, but
just make sure that 0 and "" are not valid values.
$a = 0;
$a ||= 1;
That will set the value to 1, since 0 is a false value.
perl 5.10 gives us a new conditional that takes this into
consideration. The defined-or operator //.
$a = 0;
$a //= 1;
It is equivalent to but much more concise than this:
$a = 1 unless defined $a;
Cheers,
Cees
More information about the kw-pm
mailing list