temporal has asked for the wisdom of the Perl Monks concerning the following question:
I'd like to settle on a coding style for passing arguments to subroutines. I did some hunting on CPAN for a relevant module and didn't turn anything up (was surprised, actually). In the past I've done all of the following:
# single arg, used for simple and dirty sub foo { my $arg = shift; } # more flexible, I've been using this more frequently for complex subs sub bar { my ($arg1, $arg2, @optionals) = @_; } # I want more sophisticated argument handling for optional args, so I +pass a hash reference containing all the arguments in predefined keys sub bletch { my $href = shift; # will warn me if $href->{hello_sub} is not defined print 'hi!' if $href->{hello_sub}; }
I like sub bletch the best because it allows all of my arguments to be optional and I can pass a single reference without having to worry about arguments being in the correct order, the caller code is more legible because it specifies key names, etc.
I did, however, encounter a snag with this method. I have to check for existence of the key within the referenced hash before attempting to access it otherwise Perl warns me about accessing an uninitialized value if the argument was not set by the user (this warning doesn't seem to complain when accessing a hash directly, rather than through a deref). This led to me writing this code:
# processes arguments passed to subroutine in hashref # returns hash sub sub_opts { my $href = shift; error("bad options hashref: $href") if ref($href) ne 'HASH'; # get all options to return if they exist my %hash = map {$_ => exists $href->{$_} ? $href->{$_} : 0} keys % +{$href}; return %hash; } # implemented like: sub foobie { my %opts = sub_opts(shift); # won't warn me if $opts{hello_sub} doesn't exist, just treats it +as false print 'hi!' if $opts{hello_sub}; }
But now I'm creating a new hash from the ref which I'd rather not do. Not that I'm planning on creating any huge hashes but I consider it good practice not to needlessly replicate variables. But the alternative is checking if any argument I want to access exists before accessing it within each subroutine I write. What a (possibly dangerous) pain.
Anyway, I really feel like I am reinventing the wheel here and I'm sure some of my fellow monks out there have developed a sane scheme for subroutine argument handling. Or maybe there's a CPAN module that I missed.
Advice/critique/discussion? Thanks!
|
|---|