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

Hi monks, I am having some hash trouble. I basically want to print out key-value pairs from the hash, but it seems to think there is only one key-value pair which hold all the key-values.!? Anyway, can anyone solve this? Any help much appreciated. ;->
# @pair contains all the keys. my @pair = $pair; my @value = $value; %hash = map {$pair[$_] => $value[$_]} 0..$#pair; while (($key, $value) = each (%hash)) { if ($key eq 'TG') { $TG_score = $value; } print "The value of $key is:$value"; }
The output is
The value of TG AT CG is: 3 2 2
I want it to be;
The value of TG is:3
etc

Replies are listed 'Best First'.
Re: hashes - treating all keys/ values as one
by tachyon (Chancellor) on Feb 27, 2003 at 12:24 UTC

    You need to set @pair and @value to lists rather than scalars. You can use a hash slice rather than map as shown.

    my @pairs = qw( A B C D ); my @vals = 1..4; my @hash{@pairs} = @vals; while ( my($key,$val) = each %hash ) { print "$key:$val\n"; }

    It looks like you have newline separated data in $pair so you could

    my @pairs = split "\n", $pair;
    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: hashes - treating all keys/ values as one
by Abigail-II (Bishop) on Feb 27, 2003 at 12:22 UTC
    Both @pair and @value contain a single element. So, %hash contains just one key/value pair.

    Abigail

Re: hashes - treating all keys/ values as one
by hardburn (Abbot) on Feb 27, 2003 at 15:06 UTC

    The easy way:

    use Data::Dumper; print Data::Dumper->Dumper(\%hash);

    ----
    Reinvent a rounder wheel.

    Note: All code is untested, unless otherwise stated

Re: hashes - treating all keys/ values as one
by OM_Zen (Scribe) on Feb 27, 2003 at 15:48 UTC
    Hi ,

    The @pair and @value contain scalars and not list of values .

    May be if the $pair ,the $value you have are references then you should dereference it to get the arrays first and then start the hash creation and accessing the elements
    use strict; my @pair; my @values; my $pairs; my $value; # if the $pair and $value you mentioned # are references then dereference it with # the statements here : @pair = @$pairs; @values = @$value ; my @hashofarrays{@pair} = @values; foreach (my ($Key , $Value) = each %hashofarrays){ print "$Key , $Value\n"; }