Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Hash Ref Initialization

by hypochrismutreefuzz (Scribe)
on Dec 10, 2007 at 20:28 UTC ( [id://656215]=perlquestion: print w/replies, xml ) Need Help??

hypochrismutreefuzz has asked for the wisdom of the Perl Monks concerning the following question:

How is the best way to initialize a hash_ref?

my $hash_ref = { hack => slash, frobozz => portrait, candle => lit, }; my @keys = keys %$hash_ref; my $hash_copy = {};

Now say we want $hash_copy to contain a copy of all the information in $hash_ref. Which of these is preferable?

@{ $hash_copy } { @keys } = @{ $hash_ref } { @keys }; $hash_copy->{$_} = $hash_ref->{$_} for @keys;

Replies are listed 'Best First'.
Re: Hash Ref Initialization
by eric256 (Parson) on Dec 10, 2007 at 20:36 UTC

    How about $hash_copy = { %$hash_original }?


    ___________
    Eric Hodges
Re: Hash Ref Initialization
by mwah (Hermit) on Dec 10, 2007 at 20:51 UTC

    simply by 'hash intialization' (%$hash_copy = %$hash_ref):

    use strict; use warnings; my $hash_ref = { hack => 'slash', frobozz => 'portrait', candle => 'lit', }; my $hash_copy; %$hash_copy = %$hash_ref; map $_ .= '_mod', values %$hash_copy; # encouraged in v.5.10 print map "$_ => $hash_ref->{$_} \n", keys %$hash_ref; print map "$_ => $hash_copy->{$_} \n", keys %$hash_copy;

    Regards

    mwa

Re: Hash Ref Initialization
by Roy Johnson (Monsignor) on Dec 10, 2007 at 20:50 UTC
    If your hashref could contain other refs, you might want to look at Clone and/or Data::COW.

    Caution: Contents may have been coded under pressure.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://656215]
Approved by kyle
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-03-29 02:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found