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

Hello Monks, I have two arrays @ar_1 @ar_2 @ar_1 is the list of users and @ar_2 is the list of places visited by each user.Now each user has places visited in common like in @ar_2 cosists of {boston,Ny,Delhi,Paris,boston,cicago,Ny} etc. You see the repetion of cities in @ar_2.This repetion is a value to different user in @ar_1. My question is for a single key from @ar_1, how will you find the keys for that?
  • Comment on Mutiple values for a single ke in hashes

Replies are listed 'Best First'.
Re: Mutiple values for a single ke in hashes
by hipowls (Curate) on Jan 25, 2008 at 11:15 UTC

    You are probably using the wrong data structure and should use a hash of arrays, e.g.

    my %visited_by = ( Peter => [ qw(Sydney Melbourne Perth) ], Paul => [ qw(Shrewsbery Cambridge) ], Mary => [ qw(Paris London Rome) ], ); print "Mary has been to @{ $visited_by{Mary} }\n"; Output Mary has been to Paris London Rome

Re: Mutiple values for a single ke in hashes
by CountZero (Bishop) on Jan 25, 2008 at 11:26 UTC
    It depends on how you have set-up your arrays. If they are like this:
    index @ar_1 @ar2 0 John London 1 Mike Paris 2 Vivien Milan 3 John Berlin 4 Vivien Paris etc...
    Then you would like to end up with a Hash of Array structure as follows:
    John => [London, Berlin], Mike => [Paris], Vivien => [Milan, Paris]
    Which you can do as follows:
    use strict; use Data::Dump qw/dump/; my @ar_1 = qw/John Mike Vivien John Vivien/; my @ar_2 = qw/London Paris Milan Berlin Paris/; my %hash; foreach (0 .. $#ar_1) { push @{$hash{$ar_1[$_]}}, $ar_2[$_]; } print dump(\%hash);

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Mutiple values for a single ke in hashes
by Jasper (Chaplain) on Jan 25, 2008 at 11:59 UTC
    if @ar_1 is a list of users, why not call it @users? That will make it much easier later.

    Similarly for @ar_2 -> @cities.

    Your @ar_2 consists of a reference to a hash with keys of city names, and values of other city names? That seems unlikely to me. What is the real data you have, and what structures have you got it in?

    Your question is horribly unclear, and stinks of homework.