http://www.perlmonks.org?node_id=1025981


in reply to Passing array into a hash

What I usually do is to have a single parameter that is a hashref.   For example:

use strict; use warnings; errors( { 'all_msgs' => 'foo', 'msg_subject' => 'bar', } ); sub errors { my $args = shift; my $all = $$args{'all_msgs'} || ''; ... }

A few things to notice here, and they’re partly just stylistic:

  1. Perl lets you have a trailing-comma, as I do in my call to errors(), for the pure-and-simple reason that it's a bit easier to add new stuff after it as you revise the program.   The hash as-shown contains two keys, not three.
  2. I enclose the hash-keys in quotes, vs. the so-called “barewords.”
  3. To me, the use of use strict; use warnings; is obligatory.
  4. In the snippet of code defining errors() itself, $$args{'foo'} is a shorthand for $args->{'foo'} that I happen to prefer.

In this example, the first (and only) argument to the subroutine is “a reference to a hash,” otherwise known simply as a “hashref.”   Perl uses the notion of a “ref” quite extensively, allowing you to build up arbitrarily complex data structures.