[newbie] scope of the variables

Discussion in 'Perl Misc' started by John, Sep 30, 2003.

  1. John

    John Guest

    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
     
    John, Sep 30, 2003
    #1
    1. Advertising

  2. John <> wrote:

    > 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.


    --
    Tad McClellan SGML consulting
    Perl programming
    Fort Worth, Texas
     
    Tad McClellan, Sep 30, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mortal Wombat
    Replies:
    3
    Views:
    6,852
    Mortal Wombat
    Aug 7, 2003
  2. Paul Opal
    Replies:
    12
    Views:
    985
    Paul Opal
    Oct 11, 2004
  3. ann
    Replies:
    13
    Views:
    689
    Patricia Shanahan
    Sep 13, 2005
  4. Steven T. Hatton
    Replies:
    9
    Views:
    510
  5. Talha Oktay
    Replies:
    8
    Views:
    227
Loading...

Share This Page