Replacing a hash with a variable when calling a function

Viewed 89

What I want to do is replace the function call:

my_function({'param1' => 123, 'param2' => 456});

with:

my %tmp = {'param1' => 123, 'param2' => 456};
my_function(%tmp);

I get the run-time error message:

Can't use string ("HASH(0x16cffb0)") as a HASH ref while "strict refs" in use

What am I doing wrong?

3 Answers

This does not do what you want:

my %tmp = {param1 => 123, param2 => 456};

You are trying to assign a hash reference to a hash. This raises warning:

Reference found where even-sized list expected at -e line 4.

Moral: always use strict; use warnings;, so such error is spotted quickly.

Your function appears to take a hash reference as argument. So either build a hash and pass it by reference:

my %tmp = (param1 => 123, param2 => 456);
my_function(\%tmp);

Or build a hash reference and pass it as-is:

my $tmp = {param1 => 123, param2 => 456};
my_function($tmp);

Your function looks like it expects a reference to a hash (which is a scalar in Perl):

my $tmp = {'param1' => 123, 'param2' => 456};
my_function($tmp);

Curly braces ({}) are used to create a hash reference.

Refer to perldoc perlreftut

my %tmp = {'param1' => 123, 'param2' => 456};

A hash is initialised with a list. And lists are defined using round brackets:

my %tmp = ('param1' => 123, 'param2' => 456);

You can then take a reference to that hash and pass the reference to your subroutine:

my_function(\%tmp);

Alternatively, you can use the { ... } to create an anonymous hash and get the reference to it immediately:

# Note that $tmp is a scalar as it contains
# a reference, not a hash.
my $tmp = {'param1' => 123, 'param2' => 456};

You can then pass that reference to your subroutine:

my_function($tmp);
Related