Global Variables Via Namespaces |
The previous section described a way to share variables between
different files which are included from /base.html , by using the
same package across all the files. However this doesn't help us much
when dealing with the method files such as subs.html , because
these files have to have their own packages - so we are back to square
one. There is another way to share variables across even different
packages, and that is by using namespaces. For variables that need to
be accessible even from subs.html , you could use a namespace which
is specific to your website. For example, if your website domain is
mydomain.com, then you could create variables using the form $mydomain::xxx = "hello"; As long as you then make sure that you only use this namespace on this
website (and other websites on the same Apache web server use their
own namespaces), then you shouldn't get any conflicts. Once again, use
this with caution, since you introduce the possibility of
inadvertently sharing variables between completely different
websites. For example, if you cut and paste some useful code from one
website to another, you will need to make sure you change the
namespace of any globals. Otherwise, you could get some very obscure
bugs, since different requests to the various websites could conflict. You also need to be careful about variable initialization, since these
globals will now exist between different requests. So, it's possible
that if you don't re-initialize a global variable, then it may contain
some random value from a previous request. This can result in obscure
bugs. Just be careful to initialize all variables properly and you'll
be fine. Finally, note that Embperl will only clean up variables which don't
have an explicit package (i.e. are in one of the packages
automatically set up by Embperl). Variables in other namespaces are
not automatically cleaned up. As a result, you need to pay closer
attention to cleaning up if you use your own namespaces. The safe way
to clean up a variable is simply to 'undef' it.
|