Find the answer to your Linux question:
Results 1 to 4 of 4
I have already assigned values to a hash but now again I need to assign values in same hash for the same keys. but old values should remain there. And ...
  1. #1
    Linux Newbie
    Join Date
    Jan 2008
    Posts
    114

    How can I assign two values for a Key in hash Perl

    I have already assigned values to a hash but now again I need to assign values in same hash for the same keys. but old values should remain there.

    And at last I want to access/print both values using that single key

    Please help!!

  2. #2
    Linux Guru coopstah13's Avatar
    Join Date
    Nov 2007
    Location
    NH, USA
    Posts
    3,149
    a key in a hash table can only map to one value, thats how a hash table works

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    A hash key can only map to a single scalar, this is true. However, by using arrayrefs, you can get around this. I assume you know about arrayrefs. See the below code for an example of what I mean:
    Code:
    alex@danu ~/test/perl $ cat arrayrefs_in_hash 
    #!/usr/bin/perl
    
    use strict;
    
    my %hash;
    
    for(qw/a b c/)
    {
        push @{$hash{'key'}}, $_;
    }
    
    for (@{$hash{'key'}})
    {
        print "$_\n";
    }
    alex@danu ~/test/perl $ ./arrayrefs_in_hash 
    a
    b
    c
    I make $hash{'key'} point to an arrayref, so I can push, loop, and all the normal array operations on it.
    DISTRO=Arch
    Registered Linux User #388732

  4. #4
    Linux Enthusiast apoorv_khurasia's Avatar
    Join Date
    Feb 2005
    Location
    Laurasia
    Posts
    624
    The values should be a list with elements as what your are using as values now.
    "There is no sixth rule"
    --Rob Pike
    Registered Linux User: 400426 home page

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...