How can I update a hash value using a hash reference in Perl?

3.3k Views Asked by At

Is there a way to update a value in a hash using a hash reference that points to the hash value?

My hash output looks like this:

    'Alternate' => {
        'free' => '27.52',
        'primary' => 'false',
        'used' => '0.01',
        'name' => '/mydir/journal2',
        'size' => '50.00'
     },
    'Primary' => {
        'free' => '60.57',
        'primary' => 'true',
        'used' => '0.06',
        'name' => '/mydir/journal',
        'size' => '64.00'
    }
};

I attempted to create a hash reference to the 'used' property in the hash and tried to update the value:

$hash_ref = \%hash->{"Primary"}->{used};
$hash_ref = "99%";
print $$hash_ref, "\n";

This changes the value of the hash, but I get the "Using a hash as a reference is deprecated at line X". I'd like to know if what I'm trying to do is possible and what I'm doing wrong.

2

There are 2 best solutions below

0
Filippo Lauria On
 ...
'Primary' => {
    'free' => '60.57',
    'primary' => 'true',
    'used' => '0.06',
    'name' => '/mydir/journal',
    'size' => '64.00'
}
 ...

Try to bypass the deprecation problem doing it like this:

 ...
my $hash_ref = $hash{'Primary'}; # if you declared `%hash = ( .. );`
# Or my $hash_ref = $hash->{'Primary'}; if you declared `$hash = { .. };`
print $hash_ref->{used}; # Prints 0.06
$hash_ref->{used} = '0.07'; # Update
print $href->{used}; # Prints 0.07
 ...

See perldsc, if you want to learn more.

0
Miller On

Your failure started because you tried to create a hash reference to a scalar. That's kind of a meaningless goal as those are different data types. As Filippo already demonstrated, you already have hash references as values of your greater hash, so you can rely on that.

However, if you really want to create a reference to the scalar, you can just edit that value. This is how you'd do it:

use strict;
use warnings;

my $h = {
    'Alternate' => {
        'free' => '27.52',
        'primary' => 'false',
        'used' => '0.01',
        'name' => '/mydir/journal2',
        'size' => '50.00',
     },
    'Primary' => {
        'free' => '60.57',
        'primary' => 'true',
        'used' => '0.06',
        'name' => '/mydir/journal',
        'size' => '64.00',
    }
};

my $primary = $h->{Primary};
print $primary->{used}, "\n"; # Outputs 0.06

my $usedref = \$h->{Primary}{used};
$$usedref = '0.07';

print $primary->{used}, "\n"; # Outputs 0.07