Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

modifie the first set of keys in a hash

by etricaen (Novice)
on Apr 19, 2016 at 09:29 UTC ( [id://1160863]=perlquestion: print w/replies, xml ) Need Help??

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

hi monks, i have a hash : $hash_sample_cds_genotype{$cds} and i want to modifie all the keys: $cds with  $cds."\t" How i do that ?

Replies are listed 'Best First'.
Re: modifie the first set of keys in a hash
by Corion (Patriarch) on Apr 19, 2016 at 10:34 UTC

    My suggestion is to modify the things on output instead of modifying the things in your data structure. See for example Text::CSV_XS for how to write a (tab-separated) CSV file.

Re: modifie the first set of keys in a hash
by Discipulus (Canon) on Apr 19, 2016 at 09:52 UTC
    probably you means you want modify values, not keys. You can access every key within an hash using keys values using values and both using each

    Modifying one key name in a hash does not make much sense to me and must be done copying the original to a new one and delete the original key, like in:

    $hash{'new_key'} = $hash{'key'}; delete $hash{'key'};

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: modifie the first set of keys in a hash
by davido (Cardinal) on Apr 19, 2016 at 15:24 UTC

    It may be a little unusual to construct hash keys that contain trailing whitespace, but putting that aside the challenge is that hash keys are immutable strings in Perl. Nevertheless, you can do what I think you're asking for like this:

    $hash_sample_cds_genotype{"$_\t"} = delete $hash_sample_cds_genotype{$_} for grep {m/^\Q$cds/} keys %hash_sample_cds_genotype;

    This is assuming that you wish to find all keys that start with a string that looks like $cds, and then append a tab to that key name. Since hash keys are immutable, you pretty much have to remove one element and add it back in under the new key name, which is what this code will do.


    Dave

Re: modifie the first set of keys in a hash
by Anonymous Monk on Apr 19, 2016 at 09:40 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2024-03-28 16:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found