Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 404
slim Avatar asked Nov 28 '22 01:11

slim


1 Answers

The reason you're seeing an error about using a string as a hash reference is because you're using the wrong operator. |= means "bitwise-or-assign." In other words,

  $foo |= $bar;

is the same as

  $foo = $foo | $bar

What's happening in your example is that your new anonymous hash reference is getting stringified, then bitwise-ORed with the value of $myhash{$key}. To confuse matters further, if $myhash{$key} is undefined at the time, the value is the simple stringification of the hash reference, which looks like HASH(0x80fc284). So if you do a cursory inspection of the structure, it may look like a hash reference, but it's not. Here's some useful output via Data::Dumper:

   perl -MData::Dumper -le '$hash{foo} |= { }; print Dumper \%hash'
   $VAR1 = {
             'foo' => 'HASH(0x80fc284)'
           };

And here's what you get when you use the correct operator:

  perl -MData::Dumper -le '$hash{foo} ||= { }; print Dumper \%hash'
  $VAR1 = {
            'foo' => {}
          };
like image 114
friedo Avatar answered Dec 05 '22 09:12

friedo