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

Hi Monks.i have two problems with hashes.i have two hashes each of them contains an array for each key.i have two number in each array.i want to compare keys in these two hashes and if keys where equal do some function on numbers in array and i am not sure that in array for each key order of numbers will change or not,i mean hash will save the arrays as i give or not.

%genome1=(a=>(10,15), b=>(3,7), c=>(9,14)); %genome2=(d=>(3,21), a=>(3,4), g=>(5,10), b=>(2,7));

in above hashes i want to calculate for a and b that are similar in two hashes.thank you for your help.

Replies are listed 'Best First'.
Re: array in hashes
by ikegami (Patriarch) on Jul 29, 2011 at 08:25 UTC

    i have two hashes each of them contains an array for each key

    No you don't.

    First, there are no arrays anywhere in that code. Just lots of meaningless parens.

    Secondly, hash values must be scalars, and arrays aren't scalars. You could store a reference to an array in a hash value, though.

    my %genome1 = ( a => [ 10, 15 ], b => [ 3, 7 ], c => [ 9, 14 ], ); my %genome2 = ( d => [ 3, 21 ], a => [ 3, 4 ], g => [ 5, 10 ], b => [ 2, 7 ], ); for (keys(%genome1)) { if ($genome2{$_}) { print("Both genomes have key $_\n"); } }

      i am sorry,i am new in perl.i got it,but if i wrote the following code ,because i need the values for each key, error is about arrays.i haven't gotten this!

      #!/usr/bin/perl -w use strict; my %genome1 = ( a => [ 10, 15 ], b => [ 3, 7 ], c => [ 9, 14 ], ); my %genome2 = ( d => [ 3, 21 ], a => [ 3, 4 ], g => [ 5, 10 ], b => [ 2, 7 ], ); for (keys(%genome1)) { if ($genome2{$_}) { print("$genome1{$_} and $genome2{$_}\n"); } }

        That code doesn't throw any errors. It might not give the output you want, but then you should at least tell us what output it produced, and what you wanted it to print instead.

        In this case reading perlreftut and applying what you learn there should solve your problem.