[Chicago-talk] Global variable behavior

Alexander Danel danel at speakeasy.net
Wed Mar 3 19:00:08 PST 2010

Get in the habit of putting the following at the top of every file:


            use strict;


Try it.  It will inform you that you are implicitly doing just what you
claim you are not doing: you have declared (or, as you put it "redeclared")
the variable.  "Use strict" will protest because implicit declarations are
often an accident; which is clearly appropriate for your case.


By the way, I take exception to your statement  ". . . should make it global
across all name spaces."  No such concept exists in Perl.  You declared the
variable to be in the "main" namespace; which you seemingly understood when
you used "$::c", the naked double-colon being an alias for "main::".   The
package "main" is in force until you declare otherwise.


Alexander Danel


From: chicago-talk-bounces+danel=speakeasy.net at pm.org
[mailto:chicago-talk-bounces+danel=speakeasy.net at pm.org] On Behalf Of Mithun
Sent: Wednesday, March 03, 2010 8:20 PM
To: chicago-talk at pm.org
Subject: [Chicago-talk] Global variable behavior


Hi Everyone,

A piece of my code is behaving in a way I didn't expect and I was hoping
someone could enlighten me as to why..

$ cat a.pl 
push @INC, '.';

our $c = 15;

require newbie;
$ cat newbie.pm 
package newbie;

print "first attempt: " . $c . "\n";
print "second attempt: " . $::c . "\n";

$ perl a.pl 
first attempt: 
second attempt: 15

The way I see it the our in a.pl should make it global across all
namespaces. The second attempt does seem to say that did take place. What I
am not sure is why the $c variable has become local in scope even though I
haven't re-declared or redefined it in any way inside newbie.pm.

- Mithun


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/chicago-talk/attachments/20100303/cffba3df/attachment.html>

More information about the Chicago-talk mailing list