Sam Adamsh
Sam Adamsh

Reputation: 3391

perl hashref/ perl syntax

A variation of this code passed by today (written by a perl coder), and it is confusing:

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

Why? What does that do? That seems to be the same thing as this:

   my $y = $k;

The context is in a call using dbi module:

               while (my $x = $db->fetchrow_hashref )
               {  $y{something} = {%$x};  }

Upvotes: 4

Views: 343

Answers (2)

user554546
user554546

Reputation:

The difference is that it's cloning the data structure without referencing the same memory.

For example:

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

Incidentally, manually initialising a hash by using all commas (as in my $k = {3,5,6,8}) is very, very ugly.

Upvotes: 8

ikegami
ikegami

Reputation: 385546

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

Compare

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

with

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

Upvotes: 0

Related Questions