Recently, I was writing a commandline tool in Perl, one of my favorite things to do. I needed Getopt::Long. I also was being nagged internally to use Util::H2O. Why? I simply wanted "real" accessors for the options hashref that I really like using with GetOptions. I ended up with something like this:
Almost magically, with the addition of a single line (well, 2 if you count the use Util::H2O qw/h2o/; line,) I had accessors for $opts. I was pleased, to say the least. Note, I have not tried this with callbacks, but I also don't use them much. I suspect that works just fine. (update) Also note, in this case one gets accessors only for the options passed (or more precisely for only the keys that exist in $opts). I suspect this could be leveraged for more interesting and perlish ways of checking what options were actually passed.use strict; use warnings; use Getopt::Long qw/GetOptions/; use Util::H2O qw/h2o/; # <~ here my $opts = {}; GetOptions( $opts, qw/ option1=s option2=i option3 option4! option5+ / ); h2o $opts; # <~ here #... exit; __END__ ## now we get the following, but only for the options actually passed +(updated) # $opts->option1 # $opts->option2 # $opts->option3 # $opts->option4 # $opts->option5
And now I can start to quantify where and when I'd like to use Util::H2O - not as an actual way to have a bunch of boiler plate at the top of my script to declare classes (which it does support), but perlishly (and iteratively) adding accessors to hash references - which my code tends to be absolutely full of. I've used it in some other places to clean up existing code and in new code, knowing full well I am going to be slinging hash references all over the place.
In summary - check out Util::H2O. If you're like me, then you'll find little benefits to you that POOP offers can actually be satisfied in this natural way. It also occurs to me, this topic would be an ideal entry for the Perl Advent Calendar - so maybe I'll work out some more examples and make a submission later this year.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perl OOP (POOP) - a use case for Util::H2O (hash to object)
by perlfan (Parson) on Jul 08, 2021 at 16:43 UTC |