Perl hashref / perl syntax

A variant of this code passed today (written by a perl encoder) and it confuses:

my $k = {3,5,6,8}; my $y = {%$k}; 

Why? What does it do? This is similar to the following:

  my $y = $k; 

The context is in a call using the dbi module:

  while (my $x = $db->fetchrow_hashref ) { $y{something} = {%$x}; } 
+4
source share
2 answers

The difference is that it clones the data structure without reference to the same memory.

For instance:

 use strict; use warnings; use Data::Dumper; my $h={'a'=>1,'b'=>2}; my $exact_copy=$h; #$exact_copy references the same memory as $h $h->{b}++; #$h maps b to 3 print Dumper($exact_copy) . "\n"; #a=>1,b=>3 my $clone={%$h}; #We dereference $h and then make a new reference $h->{a}++; #h now maps a to 2 print Dumper($clone) . "\n"; #a=>1,b=>3 so this clone doesn't shadow $h 

By the way, manually initializing a hash using all commas (as in my $k = {3,5,6,8} ) is very, very ugly.

+8
source

{ } , in this case, is a hash constructor. It creates a new hash and returns a link to it. So

Comparison

 my $k = { a => 4 }; my $y = $k; $k->{a} = 5; print $y->{a}; # 5 

from

 my $k = { a => 4 }; my $y = { %$k }; $k->{a} = 5; print $y->{a}; # 4 
0
source

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


All Articles