in reply to Re^2: Put references to array of hash elements in an array
in thread Put references to array of hash elements in an array

References work the other way round. \$AoH[0]{age} is a reference to the value stored under age, i.e. something like \42, it's no longer connected to the structure it came from.

You need to store the references in the @AoH if you want it to reflect the changes:

#!/usr/bin/perl use warnings; use strict; my @AoH; my @age_ref = (42, 33); @AoH = ( { age => \$age_ref[0] }, {}, { age => \$age_ref[1] }, ); use Data::Dumper; print Dumper \@age_ref; @age_ref = (1, 2); use Data::Dumper; print Dumper \@AoH;

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^4: Put references to array of hash elements in an array
by tel2 (Pilgrim) on Aug 03, 2018 at 07:41 UTC
    Thanks for that, choroba,

    If references work the other way round (i.e. I need to store the reference in the @AoH), then why does this code update the @AoH?:

    @AoH = ( { name => Adam, age => 0 }, { name => Bob, age => 10 }, { name => Cat, age => 20 } ); @age_ref = (\$AoH[0]{age},\$AoH[2]{age}); ${$age_ref[1]} = 23; print "\$AoH[2]{age} = $AoH[2]{age}\n"; # The above prints '$AoH[2]{age} = 23'

    Thanks.
    Tel2

      When you assign to @AoH directly
      @AoH = ...

      the previous contents of the @AoH is irrelevant, the array now contains different elements. When you assign to something an elements references to, it changes the thing being referenced.

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
        Thanks choroba,

        > "When you assing to @AoH directly (@AoH = ...) the previous contents of the @AoH is irrelevant, the array now contains different elements."

        Where in my code did I assign anything to @AoH directly via "@AoH = ..." apart from at the very beginning?