in reply to logical-assignment operators

When you have an operator paired with an =, that can usually be translated to an easier to understand version. Your examples could be written as:

$v ||= $w --> $v = $v || $w $x &&= &y --> $x = $x && $y $v |= $w --> $v = $v | $w $x &= $y --> $x = $x & $y

The first set of examples are logical and, and logical or. The or example checks if $v is true, if it is, $v is set to itself, OR it is set to $w. The and example is a little more confusing and I'm not really sure why you would want to use it. If $x is 0, it remains 0, otherwise it is set to $y.

The second set of examples is bitwise and, and bitwise or.

You can look up more information about these operators in perlop

Replies are listed 'Best First'.
Re^2: logical-assignment operators
by Marshall (Canon) on Mar 27, 2009 at 19:40 UTC
    Here is yet another way to use ||=.
    $cache{$a} ||= expensive_sub($a);

    Here we have an expensive operation on $a, and we want to save the result so that if $a is seen again, we already have the answer from expensive_sub().

Re^2: logical-assignment operators
by gwadej (Chaplain) on Mar 27, 2009 at 19:15 UTC

    Having recently run into a really good use for &&= this comment caught my eye. How about:

    $value &&= 'prefix-' . uc $value;

    translated as "$value contains a string, uppercase it and prepend the prefix."

    In my particular circumstance, '0' was not going to happen but either undef or the empty string were possible. Those cases were filtered out in later processing.

    G. Wade
Re^2: logical-assignment operators
by Marshall (Canon) on Mar 27, 2009 at 19:24 UTC
    Here is one example of where ||= is useful... If this regex doesn't match then $license_class is undefined. Instead of some kind of "if" code that does something "if (!defined ...)", this just sets the default case "BAD_CLASS" if that happens.
    my $license_class = ($raw_html =~ m|Class:</td><td class="di">(\w+?) |)[0]; $license_class ||= "BAD_CLASS";