1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2063351
  • 503
  • 2
  • 13
  • 31
  • To access the 'used' key you would do something like this $hash->{Primary}->{used} or $hash{Primary}->{used} (depending on whether your outer structure is a hash-ref or a hash). This will return the value 0.06, not a reference. What are you trying to achieve? – arunxls Mar 10 '14 at 12:45

2 Answers2

4
 ...
'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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Filippo Lauria
  • 1,965
  • 14
  • 20
0

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Miller
  • 34,962
  • 4
  • 39
  • 60