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

Ive stumbled upon a problem that im having a tough time finding a solution on, and thats storing key/value pair in a hash. I have a standard $text variable that im appending text to. I double checked and when i print out $text it does indeed store the correct information. However, when try this : %descHash = (%descHash,$file, $text); and then try to print out the contents of %descHash, i get the $file being stored correctly, but the $text comes out with a number between 1 and 4.

I must note that the variable $text changes throughout the program,(not through the hash though) so im not sure if the hash is storing $text as a reference or the actual value is being stored, but it dosnt make sense to me. If anyone knows whats going on, please help! here is my output:
Key = oleochemicals-index.html Value = 1 Key = pilot-index.html Value += 1 Key = news.html Value = 4 Key = deodorizing.html Value = 1 Key = +profile.html Value = 2 Key = refining.html Value = 1 Key = products.h +tml Value = 3 Key = profile-index.html Value = 2 Key = extraction-ind +ex.html Value = 1 Key = refining-index.html Value = 1 Key = index.htm +l Value = 2 Key = products-index.html Value = 3 Key = preparation-ind +ex.html Value = 1 Key = dryer-index.html

Replies are listed 'Best First'.
Re: Question about hashes
by fglock (Vicar) on Jul 31, 2003 at 20:12 UTC

    I think this is all you need:

    $descHash{ $file }  = $text;

    The previous keys/values are preserved - you don't have to add them again each time.

    This will help you to find out what's up with $text:

    print $text;
Re: Question about hashes
by sgifford (Prior) on Jul 31, 2003 at 21:09 UTC
    The code you have is correct, although fglock gives you a simpler and more idiomatic way to do it.
    #!/usr/bin/perl -w use strict; my %h = (1 => "one", 2 => "two"); %h = (%h, 3, "three"); %h = (%h, 4, "four"); print "h is:\n",printhash(%h); sub printhash { my $i = 0; join("",map { $_.($i++%2?"\n":" => ") } @_); }
    produces
    h is:
    1 => one
    2 => two
    3 => three
    4 => four
    

    Consider using debugging information to see if your error is elsewhere---for example, printing out the contents of $file and $text whenever you add to the hash.

Re: Question about hashes
by cianoz (Friar) on Aug 01, 2003 at 09:27 UTC
    $text is stored "as is" and if it was a reference you would see something like SCALAR(0x8105cd4) instead
    try to print out $text just before assignig it to %descHash.