0

I wrote th following program to see feature called circular reference in perl.

my $foo = 100;  
$foo = \$foo;
print "Value of foo is : ", $$foo, " " , $foo;

the output was:

Value of foo is : REF(0x21b632c) REF(0x21b632c)  

but i was wondering where the value 100 gone can any one help me.or is it a memory leak?

nikhil mehta
  • 972
  • 15
  • 30
  • 5
    The value of 100 was clobbered. That is no different than saying, `$f = 100`, and then saying `$f = 'foobar'`. The old value is lost. – Miller Mar 28 '14 at 09:45
  • 1
    Also, as perl uses a reference-counted garbage collector (plus a mark-and-sweep for circular references), there is no memory leak either. – Phylogenesis Mar 28 '14 at 09:46
  • @Phylogenesis It's new for me that Perl does mark-and-sweep – are you confusing this with CPython? OP's code will absolutely leak memory (`$foo` has a refcount of two, and will never drop to zero unless the circle is broken by reassignment or reference weakening). However, the scalar `100` will be garbage-collected. – amon Mar 28 '14 at 09:54
  • @amon It seems the mark-and-sweep is only run on exit. See [this question](http://stackoverflow.com/questions/2972021/garbage-collection-in-perl). – Phylogenesis Mar 28 '14 at 10:05
  • 1
    @Phylogenesis, actually a circular reference *is* a memory leak, because the clean-up doesn't happen until the program exits. –  Mar 28 '14 at 10:21
  • @dan1111 To be fair, my point about the memory leak was a direct answer to the question about whether the scalar value leaks. – Phylogenesis Mar 28 '14 at 10:23
  • @Phylogenesis, fair enough. –  Mar 28 '14 at 10:25

1 Answers1

0

The value 100 was overwritten. When you assign a value into a variable, it replaces the previous value.

my $foo = 100;
$foo = "a string here";

The value 100 has gone. The same thing happens in your code above. The only difference is what kind of value was put in there.

LeoNerd
  • 8,344
  • 1
  • 29
  • 36