I'm doing this:
foo(('x' => 'y'), 'bar');
use strict;
sub foo {
my ($hash, $s) = @_;
my %e = %$hash;
print %e{'x'};
print $s;
}
I'm getting:
Can't use string ("x") as a HASH ref while "strict refs" in use at a.pl line 7.
What is the right way to pass a hash and a scalar to a subroutine?
('x' => 'y')
isn't a "hash", it's a list with two elements, and the parentheses don't even matter. What you're calling is the same as foo('x', 'y', 'bar')
.
If you want to pass a hashref as the first argument, you can use the anonymous hash reference constructor: foo({ x => 'y' }, 'bar')
.
Side note: print %e{'x'}
should be print $e{'x'}
. Or more simply, you can use the ->{}
operator to dereference and access at the same time: print $hash->{'x'}
.