[Purdue-pm] Copying Hashrefs - A Better Way?

Rick Westerman westerman at purdue.edu
Mon Mar 1 09:12:15 PST 2010


David Jacoby wrote:
> I want to copy a hashref. Well, I want to copy the hash reffed, not 
> the pointer. This is not it.
>
>     my $href_1 ;
>     $href->{x} = 8 ;
>     my $href_2 = $href_1 ;
>
> You just get a pointer to the old hash, not a new hash. I want to copy 
> the anonymous hash that $href_1 is referring to.
>
>     my $href_1 ;
>     my $href_2 ;
>     $href->{x} = 8 ;
>
>     %$href_2 =  map { $_ } %$href_1 ;
>
> Yes, this works. But is there a better way?
>
I'd say no.   Although you can drop the 'map' part.  But I believe the 
normal hash copy uses 'map' internally so leaving it in does not really 
matter. 

Basically you are creating a new hash in memory.    In long form -- to 
emphasize the point -- what you are doing is (where %h1 and %h2 are 
actual memory-using hashes) is basically:

(created elsewhere):  %h1

my $href_1 = \%h1;

my %h2;
my $href_2 = \%h2 ;

If you were just working with hashes instead of hash references you 
would do a:

%h2 = %h1 ;

With references the syntax is not any different

%h2 = %$href_1 ;

or

%$href_2 = %$href_1 ;


Of course one then should ask, why do I need a complete copy of a hash?  
There may be good reason.  Or perhaps better is to use 'grep' (akin to 
'map') to filter the data from the old hash into the new hash.


-- 
Rick Westerman westerman at purdue.edu Bioinformatics specialist at the 
Genomics Facility. Phone: (765) 494-0505 FAX: (765) 496-7255 Department 
of Horticulture and Landscape Architecture 625 Agriculture Mall Drive 
West Lafayette, IN 47907-2010 Physically located in room S049, WSLR 
building


More information about the Purdue-pm mailing list