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

I struggled with some Perl that uses hash links.

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

$myhash{$key} |= {};

That is, "give $ myhash {$ key} a link to an empty hash if it doesn’t matter anymore."

The dereferencing of this and an attempt to use it as a hash link, however, led to interpreter errors about using the string as a hash link.

Change it to:

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

... did the job.

Therefore, I have no problem. But I wonder what is going on.

Can anyone explain?

+3
source share
4 answers

, -, , . |= " ". ,

  $foo |= $bar;

  $foo = $foo | $bar

, , - , -ORed $myhash{$key}. , $myhash{$key} undefined , -, HASH(0x80fc284). , , -, . Data::Dumper:

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

, :

  perl -MData::Dumper -le '$hash{foo} ||= { }; print Dumper \%hash'
  $VAR1 = {
            'foo' => {}
          };
+15

Perl . ||= - Perl, . , |=, ||=, .

Perl 5.10 //=. // , , false.

+16

, "|=" ( ) "||=" (, false).

, . , "$myhash{$key} ||= {}" , false -, . , , .

+4

:

my %myhash;
$myhash{$key} ||= {};

You cannot declare a hash element in a sentence my, as far as I know. First you declare a hash, then add an element.

Edit: I see you pulled out my. How about trying ||=instead |=? The first is idiomatic for lazy initialization.

+2
source

Source: https://habr.com/ru/post/1697745/


All Articles