[newbie] scope of the variables

J

John

Hi all,


I am trying to create a module. and I have a question about the scope
of the variables.



lets say,

use strict;


sub one {

my ($rvalue) = @_; # here I define a variable

for my $i (0..$#$rvalue){ # here I define a local
# variable $i and I use it

# do something
}

}


sub second {

my ($rvalue) = @_; # on this second sub $rvalue
# is a new one or I carry it
# as the first one


for my $i (0..$#$rvalue){ # now the same case, $i was
# already defined and if the
# scope is just its
# own subsroutine, now this
# $i is something copletely
# new. Am I right?

# do something else
}
}


# Thanks for your help
# John
 
T

Tad McClellan

John said:
I am trying to create a module. and I have a question about the scope
of the variables.


None of the variables in your module code below will be visible
in the "use"ing program, they are all "lexical variables".

Learn all about Perl's two separate systems of variables at:

"Coping with Scoping":

http://perl.plover.com/FAQs/Namespaces.html


for my $i (0..$#$rvalue){ # here I define a local ^^^^^
# variable $i and I use it
^^^^^^^^

(I can't say "for" for "foreach". I reserve "for" for for(;;) :)


In Perl, local() has to do with _package_ variables, which are
a form of _global_ variable, so it is confusing to use "local"
to mean "local". :) or should it be :-( ?

You have defined a _lexical_ variable.

Lexical variables (my) always get you a completely new variable,
new memory allocated and all.

So, yes, $i will be visible only within the body of the foreach() block.

When the (foreach) block exits, $i will cease to exist.

for my $i (0..$#$rvalue){ # now the same case, $i was
# already defined and if the
# scope is just its
# own subsroutine, now this
# $i is something copletely
# new. Am I right?


You are right.
 

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

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top