Out value scope : Package « Language Basics « Perl






Out value scope

  

#!/usr/bin/perl

use warnings;
use strict;

package MyPackage;

my $my_var = "my-var";         
our $our_var = "our-var";      
our $local_var = "global-var"; 
use vars qw($use_var);         
                               

$use_var = "use-var";

package AnotherPackage;

print "Outside, my_var is '$my_var' \n";       
print "Outside, our_var is '$our_var' \n";     
print "Outside, local_var is '$local_var' \n"; 

#-----

sub sub1 {
    my $my_var = "my_in_sub1";
    our $our_var = "our_in_sub1";
    local $local_var = "local_in_sub1";

    print "In sub1, my_var is '$my_var'\n";    
    print "In sub1, our_var is '$our_var'\n";  
    print "In sub1, local_var is '$local_var'\n"; 

    sub2();
}

sub sub2 {
    print "In sub2, my_var is '$my_var'\n";       
    print "In sub2, our_var is '$our_var'\n";     
    print "In sub2, local_var is '$local_var'\n"; 
}

#-----

sub1();

print "Again outside, my_var is '$my_var' \n";       # display 'my-var'
print "Again outside, our_var is '$our_var' \n";     # display 'our-var'
print "Again outside, local_var is '$local_var' \n"; # display 'global-var'

   
    
  








Related examples in the same category

1.A package is a separate name space for variables to reside in.
2.Contents of the symbol table for the main package.
3.Default package is main
4.Define variables with the same name in different package
5.Module::get_scalar()
6.Package declarations and subroutine
7.Reference variable by package name
8.Requires the package created above and calls the subroutine declared within it:
9.Scope change
10.Switches between packages.
11.This code should be stored in the file Mymodule.pm.
12.Using the package keyword to change the package context
13.You have to tell Perl which packages you intend to use, with the use command:
14.Your package