Muhammad Saad
Muhammad Saad

Reputation: 13

Give multiple values to a key in perl while hashing

I want to give multiple values to a key and print them. Here is the code, but it replaces the key with a new value.

#!/usr/bin/perl
%coins = ( 
    "Quarter" , 25,
    "Dime" , 10,
    "Quarter", 5 
);
foreach $value (sort { $coins{$a} <=> $coins{$b} } keys %coins) {
    print "$value $coins{$value} \n";
}

Upvotes: 0

Views: 261

Answers (3)

vaishali
vaishali

Reputation: 335

You can store the values in array. In hash assign its reference. So whenever you push a value to the array, it will be accessible in hash also. If you gave anonymous array you have to manually assign a value every time. For example:

@array_value=(1);
%hash=('number' => \@array_value);
push @array_value,3;
print "@{$hash{'number'}}";

Whenever you want to add the value in hash you can add it in array "@array_value". you can dereference the array of values in hash like below @{$hash{'number'}}.

Upvotes: 1

Xavier S.
Xavier S.

Reputation: 1157

it seems legit perl replace value. Because the first field is the key, and the second is the value.

So you have 2 solution to solve your problem:

1. Invert key / value (worst solution)

    #!/usr/bin/perl
    %coins = ( 
        25, "Quarter",
        10, "Dime",
        5, "Quarter"
    );
    foreach $value (sort { $coins{$a} <=> $coins{$b} } keys %coins) {
        print "$value $coins{$value} \n";
    }

With this methoid, you cant have 2 "values" with same "key" ... obvious

2. Hash/Array (better solution)

    #!/usr/bin/perl
    %coins = ( 
        "Quarter" => [25, 5, 15],
        "Dime" => [10]
    );
    foreach $value (keys %coins) {
        my @valueArray=@{$coins{$value}};

        foreach my $index (sort { $a <=> $b } @valueArray) {
            print "$value $index \n";
        }
    }

Combine a array with a hashtable

Upvotes: 1

Quentin
Quentin

Reputation: 943108

A key can't have multiple values. The closest you could get would be to have the value be an arrayref, and have multiple values in that array.

%coins = ( 
    Quarter => [25, 5],
    Dime => [10],
);

Although, for the data you have, it looks like you should reverse the structure:

%coins = ( 
    5 => "Quarter",
    25  => "Quarter", 
    10 => "Dime"
);

Upvotes: 4

Related Questions