Do you ever find yourself using plain hash references to store little collections of data, always with the same fields, internally in your code? Or maybe you return them to callers to represent little collections of information?
Convenient as these are, they always run the risk that just spelling a key name wrong (or inventing new key names by mistake) doesn't cause an immediate error - either you'll end up reading undef, or worse, you'll create a new field in the structure.
Of course you could create an entire object class for these, but an entire class in its own file just for a few pieces of structural data with no "exciting behaviour" methods seems somewhat overkill.
In this sort of situation when you just have dumb structural data with no other methods you can use Struct::Dumb to represent them.
This helpful little one line of code creates a constructor function which returns objects having all those fields:
Your caller can now read the fields of the struct as if they were methods on an object:
Though just like hash references these fields are updatable. They act as lvalue methods:
However, unlike hash references instances give a helpful error if you try to access a field that doesn't exist:
This makes them just as convenient as plain hash references for internal data inside your modules or classes.
If you want to create structures that cannot be mutated after construction, you can instead use
readonly_struct to declare them:
The constructor function helpfully reminds you of missing fields if you invoked it incorrectly:
Of course, this doesn't help you if you pass the right number of arguments but mix up the order of them:
One thing that can help here is to instead have Struct::Dumb create a constructor that uses named parameters rather than positional arguments - in other words instead of passing in an ordered list of parameters you pass in key/value pairs much more like traditional hash creation. This looks something like this:
It's even possible to enable defaulting to named parameters on a per-package basis:
Under the hood Struct::Dumb uses arrays to store the data. This means that these data structures can be much smaller:
If you're using a vast number of identically keyed hashes then Struct::Dumb can save a significant amount of memory.
In certain situations Struct::Dumb can provide a more strict and smaller alternative to simple hash usage with minimal code overhead. With a pure Perl implementation requiring no dependencies, there's very little reason you shouldn't start using it in your code today.