Loading ...
Sorry, an error occurred while loading the content.

my, our, local?

Expand Messages
  • Jonathan Hipkiss
    Can anyone explain in English what the difference is between these three? Cheers Jonathan
    Message 1 of 8 , Sep 1, 2003
    • 0 Attachment
      Can anyone explain in "English" what the difference is between these
      three?

      Cheers

      Jonathan
    • Paul Archer
      ... (Short answer on local , BTW, is it predates my , and isn t used much anymore.) From the beginners@perl.org list: From Bob_Showalter@taylorwhite.com Mon
      Message 2 of 8 , Sep 1, 2003
      • 0 Attachment
        3:15pm, Jonathan Hipkiss wrote:

        > Can anyone explain in "English" what the difference is between these
        > three?
        >

        (Short answer on 'local', BTW, is it predates 'my', and isn't used much
        anymore.)


        From the beginners@... list:

        From Bob_Showalter@... Mon Sep 1 10:27:55 2003
        Date: Wed, 13 Aug 2003 09:44:06 -0400
        From: Bob Showalter <Bob_Showalter@...>
        To: 'Paul Archer' <tigger@...>
        Cc: beginners@...
        Subject: RE: our vs my

        Paul Archer wrote:
        > Actually, while we're on the subject: can anyone *really* explain the
        > difference between the two, or perhaps more importantly, when someone
        > would want to use 'our' over 'my'? I've read the docs, but they're
        > not sinking in.

        Perl has two kinds of variables. The first kind are global variables (also
        called "package" variables or "symbol table" variables). These variables a)
        have a name in a package's symbol table, and b) have a lifetime equal to the
        duration of your process (Notwithstanding Perl's "local" statement, which
        adds a twist. But save that for another discussion.)

        You refer to a package variable like this:

        $MyPackage::foo = 1;

        This assigns to a scalar, $foo, in the "MyPackage" package. You don't have
        to declare such a variable; it is created automatically simply by your
        having used it's name.

        Perl has a "package" statement, which allows you to define a default package
        to be used when you don't explicitly specify one. So the following is
        equivalent to what's above:

        package MyPackage;
        $foo = 1;

        (If no package statement has been issued, the default package is "main").

        But that raises a problem. Since global variables are created automatically,
        it's easy to introduce bugs into your program by making typos in variable
        names.

        That's where "use strict" comes in. "use strict" (which should *always* be
        used in your programs), requires you to pre-declare package variables that
        you plan to use without a package name. Consider:

        package MyPackage;
        use strict;
        $foo = 1; # compile-time error: $foo not defined

        "our" is a declaration that introduces a package variable. So instead you
        write:

        package MyPackage;
        use strict;
        our $foo;
        $foo = 1; # OK; $foo has been declared

        You can combine the declaration and assignment in one step:

        our $foo = 1;

        Now if you accidentally misspell $foo as $fooo later in your program, Perl
        will raise a compile-time error.

        You can think of "our" as a license to use the variable without its package
        name under "use strict".

        "our" obeys lexical scoping rules. That is to say, your "license" is good
        from the point you issue the "our", until the end of the innermost enclosing
        block, eval, or file. Consider:

        use strict;

        {
        our $foo;
        $foo = 1; # OK, "our" declaration is in force
        } # block ends, "our" declaration ends
        $foo = 2; # compile-time error; outside of "our" scope

        Note that "our" is never strictly required. "use strict" always allows you
        to fully qualify a variable with a package name, even if you haven't
        declared it with "our":

        use strict;
        $MyPackage::foo = 1; # legal anywhere

        But doing this robs you of the compile-time checking that "use strict"
        provides. So, we recommend the use of "use strict" and "our" for package
        variables.

        The second type of variable is a lexical variable. These are created with
        the "my" statement. Unlike package variables, lexicals do not have an entry
        in a package symbol table. lexical variables also have a lexical scope: they
        have an existence only from the point of declaration until the end of the
        innermost enclosing block. This makes them similar to "auto" or stack-based
        variables in other languages. (Actually, the situation is more complex than
        that; file-scoped lexicals have essentially global lifetime, and if a global
        reference is taken to a block-scoped lexical, that value can persist beyond
        the lexical scope, unlike in languages like C).

        Anyway, you generally want to use the most restrictive scope appropriate for
        your variables, in order to formalize the interfaces between your program's
        parts and minimize the use of side effects through global variables. That is
        why "my" variables are generally recommended over package variables.

        There are some cases where you need package variables. For example, only
        package variables can be exported through the Exporter.pm mechanism. Since
        we always recommend the use of "use strict", you need to use "our" to
        declare those variables. (However, note that *importing* a symbol via the
        "use Package qw(list)" mechanism declares the symbols for the purposes of
        "use strict". "our" only needs to be used in the module that exports the
        symbols.)
      • J.E. Cripps
        ... Perl variables (be they $scalar, @array, %hash) may be 1. global or package variables 2. lexical or scoped Global variables are the default. They can
        Message 3 of 8 , Sep 1, 2003
        • 0 Attachment
          > Can anyone explain in "English" what the difference is between these
          > three?


          Perl variables (be they $scalar, @array, %hash) may be
          1. "global" or "package" variables
          2. "lexical" or scoped

          Global variables are the default. They can be accessed an
          altered at any time by any subroutine or assignment anywhere
          in the package they live in. This can lead to confusing results.

          Lexical, or "scoped" variables are created with "my" function,
          and "our" is just the plural of "my". Lexical variables exist
          within the block, brackets or sub in which they are declared.

          Maybe I'll dig up some examples for the difference.

          The "use strict" enforces scoping of variables. That's why
          it gets so much commendation.

          "Local" gives a variable a temporary value for the duration
          of the current block, and that value is seen
          everywhere in the program. It's used mainly with predefined
          variables e.g. $/

          Mark-Jason Dominus has a number of articles on these topics:

          Mark-Jason Dominus: Coping with Scoping:
          URL: http://perl.plover.com/FAQs/Namespaces.html
          Read this first, then his "Seven Uses of Local"

          His counsel "Don't use "local"; always use "my" " is widely
          quoted, but, as you'll see, is a bit of an exagerration.
        • J.E. Cripps
          ... That s right. The my function wasn t around in Perl 4, local was.
          Message 4 of 8 , Sep 1, 2003
          • 0 Attachment
            Paul Archer wrote:
            > (Short answer on 'local', BTW, is it predates 'my', and isn't used much
            > anymore.)


            That's right. The "my" function wasn't around in Perl 4,
            "local" was.
          • J.E. Cripps
            ... More accurately, from perldoc perlsub: use strict vars ; then any variable reference from there to the end of the enclosing block must EITHER refer to a
            Message 5 of 8 , Sep 1, 2003
            • 0 Attachment
              > The "use strict" enforces scoping of variables. That's why
              > it gets so much commendation.

              More accurately, from perldoc perlsub:

              use strict 'vars';

              then any variable reference from there to the end of the enclosing
              block must EITHER refer to a lexical variable, or must be
              FULLY qualified with the package name. A compilation error
              results otherwise.
            • Paul Archer
              ... Yuppers. One critical difference between local and my (and a good reason to (usually) avoid local ) is that a local variable in a subroutine will be
              Message 6 of 8 , Sep 1, 2003
              • 0 Attachment
                >
                > Paul Archer wrote:
                > > (Short answer on 'local', BTW, is it predates 'my', and isn't used much
                > > anymore.)
                >
                >
                > That's right. The "my" function wasn't around in Perl 4,
                > "local" was.
                >

                Yuppers.

                One critical difference between 'local' and 'my' (and a good reason to
                (usually) avoid 'local') is that a 'local' variable in a subroutine will be
                passed to another subroutine, where a variable scoped with 'my' won't.


                $var1 = 1;
                $var2 = 2;

                &sub1;


                sub sub1 {
                my $var1 = one;
                local $var2 = two;
                &sub2;
                }


                sub sub2 {
                print "\$var1 is $var1\n";
                print "\$var2 is $var2\n";
                }

                print "Afterwards \$var1 is $var1\n";
                print "Afterwards \$var2 is $var2\n";


                __END__


                Paul
              • Jonathan Hipkiss
                Thanks to all who replied to this, much appreciated. Jonathan ... these
                Message 7 of 8 , Sep 2, 2003
                • 0 Attachment
                  Thanks to all who replied to this, much appreciated.

                  Jonathan

                  --- In perl-beginner@yahoogroups.com, "Jonathan Hipkiss"
                  <jonathan@h...> wrote:
                  > Can anyone explain in "English" what the difference is between
                  these
                  > three?
                  >
                  > Cheers
                  >
                  > Jonathan
                • lang@ms.chinmin.edu.tw
                  ... I think another reason is you find yourself using the same name for different variables in different parts of the program, without realizing it. -- Greg
                  Message 8 of 8 , Sep 4, 2003
                  • 0 Attachment
                    On Mon, 01 Sep 2003, Paul Archer wrote:

                    > >From the beginners@... list:

                    > >From Bob_Showalter@... Mon Sep 1 10:27:55 2003
                    > Date: Wed, 13 Aug 2003 09:44:06 -0400
                    > From: Bob Showalter <Bob_Showalter@...>
                    > To: 'Paul Archer' <tigger@...>
                    > Cc: beginners@...
                    > Subject: RE: our vs my

                    > Since global variables are created automatically,
                    > it's easy to introduce bugs into your program by making typos in variable
                    > names.

                    I think another reason is you find yourself using the same name
                    for different variables in different parts of
                    the program, without realizing it.

                    --
                    Greg Matheson, Taiwan
                  Your message has been successfully submitted and would be delivered to recipients shortly.