in reply to Re: hash 2 array ?
in thread hash 2 array ?

That would use a lot of memory. If I would need something like:
$hash{$_} = { content => $hash{$_}, position => $i++ } for sort keys % +hash;
I would do it like this:
$hash{$_} = pack( 'N',$i++).$hash{$_} for sort keys %hash;
in other words, prefix the ordinal number packed at the beginning of the string. Then, when you either need the linenumber and/or the original string, use unpack:
my ($line,$string) = unpack( 'Na*',$hash{$key} );
Liz

Replies are listed 'Best First'.
Re: Re: Re: hash 2 array ?
by halley (Prior) on Sep 15, 2003 at 15:44 UTC
    Wouldn't this kill any chance of using leading digits in keys ({ '34' => 'thirty four' })? And take a significant runtime hit to pack and unpack accordingly?

    Tie::IxHash is already done. Does this not serve the purposes required?

    --
    [ e d @ h a l l e y . c c ]

      Eh... I added a packed ordinal number to the value of each hash entry. Doesn't have anything to do with keys. And yes, you will have a runtime hit, but only if you need to sort (when you need the ordinal number) and/or obtain the (real) value of the hash entry.

      Again, my solution optimizes for memory usage. Not CPU. YMMV.

      With regards to Tie::IxHash: that's a fine module, but may be doing (a lot) more than you want. And don't forget the inherit CPU hit for using a tied hash. Finally, TIMTOWTDI. ;-)

      Liz