As everyone has already mentioned, Perl has garbage collection and you don't need to worry about it. However, if you did for some reason need to free up some memory the way to do that would be
undef $x;
not
$x = undef;
The former is equivalent to the C "free" function, whereas with the latter you are moving your pointer/reference off your object - if this were C code, you'd have just lost your allocated memory and leaked it. This is Perl, so the garbage collector takes care of you and it works, but not for the reason you think it does.

There is one case where you need to manage your memory in Perl, and that's when you're using SWIG to allocate memory in C from Perl:
use SwiggedCLib; #allocate a struct in C my $pointer = SwiggedCLib::createIt(); #do something with the struct my $result = SwiggedCLib::doSomething( $pointer ); #destroy the struct - Perl doesn't know how SwiggedCLib::destroyIt( $pointer );
When I did this with SWIG/C/Perl/Tcl, I vaguely remember having to undef the $pointer that held the struct or I would get a fatal exception from the garbage collector. However, that may have been in Tcl, not Perl. And I may have been doing something wrong. I'll update this when I get home and can look at the code...

Update

I just checked the code, and I did need to do
undef $pointer;
after freeing the memory using a SWIGged C function (which also set the C pointer to NULL). The error I got if I didn't may have been a segfault - I don't remember, I just know it was a showstopper. It leaves open the possibility that I was doing something wrong - it worked fine in Tcl, though...

In reply to Re: Memory Management... by bean
in thread Memory Management... by alincoln

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.