#!/usr/bin/perl -w package Szywiecki; $Robert = "the boss"; sub terminate { my $name = shift; # the following line was updated on 2004-12-29 following on aristotle73's comment print "$Robert has canned ${name}'s sorry butt\n"; } terminate("arturo"); # prints "the boss has canned arturo's sorry butt" package main; # terminate("arturo"); # produces an error if you uncomment it #### #!/usr/bin/perl -w use strict; $Robert = "the boss"; # error! print "\$Robert = $Robert\n"; #### #!/usr/bin/perl -w use strict; $main::Robert = "the boss"; print "\$main::Robert = $main::Robert\n"; #### #!/usr/bin/perl -w package Szyewicki; $Robert = "the boss"; package PoolHall; $Robert = "the darts expert"; package Sywiecki; # back to work! print "Here at work, 'Robert' is $Robert, but over at the pool hall, 'Robert' is $PoolHall::Robert\n"; #### #!/usr/bin/perl -w use strict; #remember we're in package main use vars qw($foo); $foo = "Yo!"; # sets $main::foo print "\$foo: $foo\n"; # prints "Yo!" my $foo = "Hey!"; # this is a file-level my variable! print "\$foo: $foo\n"; # prints "Hey!" -- new declaration 'masks' the old one { # start a block my $foo = "Yacht-Z"; print "\$foo: $foo\n"; # prints "Yacht-Z" -- we have a new $foo in scope. print "\$main::foo: $main::foo\n"; # we can still 'see' $main::foo subroutine(); } # end that block print "\$foo: $foo\n"; # there it is, our file-level $foo is visible again! print "\$main::foo: $main::foo\n"; # whew! $main::foo is still there! sub subroutine { print "\$foo: $foo\n"; # prints "Hey!" -- as the script is written # why? Because the variable declared in the naked block # is no longer in scope -- we have a new set of braces. # but the file-level variable is still in scope, and # still 'masks' the declaration of $main::foo } package Bar; print "\$foo: $foo\n"; # prints "Hey!" -- the my variable's still in scope # if we hadn't made that declaration above, this would be an error: the # interpreter would tell us that Bar::foo has not been defined. #### #~/usr/bin/perl -w use strict; our ($bob); use vars qw($carol); $carol = "ted"; $bob = "alice"; print "Bob => $bob, Carol => $carol\n"; package Movie; print "Bob => $bob, Carol => $carol\n"; #### #!/usr/bin/perl -w use strict; use vars qw ($foo); # or "our $foo" if you're using 5.6 $foo = "global value"; print "\$foo: $foo\n"; # prints "global value" print "mysub result '", &mysub(), "'\n"; #"global value" print "localsub result '", &localsub(), "'\n"; # "local value" print "no sub result '",&showfoo(), "'\n"; #"global value" sub mysub { my $foo = "my value"; showfoo(); # } sub localsub { local $foo = "local value"; showfoo(); # ALWAYS prints "local value" } sub showfoo { return $foo; }