On Fri, Aug 14, 2009 at 18:00, Noah Garrett
Wallach<noah-l...@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.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to