in reply to Filling a hash

Considerations in random order.
The function 'push' is not allowed.
This is a strange requirement for two reasons: first , because we should be free of using push wherever we think it's good to; second, how I can add an element to a hash using the push function in an intuitive way? Nothing comes to my mind.
Then each hash is printed to the screen.
Either your teacher missed something, or you failed to copy the input of your homework. I thought we were talking about one hash, not many. Anyway, if you want to print hash contents you could find Data::Dumper interesting.

Flavio
perl -ple'$_=reverse' <<<ti.xittelop@oivalf

Don't fool yourself.

Replies are listed 'Best First'.
Re^2: Filling a hash
by Tanktalus (Canon) on Oct 26, 2005 at 14:18 UTC

    Actually, I use push to put items in a hash all the time. Of course, it's because I want a HoA so I can detect and deal with duplicates. One of the places I use this I then go through the HoA at the end, verify that all arrays have a single member, and then convert from HoA to straight H. I suppose I could do something like this:

    @h{keys %h} = map { $_->[0] } values %h;
    but I think I do this in a slightly longer piece of code.

    In another location, I keep the arrays - I need to keep duplicate entries. Think of an XML file - each element can have multiple subelements. In my case, order between elements of different names doesn't matter, so I can put each name into a hash, and have an array of elements that all have that name as a child of the current element. (Does that even make sense?)

    So, yes, I use push to populate hashes. It's not the usual way, but it's not uncommon.

    (All actual examples of how I do it are removed so as not to give the OP any silly ideas to cut&paste...)

      Uh, I was thinking about pushing both key and values, but yes, your solution is a viable one using push.
      All actual examples of how I do it are removed so as not to give the OP any silly ideas to cut&paste...
      Given the fact that the OP cannot use push, an example would be safe here :)

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.
Re^2: Filling a hash
by Fletch (Bishop) on Oct 26, 2005 at 13:44 UTC
    how I can add an element to a hash using the push function in an intuitive way

    One could push the key value pairs onto an array and then construct a hash from that array (but that's just wonky, even for homework).

      Something like:
      { my @ary = %hash; push @ary, $k => $v; %hash = @ary; }
      I suppose. But it doesn't seem much natural :) I only wondered why the teacher had to specify this strange requirement.

      Update: corrected bug in snippet, thanks to QM

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.