tags:

views:

98

answers:

1

I am trying to use a hash of hashes like this -

#!/usr/bin/perl -w
use strict;

my %hash = ();

sub hash_populate
{
    my $name = "PQR,ABD,XYZ";
    my @parts = split(/,/,$name);
    my $i = $parts[0];
    my $a= $parts[1];
    my $b = $parts[2];

    $hash{$i} = {"A" =>$a,"B" => $b};
    my $c =  $hash{$i}{"A"};
    print $c;
}

I get an error of the form

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

The same code works when use strict is not present. Can someone tell me why?

+1  A: 

Well since I tried this in 5.8.7 with strict and it worked, I can't help thinking that the code you're actually running was malformed in some way this is not and "It worked without strict" means that it didn't die. Perl just let you do whatever you wanted, and lets you catch the problems yourself.

So the answer is

1) the code works (for toy code) for 5.8

2) "it worked without strict" is a common statement among Perl newbies, and until I can see some code that tries to stringify a hash reference I can't say anything different.

3) Why it "works without strict" is a combination of how much you fit that pattern, how the actual code is malformed, and the fact that Perl will allow you to shoot yourself in the foot myriad times with strict turned off--and some times you'll think that it worked.

4) Somethings actually do work without strict, and they are meant to. That is turning strictures off (no strict 'refs';) is meant to be the way that you purposely do a chancy operation.

Axeman
Well, it turns out that the problem was not with the hash. I was trying to tie this multi-level hash to a dbm file, and that's what caused the error. In case of a multi-level hash, an MLDBM (Multi level DBM) is required. Thanks.