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

Discussion in 'Perl Misc' started by Steve D, Aug 22, 2003.

  1. Steve D

    Steve D Guest

    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
     
    Steve D, Aug 22, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tim Jones
    Replies:
    0
    Views:
    396
    Tim Jones
    Jan 31, 2004
  2. Oodini
    Replies:
    1
    Views:
    1,795
    Keith Thompson
    Sep 27, 2005
  3. rp
    Replies:
    1
    Views:
    556
    red floyd
    Nov 10, 2011
  4. Une bévue
    Replies:
    5
    Views:
    155
    Une bévue
    Aug 10, 2006
  5. Ralf Baerwaldt
    Replies:
    1
    Views:
    140
    Paul Lalli
    Jul 20, 2004
Loading...

Share This Page