Zii
Zii

Reputation: 359

What is ||=[] in perl?

What does below array @{$violated{$desc}||=[]} mean in below subroutine? I understand @{$violated{$desc}} is the anonymous array referenced by $violated{$desc}, though.

sub not_in_file_ok {
    my ($filename, %regex) = @_;
    open( my $fh, '<', $filename ) or die "couldn't open $filename for reading: $!";
    my %violated;
    while (my $line = <$fh>) {
        while (my ($desc, $regex) = each %regex) {
            if ($line =~ $regex) {
                push @{$violated{$desc}||=[]}, $.;
            }
        }
    }
    if (%violated) {
    fail("$filename contains boilerplate text");
    diag "$_ appears on lines @{$violated{$_}}" for keys %violated;
    } else {
    pass("$filename contains no boilerplate text");
    }
}

Upvotes: 3

Views: 356

Answers (3)

hobbs
hobbs

Reputation: 240819

It's a compound assignment operator; it assigns [] (a reference to a new empty array) to $violated{$desc} if it contains a false value (i.e. if it hasn't been initialized yet).

It's also completely unnecessary, because Perl does that automatically anyway. The same code with ||=[] removed does the same thing, more clearly.

However, there are times when it actually does make sense to do something like this, so it's worth keeping the pattern in mind.

Upvotes: 9

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18865

Logical or with assignment. It takes left operand, and right operand, performs left || right and assigns it back to left.

Check perl assignment operators

Upvotes: 2

Amadan
Amadan

Reputation: 198566

$x ||= [] is pretty much equivalent to $x = $x || [], which is, in turn, almost equivalent to $x = $x ? $x : []. In other words, if $x is falsy, it will make it an empty array reference; otherwise, it will leave it alone.

Upvotes: 7

Related Questions