Why does the following gives the following output? $a1 is defined...
package A1;
use Hash::Merge;
use Data::Dumper;
sub new
{
my $class = shift;
my $self =
{
length => 2,
};
return bless $self, $class;
}
1;
my $a1 = A1->new();
print("a1 = " . ref($a1) . "\n");
my %a = {'1' => $a1};
my $a3 = \%a;
print( Dumper($a3));
output:
a1 = A1
$VAR1 = {
'HASH(0x247c568)' => undef
};
I would've expected for the value to be a 'A1(0x...)' and not just undefined...
CodePudding user response:
The curly braces introduce a hash reference, but %a
is a hash, not a reference. Therefore, the reference was stringified and used as the key, and there was nothing to use as the value, so it remained undefined.
Try
my %a = (1 => $a1);
instead.
You can also create the reference directly without %a
:
my $a3 = {'1' => $a1};
You should always use warnings;
. Perl would've told you
Reference found where even-sized list expected at ...