Gossamer Forum
Home : General : Perl Programming :

use strict?

Quote Reply
use strict?
This is something that has been driving me crazy for a while.

If use strict is on, every variable must be declared right? But why must every variable, except constants, be declared using 'my'? How can I declare a global with use strict turned on, and why does 'local' and 'our' always give an internal server error?

Thanks,

- Jonathan
Quote Reply
Re: [jdgamble] use strict? In reply to
Well as I always keep searching, I find my answers.

http://perldoc.perl.org/strict.html

While posting too many messages here lately....

- Jonathan
Quote Reply
Re: [jdgamble] use strict? In reply to
See the differences between my, local, and our (and 'use vars').
In a nutshell, 'my' is the most widely used of the four. It defines a variable scoped to the current scope (which could be an entire file). It cannot be referred to from different scopes.

'local' lets you redefine a 'global' (package) variable for the current scope. If you want to make printing a list really simple, for instance, you might use something like
Code:
local $, = local $\ = $/;
print @list;


this will set $, (usually '') and $\ (usually '') to $/ (usually "\n") for the current scope.

'our' tells perl that you will be using the names package variable. For a normal program (i.e., not a package) using this, it tells perl that the 'variable' part of 'our variable' will refer to '*main::variable' (where * is the proper glyph). For instance,
Code:
package main;
our $abc = 123;


is exactly the same as
Code:
$main::abc = 123; # but you have to use $main::abc instead of $abc


which is the same as
Code:
no strict;
$abc = 123;


when there is no locally scoped $abc (e.g., with 'my' or 'local') for the current scope. 'our' and 'use vars' do essentially the same thing, but 'our' is now the recommended way to do it.

Code:
use vars qw/$abc/;
$abc = 123;

is the same as
Code:
our $abc;
$abc = 123;

Last edited by:

mkp: Aug 9, 2006, 11:07 AM
Quote Reply
Re: [mkp] use strict? In reply to
Thanks! I'm so used to delcaring a local scope or a global scope. Use strict just threw me off. It not helpful that every language handles scopes and variable declarations different. My perl book, that I use for reference more than anything, does not go over other declarations besides my.

But I understand what I need to know.

Thanks again,

- Jonathan