Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re^5: Improve readability of Perl code. Naming reference variables.

by TGI (Parson)
on Jan 26, 2017 at 08:25 UTC ( #1180367=note: print w/replies, xml ) Need Help??

in reply to Re^4: Improve readability of Perl code. Naming reference variables.
in thread Improve readability of Perl code. Naming reference variables.

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.

sub a_subroutine { my ($opt, @bad ) = @_; my $string = delete $opt->{a_descriptively_named_string}; my $desktop_info = delete $opt->{desktop_config}; my $important_files = delete $opt->(important_files} // []; checkopt( \%opt, \@bad, a_descriptively_named_string => defined $string, desktop_config => ref $desktop_info eq 'HASH', important_files => ref $important_files eq 'ARRAY +', ); # Do stuff. } # checkopt is a nice little function along these line. # You can customize it a bit, (add support for testing for invocants, +fancy crap with passing additional error messages, what have you) # But in pretty much this form it has caught made many a bug shallow sub checkopt { while (@_) { if ( ref eq 'HASH' ) { my $opts = shift; @args = keys @$opts; croak "Unexpected options in subroutine call: @args" if %$opts; } elsif ( ref eq 'ARRAY' ) { my $bad = shift; croak "Unexpected arguments in subroutine call." if @$bad } else { my $option_name = shift; my $option_okay = shift; croak "Invalid option '$option_name' in subroutine call" unless $option_okay; } } }

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.

TGI says moo

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1180367]
and the universe expands...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2018-05-20 20:05 GMT
Find Nodes?
    Voting Booth?