Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > How can I pack a hash in a well-defined key order

Reply
Thread Tools

How can I pack a hash in a well-defined key order

 
 
Steve D
Guest
Posts: n/a
 
      08-22-2003
I'd like to create (a lot) of message definitions to be used with Pack
and Unpack. There would be a default, with every key defined "in the
correct order" and replacements would be permitted on the fly.
Something like:

my $messages = {
1 => {
Name => "setip",
Data => {
item => 20,
IP_Addr => "100.100.100.100",
Port => 2000,
} ,
Format => "xNxsxN",
} ,
2 => {
...

and then do something like
### pack data for message $m
my %record = %$messages{$m}{Data} ;
### read in a list of field, value pairs
### assume one line with $field ="IP_Addr" and $value =
"200.200.200.200".
$record{$field} = $value ;
### now pack the code
my $data = pack( $$messages{$m}{Format}, @{[%record]} );
### then transmit the data, nicely packed up

This doesn't work because hash key order is undefined.

The Cookbook 5.6 says to use Tie::IxHash, but I can't get that to work
with a reference to an anonymous hash inside a complex structure (even
if I build the structure with a reference to an empty hash and then
call tie on dereference of that reference and then add elements -- in
fact, in that case I can't seem to even add elements to the
dereferenced hash).

So ... how can I set this up, short of retyping all the elements into
an array that is kept with the hash, e.g.
1 => {
Name => "setip",
Data => {
item => 20,
IP_Addr => "100.100.100.100",
Port => 2000,
} ,
Data_Order => [ 'item', 'IP_Addr', 'Port' ] ; # yuk
Format => "xNxsxN",

Regards,
Steve
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
hash of hash of hash of hash in c++ rp C++ 1 11-10-2011 04:45 PM
hash key to var name of value hash key value Une bévue Ruby 5 08-10-2006 04:05 PM
can I trust on key %hash natural order? filippo Perl Misc 13 06-16-2006 06:01 PM
Hash#values and Hash#keys order Alex Fenton Ruby 1 04-15-2006 05:45 AM



Advertisments