Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the alternative to structs in perl?

Tags:

perl

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?

like image 738
Laz Avatar asked Jun 25 '12 08:06

Laz


People also ask

Does Perl have structs?

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.

Can we use class instead of struct?

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.


3 Answers

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.

like image 76
timos Avatar answered Sep 24 '22 07:09

timos


If you have existing C header files with structs, use Convert::Binary::C to access data structures based on them.

like image 40
daxim Avatar answered Sep 21 '22 07:09

daxim


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.

like image 22
Paul Avatar answered Sep 21 '22 07:09

Paul