Search code examples
perlinitializationhash-reference

What does `$hash{$key} |= {}` do in Perl?


I was wrestling with some Perl that uses hash references.

In the end it turned out that my problem was the line:

$myhash{$key} |= {};

That is, "assign $myhash{$key} a reference to an empty hash, unless it already has a value".

Dereferencing this and trying to use it as a hash reference, however, resulted in interpreter errors about using a string as a hash reference.

Changing it to:

if( ! exists $myhash{$key}) {
  $myhash{$key} = {};
}

... made things work.

So I don't have a problem. But I'm curious about what was going on.

Can anyone explain?


Solution

  • Perl has shorthand assignment operators. The ||= operator is often used to set default values for variables due to Perl's feature of having logical operators return the last value evaluated. The problem is that you used |= which is a bitwise or instead of ||= which is a logical or.

    As of Perl 5.10 it's better to use //= instead. // is the logical defined-or operator and doesn't fail in the corner case where the current value is defined but false.