new guy new guy - 1 year ago 70
Perl Question

Global perl hash reference asignment

I have a global perl ref, to which i am assign the value from my local reference, I am not sure if that does a copy to the global reference or uses the same reference, but that should be a local memory to the block.

#!/usr/bin/env perl

use strict;
use warnings;

my $array;
foreach $a (1..10) {
my $localref = {"test"=> 1};
$array->[$a] = $localref; # does this result in copy?

Answer Source

I assume this should be the global hashref:

my $hash; 

The loop goes trough 1 to 10 creating a local scope hash reference $localref:

foreach $a (1..10) {
    my $localref = {"test"=> 1};

$localref is now a pointer to the memory address of a hashref containing {test => 1}. Try to add a print command to see it:

    print $localref;

You'll notice that the memory address shown changes for each loop run.

    $hash->[$a] = $localref; # does this result in copy?

$hash->[$a] is using a variable called $hash as an ArrayRef. You should consider renaming it.

Try showing the contents of your "global" $hash after the loop:

for (1..10) {
    print $_."\t".$hash->[$_];

You'll see all your references still alive.

Use Data::Dumper to show the contents:

use Data::Dumper;
print Dumper($hash);

Final conclusion:

The memory location storing your HashRefs always stays the same, the contents are never copied, but the reference (address information) is copied. Two references to the same location exist for a short moment between $hash->[$a] = $localref; and }.

PS: The memory used by {"test"=> 1} will be freed as soon as no reference to it exists any longer.