"Can't use string ("") as a HASH ref while "strict refs" in use at" error while assigning hash to an hash in perl

Viewed 275

I'm assigning an hash %attributes to another hash %attributes_r. I need to print it as key/value pair of that hash %attributes, as mentioned below. But, while printing, why do I get this error, "Can't use string ("") as a HASH ref while "strict refs" in use at" in this line "foreach my $key1 (keys %{$attributes_r{$key}}) {" ?

My Code:

use strict;
use warnings;
our %attributes_r;
my %attributes = ('clear'      => 0,
               'reset'      => 0,
               'bold'       => 1,
               'dark'       => 2,
               'underscore' => 4,
               'blink'      => 5,
               'reverse'    => 7,
               'concealed'  => 8
               );


for (keys %attributes) {
    $attributes_r{$attributes{$_}} = $attributes{$_};
    # print "$_ => $attributes_r{$attributes{$_}}\n";
}


foreach my $key (keys %attributes_r)    {
    foreach my $key1 (keys %{$attributes_r{$key}})    {
        print "$key1 = > $attributes_r{$key}{$key1}\n";
    }
}

Any help is appreciated.

1 Answers

With your data, this is incorrect:

    foreach my $key1 (keys %{$attributes_r{$key}})  {

You are trying to dereference a value that is a string, not a reference, like the error says. If you did have a hash of hash, it might work, but you do not.

You might be trying to create a hash of hash, I'm not sure. This piece of code is very odd:

$attributes_r{$attributes{$_}} = $attributes{$_};   

Here you are taking the value from the original hash and use it as a key in the other hash. For example:

$attributes_r{0} = 0;

This is not really going to accomplish anything useful. If you clarify what it is you are trying to do I might be able to suggest a fix.

Also, if you are trying to view the data structure you are creating, I suggest you print it with Data::Dumper like this:

use Data::Dumper;
...
print Dumper \%attributes_r;
Related