Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^5: Benifits of using hash rather than number of variables?

by JavaFan (Canon)
on Jul 21, 2011 at 14:59 UTC ( #915891=note: print w/ replies, xml ) Need Help??


in reply to Re^4: Benifits of using hash rather than number of variables?
in thread Benifits of using hash rather than number of variables?

As you pointed out, it won't catch typos when calling the subroutine. Which is the important case.

Since there's no reason to use the hash key more than once inside the subroutine, the protecting inside the subroutine is just overhead, adding absolutely nothing at all of value:

sub whatever { my %params = @_; my $key1 = $params{key1}; my $key2 = $params{key2}; my $key3 = $params{key3}; ... neither %params, nor the key names are needed anymore ... }
Alternatively, you can stick the key names in variables.


Comment on Re^5: Benifits of using hash rather than number of variables?
Download Code
Re^6: Benifits of using hash rather than number of variables?
by duelafn (Priest) on Jul 21, 2011 at 15:27 UTC

    Note: Updated my previous reply with various proposed solutions.

    Indeed, the initial implementation (lock_keys %params, qw/ key1 key2 key3 /;) is equivalent to your solution there. Though, my reading of the OP was that they wanted to use hashes rather than set a bunch of variables like that and lock_keys offers no less protection than the originally proposed Tie::Hash::Vivify.

    My personal use of lock_keys is restricted to command line option parsing and some cases where it is "easy" to set up on hashes that may be passed around or used a lot (for example, log file parsing as described in The value of declarations). If I were looking for a complete solution for subroutine arguments I would most likely reach for Params::Validate or similar since once you move beyond lock_keys %params, qw/ key1 key2 key3 /;, the added coding effort for proper validation (vs just verifying key names) isn't much.

    Good Day,
        Dean

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://915891]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (8)
As of 2014-07-10 17:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (214 votes), past polls