Perl doesn't have the concept of struct by default. We need to Import Struct Class. I was wondering why is this so? and What combination of basic data structures provided by the language is supposed to compensate for this?
Class::Struct exports a single function, struct . Given a list of element names and types, and optionally a class name, struct creates a Perl 5 class that implements a "struct-like" data structure. The new class is given a constructor method, new , for creating struct objects.
Class instances each have an identity and are passed by reference, while structs are handled and mutated as values. Basically, if we want all of the changes that are made to a given object to be applied the same instance, then we should use a class — otherwise a struct will most likely be a more appropriate choice.
Hashes do pretty much the same thing in Perl as structs do in C (in terms of what you use them for). You can also nest hashes to build more complex data structures.
If you have existing C header files with structs, use Convert::Binary::C to access data structures based on them.
Class::Struct never fit the role of C structs for me. In my mind, a C struct is a known memory structure that organizes data, but it's best use for me was always the automatic parsing of fixed length input records into fields just by writing them to the struct.
You can do something similar with unpack. It still requires a separate parsing call C doesn't, but if you build it into your record read, it's pretty efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With