handlers.pm
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· PM 代码 · 共 879 行 · 第 1/2 页
PM
879 行
package Attribute::Handlers;use 5.006;use Carp;use warnings;use strict;use vars qw($VERSION $AUTOLOAD);$VERSION = '0.79';# $DB::single=1;my %symcache;sub findsym { my ($pkg, $ref, $type) = @_; return $symcache{$pkg,$ref} if $symcache{$pkg,$ref}; $type ||= ref($ref); my $found; no strict 'refs'; foreach my $sym ( values %{$pkg."::"} ) { use strict; next unless ref ( \$sym ) eq 'GLOB'; return $symcache{$pkg,$ref} = \$sym if *{$sym}{$type} && *{$sym}{$type} == $ref; }}my %validtype = ( VAR => [qw[SCALAR ARRAY HASH]], ANY => [qw[SCALAR ARRAY HASH CODE]], "" => [qw[SCALAR ARRAY HASH CODE]], SCALAR => [qw[SCALAR]], ARRAY => [qw[ARRAY]], HASH => [qw[HASH]], CODE => [qw[CODE]],);my %lastattr;my @declarations;my %raw;my %phase;my %sigil = (SCALAR=>'$', ARRAY=>'@', HASH=>'%');my $global_phase = 0;my %global_phases = ( BEGIN => 0, CHECK => 1, INIT => 2, END => 3,);my @global_phases = qw(BEGIN CHECK INIT END);sub _usage_AH_ { croak "Usage: use $_[0] autotie => {AttrName => TieClassName,...}";}my $qual_id = qr/^[_a-z]\w*(::[_a-z]\w*)*$/i;sub import { my $class = shift @_; return unless $class eq "Attribute::Handlers"; while (@_) { my $cmd = shift; if ($cmd =~ /^autotie((?:ref)?)$/) { my $tiedata = ($1 ? '$ref, ' : '') . '@$data'; my $mapping = shift; _usage_AH_ $class unless ref($mapping) eq 'HASH'; while (my($attr, $tieclass) = each %$mapping) { $tieclass =~ s/^([_a-z]\w*(::[_a-z]\w*)*)(.*)/$1/is; my $args = $3||'()'; _usage_AH_ $class unless $attr =~ $qual_id && $tieclass =~ $qual_id && eval "use base q\0$tieclass\0; 1"; if ($tieclass->isa('Exporter')) { local $Exporter::ExportLevel = 2; $tieclass->import(eval $args); } $attr =~ s/__CALLER__/caller(1)/e; $attr = caller()."::".$attr unless $attr =~ /::/; eval qq{ sub $attr : ATTR(VAR) { my (\$ref, \$data) = \@_[2,4]; my \$was_arrayref = ref \$data eq 'ARRAY'; \$data = [ \$data ] unless \$was_arrayref; my \$type = ref(\$ref)||"value (".(\$ref||"<undef>").")"; (\$type eq 'SCALAR')? tie \$\$ref,'$tieclass',$tiedata :(\$type eq 'ARRAY') ? tie \@\$ref,'$tieclass',$tiedata :(\$type eq 'HASH') ? tie \%\$ref,'$tieclass',$tiedata : die "Can't autotie a \$type\n" } 1 } or die "Internal error: $@"; } } else { croak "Can't understand $_"; } }}sub _resolve_lastattr { return unless $lastattr{ref}; my $sym = findsym @lastattr{'pkg','ref'} or die "Internal error: $lastattr{pkg} symbol went missing"; my $name = *{$sym}{NAME}; warn "Declaration of $name attribute in package $lastattr{pkg} may clash with future reserved word\n" if $^W and $name !~ /[A-Z]/; foreach ( @{$validtype{$lastattr{type}}} ) { no strict 'refs'; *{"$lastattr{pkg}::_ATTR_${_}_${name}"} = $lastattr{ref}; } %lastattr = ();}sub AUTOLOAD { return if $AUTOLOAD =~ /::DESTROY$/; my ($class) = $AUTOLOAD =~ m/(.*)::/g; $AUTOLOAD =~ m/_ATTR_(.*?)_(.*)/ or croak "Can't locate class method '$AUTOLOAD' via package '$class'"; croak "Attribute handler '$2' doesn't handle $1 attributes";}my $builtin = qr/lvalue|method|locked|unique|shared/;sub _gen_handler_AH_() { return sub { _resolve_lastattr; my ($pkg, $ref, @attrs) = @_; my (undef, $filename, $linenum) = caller 2; foreach (@attrs) { my ($attr, $data) = /^([a-z_]\w*)(?:[(](.*)[)])?$/is or next; if ($attr eq 'ATTR') { no strict 'refs'; $data ||= "ANY"; $raw{$ref} = $data =~ s/\s*,?\s*RAWDATA\s*,?\s*//; $phase{$ref}{BEGIN} = 1 if $data =~ s/\s*,?\s*(BEGIN)\s*,?\s*//; $phase{$ref}{INIT} = 1 if $data =~ s/\s*,?\s*(INIT)\s*,?\s*//; $phase{$ref}{END} = 1 if $data =~ s/\s*,?\s*(END)\s*,?\s*//; $phase{$ref}{CHECK} = 1 if $data =~ s/\s*,?\s*(CHECK)\s*,?\s*// || ! keys %{$phase{$ref}}; # Added for cleanup to not pollute next call. (%lastattr = ()), croak "Can't have two ATTR specifiers on one subroutine" if keys %lastattr; croak "Bad attribute type: ATTR($data)" unless $validtype{$data}; %lastattr=(pkg=>$pkg,ref=>$ref,type=>$data); } else { my $type = ref $ref; my $handler = $pkg->can("_ATTR_${type}_${attr}"); next unless $handler; my $decl = [$pkg, $ref, $attr, $data, $raw{$handler}, $phase{$handler}, $filename, $linenum]; foreach my $gphase (@global_phases) { _apply_handler_AH_($decl,$gphase) if $global_phases{$gphase} <= $global_phase; } if ($global_phase != 0) { # if _gen_handler_AH_ is being called after # CHECK it's for a lexical, so make sure # it didn't want to run anything later local $Carp::CarpLevel = 2; carp "Won't be able to apply END handler" if $phase{$handler}{END}; } else { push @declarations, $decl } } $_ = undef; } return grep {defined && !/$builtin/} @attrs; }}{ no strict 'refs'; *{"Attribute::Handlers::UNIVERSAL::MODIFY_${_}_ATTRIBUTES"} = _gen_handler_AH_ foreach @{$validtype{ANY}};}push @UNIVERSAL::ISA, 'Attribute::Handlers::UNIVERSAL' unless grep /^Attribute::Handlers::UNIVERSAL$/, @UNIVERSAL::ISA;sub _apply_handler_AH_ { my ($declaration, $phase) = @_; my ($pkg, $ref, $attr, $data, $raw, $handlerphase, $filename, $linenum) = @$declaration; return unless $handlerphase->{$phase}; # print STDERR "Handling $attr on $ref in $phase with [$data]\n"; my $type = ref $ref; my $handler = "_ATTR_${type}_${attr}"; my $sym = findsym($pkg, $ref); $sym ||= $type eq 'CODE' ? 'ANON' : 'LEXICAL'; no warnings; if (!$raw && defined($data)) { if ($data ne '') { my $evaled = eval("package $pkg; no warnings; no strict; local \$SIG{__WARN__}=sub{die}; [$data]"); $data = $evaled unless $@; } else { $data = undef } } $pkg->$handler($sym, (ref $sym eq 'GLOB' ? *{$sym}{ref $ref}||$ref : $ref), $attr, $data, $phase, $filename, $linenum, ); return 1;}{ no warnings 'void'; CHECK { $global_phase++; _resolve_lastattr; _apply_handler_AH_($_,'CHECK') foreach @declarations; } INIT { $global_phase++; _apply_handler_AH_($_,'INIT') foreach @declarations }}END { $global_phase++; _apply_handler_AH_($_,'END') foreach @declarations }1;__END__=head1 NAMEAttribute::Handlers - Simpler definition of attribute handlers=head1 VERSIONThis document describes version 0.79 of Attribute::Handlers,released November 25, 2007.=head1 SYNOPSIS package MyClass; require v5.6.0; use Attribute::Handlers; no warnings 'redefine'; sub Good : ATTR(SCALAR) { my ($package, $symbol, $referent, $attr, $data) = @_; # Invoked for any scalar variable with a :Good attribute, # provided the variable was declared in MyClass (or # a derived class) or typed to MyClass. # Do whatever to $referent here (executed in CHECK phase). ... } sub Bad : ATTR(SCALAR) { # Invoked for any scalar variable with a :Bad attribute, # provided the variable was declared in MyClass (or # a derived class) or typed to MyClass. ... } sub Good : ATTR(ARRAY) { # Invoked for any array variable with a :Good attribute, # provided the variable was declared in MyClass (or # a derived class) or typed to MyClass. ... } sub Good : ATTR(HASH) { # Invoked for any hash variable with a :Good attribute, # provided the variable was declared in MyClass (or # a derived class) or typed to MyClass. ... } sub Ugly : ATTR(CODE) { # Invoked for any subroutine declared in MyClass (or a # derived class) with an :Ugly attribute. ... } sub Omni : ATTR { # Invoked for any scalar, array, hash, or subroutine # with an :Omni attribute, provided the variable or # subroutine was declared in MyClass (or a derived class) # or the variable was typed to MyClass. # Use ref($_[2]) to determine what kind of referent it was. ... } use Attribute::Handlers autotie => { Cycle => Tie::Cycle }; my $next : Cycle(['A'..'Z']);=head1 DESCRIPTIONThis module, when inherited by a package, allows that package's class todefine attribute handler subroutines for specific attributes. Variablesand subroutines subsequently defined in that package, or in packagesderived from that package may be given attributes with the same names asthe attribute handler subroutines, which will then be called in one ofthe compilation phases (i.e. in a C<BEGIN>, C<CHECK>, C<INIT>, or C<END>block). (C<UNITCHECK> blocks don't correspond to a global compilationphase, so they can't be specified here.)To create a handler, define it as a subroutine with the same name asthe desired attribute, and declare the subroutine itself with the attribute C<:ATTR>. For example: package LoudDecl; use Attribute::Handlers; sub Loud :ATTR { my ($package, $symbol, $referent, $attr, $data, $phase, $filename, $linenum) = @_; print STDERR ref($referent), " ", *{$symbol}{NAME}, " ", "($referent) ", "was just declared ", "and ascribed the ${attr} attribute ", "with data ($data)\n", "in phase $phase\n", "in file $filename at line $linenum\n"; }This creates a handler for the attribute C<:Loud> in the class LoudDecl.Thereafter, any subroutine declared with a C<:Loud> attribute in the classLoudDecl: package LoudDecl; sub foo: Loud {...}causes the above handler to be invoked, and passed:=over=item [0]the name of the package into which it was declared;=item [1]a reference to the symbol table entry (typeglob) containing the subroutine;=item [2]a reference to the subroutine;=item [3]the name of the attribute;=item [4]any data associated with that attribute;=item [5]the name of the phase in which the handler is being invoked;=item [6]the filename in which the handler is being invoked;=item [7]the line number in this file.=backLikewise, declaring any variables with the C<:Loud> attribute within thepackage: package LoudDecl; my $foo :Loud; my @foo :Loud; my %foo :Loud;will cause the handler to be called with a similar argument list (except,of course, that C<$_[2]> will be a reference to the variable).The package name argument will typically be the name of the class intowhich the subroutine was declared, but it may also be the name of a derivedclass (since handlers are inherited).If a lexical variable is given an attribute, there is no symbol table to which it belongs, so the symbol table argument (C<$_[1]>) is set to thestring C<'LEXICAL'> in that case. Likewise, ascribing an attribute toan anonymous subroutine results in a symbol table argument of C<'ANON'>.The data argument passes in the value (if any) associated with theattribute. For example, if C<&foo> had been declared: sub foo :Loud("turn it up to 11, man!") {...}then a reference to an array containing the stringC<"turn it up to 11, man!"> would be passed as the last argument.Attribute::Handlers makes strenuous efforts to convertthe data argument (C<$_[4]>) to a useable form before passing it tothe handler (but see L<"Non-interpretive attribute handlers">).If those efforts succeed, the interpreted data is passed in an arrayreference; if they fail, the raw data is passed as a string.For example, all of these: sub foo :Loud(till=>ears=>are=>bleeding) {...} sub foo :Loud(qw/till ears are bleeding/) {...} sub foo :Loud(qw/my, ears, are, bleeding/) {...} sub foo :Loud(till,ears,are,bleeding) {...}causes it to pass C<['till','ears','are','bleeding']> as the handler'sdata argument. While: sub foo :Loud(['till','ears','are','bleeding']) {...}causes it to pass C<[ ['till','ears','are','bleeding'] ]>; the arrayreference specified in the data being passed inside the standardarray reference indicating successful interpretation.However, if the data can't be parsed as valid Perl, thenit is passed as an uninterpreted string. For example: sub foo :Loud(my,ears,are,bleeding) {...} sub foo :Loud(qw/my ears are bleeding) {...}cause the strings C<'my,ears,are,bleeding'> andC<'qw/my ears are bleeding'> respectively to be passed as thedata argument.If no value is associated with the attribute, C<undef> is passed.=head2 Typed lexicals
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?