|Come for the quick hacks, stay for the epiphanies.|
Re^5: Improve readability of Perl code. Naming reference variables.by TGI (Parson)
|on Jan 26, 2017 at 08:25 UTC||Need Help??|
This is a nice example of why the way I learned to write subs makes me happy. I'm sharing it with you, so you can join in the fun.
This code is nice because it is very explicit. It shows you exactly what it expects. It doesn't really rely on any weirdness.
So we start off by passing in a single hashref with a set of named arguments. Extra arguments are sucked up by the @bad variable.
We then unpack the options hashref into variables, deleting keys as we go. This ensures that the hash will be empty when all known arguments have been unpacked. This is a handy place to set default values for options.
Finally we call our check function. We pass in @bad and %opt by reference, to ensure that they are empty. Other arguments are handled by passing in key/value pairs. This version croaks when a false value is found for any key.
Yes this code is a bit verbose. But it is easy to read, very regular and can contain a lot of information. Including what type each variable/argument is.
It's also worth thanking tye who wrote the original version of this check function I recalled for you. Any errors in its operation as embodied here are solely mine. The real thing actually works.