Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Benifits of using hash rather than number of variables?

by tart (Beadle)
on Jul 20, 2011 at 01:39 UTC ( #915563=perlquestion: print w/replies, xml ) Need Help??
tart has asked for the wisdom of the Perl Monks concerning the following question:

Rather than using number of variables we can use hash key and value to do the same. When passing variables to subroutine is required using hash and hash reference makes scripts more cleaner. I am bit curious to know if there are any other benefits I would get if I use hash key and value rather than using single variables.

  • Comment on Benifits of using hash rather than number of variables?

Replies are listed 'Best First'.
Re: Benifits of using hash rather than number of variables?
by davido (Archbishop) on Jul 20, 2011 at 02:28 UTC

    "That depends."

    With a hashref you pass into your subroutine an anonymous hash of name/value pairs, which allows for named parameters, unordered parameter lists, facilitates optional parameters, extendability, and so on.

    But it can be a little unwieldy. There is something succinct in "split /:/, $string, 3;" that is lost if it becomes:

    split( { pattern => qr/:/, input => $string, giveme => 3 } );

    In Perl Best Practices the assertion is that when the parameter list grows to four or more it's time to consider named params. The book doesn't attempt to define the Ten Commandments though. Mostly it's "A lot of good ideas unless you have a good argument to the contrary." I can say it's a rare occasion when I'm able to use a function that has named parameters without first looking them up in the function's documentation again. I don't often have to look up split, and when I do it's to clarify a less common use.

    Do remember that named parameter lists via hashes aren't checked at compile-time by strict. So in a general sense, while a hash is very convenient, it doesn't afford some of the protections of first class variables. On the other hand, if ever you're tempted to manipulate variable names programatically, it's probably time to revert to using a hash in the first place.


Re: Benifits of using hash rather than number of variables?
by DrHyde (Prior) on Jul 20, 2011 at 10:11 UTC

    The three big advantages of passing hashes / hashrefs to your subroutines are:

    1. you have named parameters inside the subroutine, and you don't have to remember the order of arguments outside the subroutine;
    2. much easier to handle optional arguments, and to calculate which arguments to pass at runtime;
    3. easy to build up that hash a little bit at a time;

    The big disadvantage of using hashes is that you lose some strictness checking. use strict will usually tell you if you mis-type a variable name, but it can't tell you if you mis-type a hash key - instead, if you mis-type a key name when reading the hash, it'll just auto-vivify. This sort of bug can be a real pain in the arse to track down.

    Thankfully, there's a solution to this problem on the CPAN. Tie::Hash::Vivify is meant to let you provide "a hash where if you read a key that doesn't exist, it will call a code reference to fill that slot with a value", but it can of course be used thus:

    use Tie::Hash::Vivify; use Carp qw(confess); use Data::Dumper; ... my $hashref = Tie::Hash::Vivify->new(sub { confess("No auto-vivifying!\n".Dumper(\@_)) });

      See also Hash::Util which is in perl core since 5.8.0

      use Hash::Util qw( lock_keys ); my %hash = (foo => 42, bar => 23); lock_keys(%hash); say $hash{bae}; # Boom! "Attempt to access disallowed key 'bae' in a + restricted hash..."

      Good Day,

        That doesn't really work for named parameters, specially not if some parameters are optional. Unless you're going to do something unwieldy like:
        sub whatever { unless (@_) { my %params = (key1 => undef, key2 => undef, key3 => undef,); lock_keys %params; return \%params; } my %params = %{+shift}; ... sub body using named parameters ... } my $whatever_params = whatever(); $whatever_params->{key1} = $value1; $whatever_params->{key2} = $value2; $whatever_params->{key3} = $value3; whatever $whatever_params;
Re: Benifits of using hash rather than number of variables?
by TomDLux (Vicar) on Jul 20, 2011 at 16:46 UTC

    Other people have talked about hash arguments to routines; I'll look at a more general aspect.

    The key advantage in my mind is organizing or clustering data into categories. I am defined by my clothing sizes, degrees, vehicles, etc. My degrees are defined in terms of the courses I took, the grades I got, the assignments I completed. My studies in "History of the Modern World" doesn't care about my clothing sizes or whether I have a skateboard. Aggregating data into hashes instead of independent variables creates a context, it makes it easier to understand relationships.

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://915563]
Approved by ww
Front-paged by Old_Gray_Bear
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (9)
As of 2018-03-21 13:18 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (267 votes). Check out past polls.