Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use hashes as arguments to subroutines in Perl?

People also ask

How do you call a hash in Perl?

A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..

How do you call a subroutine in Perl script?

Define and Call a Subroutinesubroutine_name( list of arguments ); In versions of Perl before 5.0, the syntax for calling subroutines was slightly different as shown below. This still works in the newest versions of Perl, but it is not recommended since it bypasses the subroutine prototypes.


The hashes are being collapsed into flat lists when you pass them into the function. So, when you shift off a value from the function's arguments, you're only getting one value. What you want to do is pass the hashes by reference.

do_stuff_with_hashes(\%first_hash, \%second_hash);

But then you have to work with the hashes as references.

my $first_hash  = shift;
my $second_hash = shift;

A bit late but,

As have been stated, you must pass references, not hashes.

do_stuff_with_hashes(\%first_hash, \%second_hash);

But if you need/want to use your hashes as so, you may dereference them imediatly.

sub do_stuff_with_hashes {
    my %first_hash = %{shift()};
    my %second_hash = %{shift()};
};

Hash references are the way to go, as the others have pointed out.

Providing another way to do this just for kicks...because who needs temp variables?

do_stuff_with_hashes( { gen_first_hash() }, { gen_second_hash() } );

Here you are just creating hash references on the fly (via the curly brackets around the function calls) to use in your do_stuff_with_hashes function. This is nothing special, the other methods are just as valid and probably more clear. This might help down the road if you see this activity in your travels as someone new to Perl.


First off,

 do_stuff_with_hashes(%first_hash, %second_hash);

"streams" the hashes into a list, equivalent to:

 ( 'key1_1', 'value1_1', ... , 'key1_n', 'value1_n', 'key2_1', 'value2_1', ... )

and then you select one and only one of those items. So,

 my %first_hash = shift;

is like saying:

 my %first_hash = 'key1_1'; 
 # leaving ( 'value1', ... , 'key1_n', 'value1_n', 'key2_1', 'value2_1', ... )

You cannot have a hash like { 'key1' }, since 'key1' is mapping to nothing.