Perl - Gotchas

perl

Perl garbage collector frees programmer from memory management … until the programmer creates circular references

Perl's garbage collector counts references. When the count reaches zero (which means that no one has a reference), Perl reclaims the entity. The approach is simple and effective. However, circular references (when object A has a reference to object B, and object B has a reference to object A) present a problem. Even if nothing else in the program has a reference to either A or B, the reference count can never reach zero. Objects A and B do not get destroyed. If the code creates them again and again (perhaps in a loop), you get a memory leak. The amount of memory allocated by the program increases without a sensible reason and can never decrease. This effect may be acceptable for simple run-and-exit scripts, but it's not acceptable for programs running 24x365, such as in a mod_perl or FastCGI environment or as standalone servers.

Circular references are sometimes too useful to avoid. A common example is a tree-like data structure. To navigate both directions (from root to leaves and vice versa), a parent node has a list of children and a child node has a reference to its parent.

If you append a newline to the end of the message you pass to die(), Perl won't report the line number the error happened on

If you append a newline to the end of the message you pass to die(), Perl won't report the line number the error has happened at, so if you code:

open FILE,$filename or die "failed to open a file\n";

The error message will be: "failed to open a file".

The warn() function, a sister of die(), behaves in the same way.

$! variable store the reason for failures.

What is the reason for this?

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License