question about variable assignment - easy

D

Danny

what is the difference between using

my $test = 5;
$test = 5;

can I use either one?

Thanks Danny
 
M

Mark Clements

Danny said:
what is the difference between using

my $test = 5;
$test = 5;

The first line is declaring $test to be a lexically scoped variable ie
local to the enclosing block or file; the second is autovivifying $test
as a package global. You should be declaring

use strict;
use warnings;

at the top of your script. Using strict catches a whole load of
potential errors at compile time and will prevent you from using the
second form - have a look at perldoc strict. If you *really* need to use
globals then you can declare such variables using our (perl 5.6+) or
with

use vars qw($test);

though this is subtly different from our.

Mark
 
R

Robin

Danny said:
what is the difference between using

my $test = 5;
$test = 5;

can I use either one?

Thanks Danny

you *can* use either one, but if you want to use strict "vars", you have to
use the first one, because strict requires you to declare your variables,
see the documentation for strict.
-Robin
 
S

Sherm Pendley

Robin said:
you *can* use either one, but if you want to use strict "vars", you have
to use the first one, because strict requires you to declare your

An incomplete answer, but at least that's better than a wrong answer. You're
improving.
variables, see the documentation for strict.

See also:

perldoc -q scoping
perldoc -f my
perldoc -f our
perldoc perlsub (section "Private Variables via my()")

sherm--
 
D

Danny

Sherm Pendley said:
An incomplete answer, but at least that's better than a wrong answer. You're

See also:

perldoc -q scoping
perldoc -f my
perldoc -f our
perldoc perlsub (section "Private Variables via my()")

sherm--

I appreciate all the responses.

Thanks very much
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top