develooper Front page | perl.beginners | Postings from August 2009

Re: ||= operator

Thread Previous
From:
Chas. Owens
Date:
August 14, 2009 16:04
Subject:
Re: ||= operator
Message ID:
58ce48dc0908141604h2ddf73f0wa54c59b0475ee795@mail.gmail.com
On Fri, Aug 14, 2009 at 18:00, Noah Garrett
Wallach<noah-list@enabled.com> wrote:
snip
> we all found that in the docs.   based on the information you posted. what
> does "||="  do?
snip

$x ||= $y;

is the same as

$x = $x || $y;

and that performs a logical or operation that returns $x if $x is true
or $y if $x is false.  This means it is roughly equivalent to:

if ($x) {
    $x = $x;
} else {
    $x = $y;
}

It is often used to create default values:

#!/usr/bin/perl

use strict;
use warnings;
#!/usr/bin/perl

sub foo {
    my ($x, $y, $z) = @_;
    $x ||= 5;
    $y ||= 10;
    $z ||= 55;
    print "x $x y $y z $z\n";
}

foo();        #all defaults
foo(1);       #x set to 1, rest defaults
foo(1, 2);    #x set to 1, y set to 2, z is default
foo(1, 2, 3); #x set to 1, y set to 2, z set to 3

This has problems though.  If you can't set $x to 0 (since it is
false).  In Perl 5.10, we have a new operator // and a corresponding
assignment operator //=.  // tests $x for definededness rather than
for truth, so

$x //= 5;

is roughly equivalent to

if (defined $x) {
    $x = $x;
} else {
    $x = 5;
}


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About