1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #!/usr/bin/perl # note: the following code will generate warnings with the -w switch, # and won't even compile with "use strict". It is meant to demonstrate # package and lexical variables. You should always "use strict". # pay attention to every line! # this is a global package variable; you shouldn't have any with "use strict" # it is implicitly in the package called "main" $global_sound = " "; package Cow; # the Cow package starts here # this is a package variable, accessible from any other package as $Cow::sound $sound = "moo"; # this is a lexical variable, accessible anywhere in this file my $extra_sound = "stampede"; package Pig; # the Pig package starts, Cow ends # this is a package variable, accessible from any other package as $Pig::sound $Pig::sound = "oink"; $::global_sound = "pigs do it better"; # another "main" package variable # we're back to the default (main) package package main; print "Cows go: ", $Cow::sound; # prints "moo" print "\nPigs go: ", $Pig::sound; # prints "oink" print "\nExtra sound: ", $extra_sound; # prints "stampede" print "\nWhat's this I hear: ", $sound; # $main::sound is undefined! print "\nEveryone says: ", $global_sound; # prints "pigs do it better" |
1 2 3 4 5 6 7 8 9 10 | #!/usr/bin/perl -w package Barebones; use strict; # this class takes no constructor parameters sub new { my $classname = shift; # we know our class name bless {}, $classname; # and bless an anonymous hash } 1; |
1 | perl -I. -MBarebones -e 'my $b = Barebones->new()' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/usr/bin/perl -w package Barebones; use strict; my $count = 0; # this class takes no constructor parameters sub new { my $classname = shift; # we know our class name $count++; # remember how many objects bless {}, $classname; # and bless an anonymous hash } sub count { my $self = shift; # this is the object itself return $count; } 1; |
1 | perl -I. -MBarebones -e 'my $b = Barebones->new(); Barebones->new(); print $b->count' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #!/usr/bin/perl -w package Barebones; # add these lines to your module's beginning, before other code or # variable declarations require Animal; # the parent class @ISA = qw(Animal); # announce we're a child of Animal # note that @ISA was left as a global default variable, and "use # strict" comes after its declaration. That's the easiest way to do it. use strict; use Carp; # make your new() method look like this: sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = $class->SUPER::new(); # use the parent's new() method bless ($self, $class); # but bless $self (an Animal) as Barebones } 1; |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |