⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 declare.pm

📁 基于稀疏网络的精选机器学习模型
💻 PM
📖 第 1 页 / 共 5 页
字号:
To reject a parameter match, the C<reject> operator is used. TheC<reject> operator takes an optional argument.If the argument is true (or was omitted), the current parametermatch is immediately rejected. For example:	-ar <R:n>	Set aspect ratio (must be in the range (0..1])				{				  $::sawaspect++;				  reject $R <= 0 || $R > 1 ;				  setaspect($R);				}	-q		Quiet option (not available on Wednesdays)				{				  reject((localtime)[6] == 3);				  $::verbose = 0;				}Note that any actions performed I<before> the call to C<reject> willstill have effect (for example, the variable C<$::sawaspect> remainsincremented even if the aspect ratio parameter is subsequently rejected).The C<reject> operator may also take a second argument, which isused as an error message if the rejected argument subsequentlyfails to match any other parameter. For example:	-q	Quiet option (not available on Wednesdays)			{			  reject((localtime)[6] == 3 => "Not today!");			  $::verbose = 0;			}=head2 Specifying other parameter variable typesAs was mentioned in L<"Type of parameter variables">, parametervariables can be restricted to matching only numbers or only integersby using the type specifiers ":n" and ":i". F<Getopt::Declare>provides seven other inbuilt type specifiers, as well as two mechanismsfor defining new restrictions on parameter variables.The other inbuilt type specifiers are:=over 4=item :+iwhich restricts a parameter variable to matching positive, non-zerointegers (that is: 1, 2, 3, etc.)=item :+nwhich restricts a parameter variable to matching positive, non-zeronumbers (that is, floating point numbers strictly greater than zero).=item :0+i  which restricts a parameter variable to matching non-negative integers (thatis: 0, 1, 2, 3, etc.)=item :0+n  which restricts a parameter variable to matching non-negative numbers (thatis, floating point numbers greater than or equal to zero).=item :s  which allows a parameter variable to match any quote-delimited orwhitespace-terminated string. Note that this specifier simply makesexplicit the default behaviour.=item :if  which is used to match input file names. Like type ':s', type ':if'matches any quote-delimited or whitespace-terminated string. Howeverthis type does I<not> respect other command-line flags and alsorequires that the matched string is either "-" (indicating standardinput) or the name of a readable file.=item :of  which is used to match output file names. It is exactly like type ':if' exceptthat it requires that the string is either "-" (indicating standard output)or the name of a file that is either writable or non-existent.=item :s  which allows a parameter variable to match any quote-delimited orwhitespace-terminated string. Note that this specifier simply makesexplicit the default behaviour.=backFor example:	-repeat <count:+i>	Repeat <count> times (must be > 0)	-scale <factor:0+n>	Set scaling factor (cannot be negative)Alternatively, parameter variables can be restricted to matching aspecific regular expression, by providing the required patternexplicitly (in matched "/" delimiters after the ":"). For example:	-parity <p:/even|odd|both/>	Set parity (<p> must be "even",					"odd" or "both")	-file <name:/\w*\.[A-Z]{3}/>	File name must have a three-					capital-letter extensionIf an explicit regular expression is used, there are three "convenience"extensions available:=over 4=item %TIf the sequence C<%T> appears in a pattern, it is translated to a negativelookahead containing the parameter variable's trailing context.Hence the parameter definition:	-find <what:/(%T\.)+/> ;ensures that the command line argument "-find abcd;" causes C<E<lt>whatE<gt>>to match "abcd", I<not> "abcd;".=item %DIf the sequence C<%D> appears in a pattern, it is translated into a subpatternwhich matches any single digit (like a C<\d>), but only if that digitwould I<not> match the parameter variable's trailing context.Hence C<%D> is just a convenient short-hand for C<(?:%T\d)> (and is actuallyimplemented that way).=item %FBy default, any explicit pattern is modified by F<Getopt::Declare>so that it fails if the argument being matched represents some definedparameter flag. If however the sequence C<%F> appears anywhere in apattern, it causes the pattern I<not> to reject strings which wouldotherwise match another flag. For example, the inbuilt types ':if' and':of' use C<%F> to enable them to match filenames which happen to beidentical to parameter flags.=back=head2 Defining new parameter variable typesExplicit regular expressions are very powerful, but also cumbersome touse (or reuse) in some situations. F<Getopt::Declare> provides a general"parameter variable type definition" mechanism to simplify such cases.To declare a new parameter variable type, the C<[pvtype:...]> directiveis used. A C<[pvtype...]> directive specifies the name, matchingpattern, and action for the new parameter variable type (though boththe pattern and action are optional).The name string may be I<any> whitespace-terminated sequence ofcharacters which does not include a ">". The name may also be specifiedwithin a pair of quotation marks (single or double) or within any Perlquotelike operation. For example:	[pvtype: num     ]	# Makes this valid: -count <N:num>	[pvtype: 'a num' ]	# Makes this valid: -count <N:a num>	[pvtype: q{nbr}  ]	# Makes this valid: -count <N:nbr>The pattern is used in initial matching of the parameter variable.Patterns are normally specified as a "/"-delimited Perl regularexpression:	[pvtype: num      /\d+/        ]		[pvtype: 'a num'  /\d+(\.\d*)/ ]	[pvtype: q{nbr}   /[+-]?\d+/   ]Alternatively the pattern associated with a new type may be specifiedas a ":" followed by the name of another parameter variable type (inquotes if necessary). In this case the new type matches the samepattern (and action! - see below) as the named type.  For example:	[pvtype: num      :+i      ]	# <X:num> is the same as <X:+i>	[pvtype: 'a num'  :n       ]	# <X:a num> is the same as <X:n>	[pvtype: q{nbr}   :'a num' ]	# <X:nbr> is also the same as <X:n>As a third alternative, the pattern may be omitted altogether, inwhich case the new type matches whatever the inbuilt pattern ":s"matches.The optional action which may be included in any C<[pvtype:...]>directive is executed I<after> the corresponding parameter variablematches the command line but I<before> any actions belonging to theenclosing parameter are executed. Typically, such type actionswill call the C<reject> operator (see L<"Termination and rejection">)to test extra conditions, but any valid Perl code is acceptible. Forexample:	[pvtype: num      /\d+/    { reject if (localtime)[6]==3 }	]	[pvtype: 'a num'  :n       { print "a num!" }		]	[pvtype: q{nbr}   :'a num' { reject $::no_nbr }		]If a new type is defined in terms of another (for example, ":a num"and ":nbr" above), any action specified by that new type isI<prepended> to the action of that other type. Hence:=over 4=item *the new type ":num" matches any string of digits, but then rejects thematch if it's Wednesday.=item *the new type ":a num" matches any string of digits (like its parenttype ":num"), I<then> prints out "a num!", I<and then> rejects thematch if it's Wednesday (like its parent type ":num").=item *the new type ":nbr" matches any string of digits (like its parent type":a num"), but then rejects the match if the global C<$::no_nbr> variableis true. Otherwise it next prints out "a num!" (like its parent type":a num"), and finally rejects the match if it's Wednesday (like itsgrandparent type ":num").=backWhen a type action is executed (as part of a particular parametermatch), three local variables are available:=over 4=item C<$_VAL_>which contains the value matched by the type's pattern. It is this value whichis ultimately assigned to the local Perl variable which is available toparameter actions. Hence if the type action changes the value of C<$_VAL_>,that changed value becomes the "real" value of the corresponding parametervariable (see the Roman numeral example below).=item C<$_VAR_>which contains the name of the parameter variable being matched.=item C<$_PARAM_>which contains the name of the parameter currently being matched.=backHere is a example of the use of these variables:	$args = new Getopt::Declare <<'EOPARAM';	[pvtype: type  /[OAB]|AB')/	                                ]	[pvtype: Rh?   /Rh[+-]/					        ]	[pvtype: days  :+i  { reject $_VAL_<14 " $_PARAM_ (too soon!)"} ]	  -donated <D:days>		  Days since last donation	  -applied <A:days>		  Days since applied to donate	  -blood <type:type> [<rh:Rh?>]	  Specify blood type					  and (optionally) rhesus factor	EOPARAMIn the above example, the ":days" parameter variable type is definedto match whatever the ":+i" type matches (that is positive, non-zerointegers), with the proviso that the matching value (C<$_VAL_>) mustbe at least 14. If a shorter value is specified for C<E<lt>DE<gt>>,or C<E<lt>AE<gt>> parameter variables, then F<Getopt::Declare> wouldissue the following (respective) error messages:	Error: -donated (too soon!)	Error: -applied (too soon!)Note that the "inbuilt" parameter variable types ("i", "n", etc.) arereally just predefined type names, and hence can be altered if necessary:	$args = new Getopt::Declare <<'EOPARAM';	[pvtype: 'n' /[MDCLXVI]+/ { reject !($_VAL_=to_roman $_VAL_) } ]		-index <number:n>	Index number			{ print $data[$number]; }	EOPARAMThe above C<[pvtype:...]> directive means that all parameter variablesspecified with a type ":n" henceforth only match valid Romannumerals, but that any such numerals are I<automatically> converted toordinary numbers (by passing C<$_VAL_>) through the C<to_roman>function).Hence the requirement that all ":n" numbers now must be Roman can beimposed I<transparently>, at least as far as the actual parametervariables which use the ":n" type are concerned. Thus C<$number> canbe still used to index the array C<@data> despite the new restrictionsplaced upon it by the redefinition of type ":n".Note too that, because the ":+n" and ":0+n" types are implicitly defined in terms of the original ":n" type (as if the directives:	[pvtype: '+n'  :n { reject if $_VAL <= 0  }  ]	[pvtype: '0+n' :n { reject if $_VAL < 0   }  ]were included in every specification), the above redefinition of ":n"affects those types as well. In such cases the format conversion isperformed I<before> the "sign" tests (in other words, the "inherited"actions are performed I<after> any newly defined ones).Parameter variable type definitions may appear anywhere in aF<Getopt::Declare> specification and are effective for the entirescope of the specification. In particular, new parameter variabletypes may be defined I<after> they are used.=head2 Undocumented parametersIf a parameter description is omitted, or consists entirely ofwhitespace, or contains the special directive C<[undocumented]>, thenthe parameter is still parsed as normal, but will not appear in theautomatically generated usage information (see L<"Usage information">).Apart from allowing for "secret" parameters (a dubious benefit), thisfeature enables the programmer to specify some undocumented actionwhich is to be taken on encountering an otherwise unknown argument.For example:	<unknown>				{ handle_unknown($unknown); }=head2 "Dittoed" parametersSometimes it is desirable to provide two or more alternate flags forthe same behaviour (typically, a short form and a long form). Toreduce the burden of specifying such pairs, the special directiveC<[ditto]> is provided. If the description of a parameter I<begins> witha C<[ditto]> directive, that directive is replaced with thedescription for the immediately preceding parameter (including anyother directives). For example:	-v		Verbose mode	--verbose	[ditto] (long form)In the automatically generated usage information this would be displayed as:	-v		Verbose mode	--verbose	   "     "   (long form)Furthermore, if the "dittoed" parameter has no action(s) specified, theaction(s) of the preceding parameter are reused. For example, thespecification:	-v		Verbose mode				{ $::verbose = 1; }	--verbose	[ditto]would result in the C<--verbose> option setting C<$::verbose> just like theC<-v> option. On the other hand, the specification:	-v		Verbose mode				{ $::verbose = 1; }	--verbose	[ditto]				{ $::verbose = 2; }would give separate actions to each flag.=head2 Deferred actionsIt is often desirable or necessary to defer actions taken in responseto particular flags until the entire command-line has been parsed. The mostobvious case is where modifier flags must be able to be specified I<after>the command-line arguments they modify.To support this, F<Getopt::Declare> provides a local operator (C<defer>) whichdelays the execution of a particular action until the command-line processingis finished. The C<defer> operator takes a single block, the execution of whichis deferred until the command-line is fully and successfully parsed. Ifcommand-line processing I<fails> for some reason (see L<"DIAGNOSTICS">), thedeferred blocks are never executed.For example:	<files>...	Files to be processed			    { defer { foreach (@files) { proc($_); } } }	-rev[erse]	Process in reverse order			    { $::ordered = -1; }	-rand[om]	Process in random order			    { $::ordered = 0; }With the above specification, the C<-rev> and/or C<-rand> flags can bespecified I<after> the list of files, but still affect the processing ofthose files. Moreover, if the command-line parsing fails for some reason(perhaps due to an unrecognized argument), the deferred processing willnot be performed.=head2 Flag clusteringLike some other F<Getopt::> packages, F<Getopt::Declare> allows parameterflags to be "clustered". That is, if two or more flags have the same"flag prefix" (one or more leading non-whitespace, non-alphanumeric characters),those flags may be concatenated behind a single copy of that flag prefix.For example, given the parameter specifications:	-+		Swap signs	-a		Append mode	-b		Bitwise compare	-c <FILE>	Create new file	+del		Delete old file	+e <NICE:i>	Execute (at specified nice level) when completeThe following command-lines (amongst others) are all exactly equivalent:	-a -b -c newfile +e20 +del	-abc newfile +dele20	-abcnewfile+dele20	-abcnewfile +e 20delThe last two alternatives are correctly parsed becauseF<Getopt::Declare> allows flag clustering at I<any point> where theremainder of the command-line being processed starts with anon-whitespace character and where the remaining substring would nototherwise immediately match a parameter flag.Hence the trailing "+dele20" in the third command-line example is parsed asS<"+del +e20"> and not S<"-+ del +e20">. This is because the previous "-"prefix is I<not> propagated (since the leading "+del" I<is> a valid flag).In contrast, the trailing S<"+e 20del"> in the fourth example is parsed asS<"+e 20 +del"> because, after the S<" 20"> is parsed (as the integerparameter variable C<E<lt>NICEE<gt>>), the next characters are "del",which I<do not> form a flag themselves unless prefixed with thecontrolling "+".In some circumstances a clustered sequence of flags on the command-linemight also match a single (multicharacter) parameter flag. For example, giventhe specifications:	-a		Blood type is A	-b		Blood type is B	-ab	 	Blood type is AB	-ba	 	Donor has a Bachelor of ArtsA command-line argument "-aba" might be parsed asS<"-a -b -a"> or S<"-a -ba"> or S<"-ab -a">. In all suchcases, F<Getopt::Declare> prefers the longest unmatched flag first.Hence the previous example would be parsed as S<"-ab -a">, unlessthe C<-ab> flag had already appeared in the command-line (in whichcase, it would be parsed as S<"-a -ba">).These rules are designed to produce consistency and "least surprise",but (as the above example illustrates) may not always do so. If theidea of unconstrained flag clustering is too libertarian for a particularapplication, the feature may be restricted (or removed completely),by including a C<[cluster:...]> directive anywhere in the specification string.The options are:=over 8=item C<[cluster: any]>This version of the directive allows any flag to be clustered (that is,it merely makes explicit the default behaviour).=item C<[cluster: flags]>This version of the directive restricts clustering to parameters which are"pure" flags (that is, those which have no parameter variables or punctuators).=item C<[cluster: singles]>This version of the directive restricts clustering to parameters which are"pure" fla

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -