·  PERL – Variable Type by Scope – Lexical

 

- Info:

  - Lexical variables are those explicitly declared using my qualifier:

    my $var = "Local";

  - Lexical variables hav no package prefix and none is assumed.

 

- Example:

  - If local variable is defined in the part of code enclosed with curly braces it will be seen only inside that block.

  - It will not be seen in the functions which are called from that block.

  - In that block, this variable will override package variable if the package variable with the same name exist.

    To use package variable of the same name you need to fully qualify its name.

 

    Test.pl

    $var = "Package Var";

    {  

      my $var="Local Var";

      print ($var      );    #"Local   Var".

      print ($main::var);    #"Package Var".

    }

    print ($var);            #"Package Var".

 

- Example:

  - If local variable is defined outside all curly braces it will be seen ANYWHERE inside file including functions.

  - If use strict; is not used then $var would mean local and not package variable.

 

    Test.pl

       $var = "Package Var"#Package variable.

    my $var = "Local   Var"#Local   variable.

    

    modifyPackageVar();

    modifyLocalVar  ();

    

    print ($main::var);       #"Modified Package Var".

    print ($var      );       #"Modified Local   Var".

    

    sub modifyPackageVar { $main::var = "Modified Package Var"; }

    sub modifyLocalVar   { $var       = "Modified Local   Var"; }