kprasanna_79 has asked for the wisdom of the Perl Monks concerning the following question:

Revered Monks,

In my project i could see variables defined like this

$::var = 1;
Whats the difference between
$var=1;
and the above one.Please ignore if i am wrong any where.
-Prasanna.K

Replies are listed 'Best First'.
Re: What does $::var means
by davorg (Chancellor) on Jul 14, 2006 at 10:11 UTC

    Basically, it means that the previous programmer either didn't really know what he was doing or was doing something very clever.

    $::var is just shorthand for $main::var, i.e. the package variable $var in the main package. Generally there are very few reasons why you would want to use package variables in preference to lexical variables, so without seeing more of the code, it's hard to know why your program uses this syntax.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: What does $::var means
by gellyfish (Monsignor) on Jul 14, 2006 at 10:10 UTC

    It's basically just a shortcut for the package variable $main::var as demonstrated by:

    package Foo; use strict; $::foo = "yayayaya"; + print $main::foo;

    In your example the unqualified$var might be a different variable if it a lexical variable.

    /J\

      gellyfish,

      But whats difference between

      my $var and $::var

      i know one is the package variable and other is lexical one. but is there any diference between them functionally


      -Prasanna.K

        They are not the same variable. The lexical variable declared as my $var is only accessible within the scope within which it is defined, whereas the package variable $main::var is essentially accessible anywhere. The package variable appears in the global symbol table whereas the lexical variables have their own 'pad' so they occupy a different namespace.

        /J\

        For the difference between $var and $::var see the following code:
        package Foo; $var = "hello\n"; $::var = "bye\n"; print $var; # hello print $Foo::var; # hello print $::var; # bye print $main::var; # bye package main; print $var; # bye !! print $Foo::var; # hello print $::var; # bye print $main::var; # bye
        So - as mentioned elsewhere - $::var is equivalent to $main::var while $var refers to the $var variable in the current package.

        -- Hofmator