Long.pm 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743
  1. #! perl
  2. # Getopt::Long.pm -- Universal options parsing
  3. # Author : Johan Vromans
  4. # Created On : Tue Sep 11 15:00:12 1990
  5. # Last Modified By: Johan Vromans
  6. # Last Modified On: Mon Feb 23 20:29:11 2015
  7. # Update Count : 1683
  8. # Status : Released
  9. ################ Module Preamble ################
  10. package Getopt::Long;
  11. use 5.004;
  12. use strict;
  13. use vars qw($VERSION);
  14. $VERSION = 2.45;
  15. # For testing versions only.
  16. use vars qw($VERSION_STRING);
  17. $VERSION_STRING = "2.45";
  18. use Exporter;
  19. use vars qw(@ISA @EXPORT @EXPORT_OK);
  20. @ISA = qw(Exporter);
  21. # Exported subroutines.
  22. sub GetOptions(@); # always
  23. sub GetOptionsFromArray(@); # on demand
  24. sub GetOptionsFromString(@); # on demand
  25. sub Configure(@); # on demand
  26. sub HelpMessage(@); # on demand
  27. sub VersionMessage(@); # in demand
  28. BEGIN {
  29. # Init immediately so their contents can be used in the 'use vars' below.
  30. @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
  31. @EXPORT_OK = qw(&HelpMessage &VersionMessage &Configure
  32. &GetOptionsFromArray &GetOptionsFromString);
  33. }
  34. # User visible variables.
  35. use vars @EXPORT, @EXPORT_OK;
  36. use vars qw($error $debug $major_version $minor_version);
  37. # Deprecated visible variables.
  38. use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
  39. $passthrough);
  40. # Official invisible variables.
  41. use vars qw($genprefix $caller $gnu_compat $auto_help $auto_version $longprefix);
  42. # Really invisible variables.
  43. my $bundling_values;
  44. # Public subroutines.
  45. sub config(@); # deprecated name
  46. # Private subroutines.
  47. sub ConfigDefaults();
  48. sub ParseOptionSpec($$);
  49. sub OptCtl($);
  50. sub FindOption($$$$$);
  51. sub ValidValue ($$$$$);
  52. ################ Local Variables ################
  53. # $requested_version holds the version that was mentioned in the 'use'
  54. # or 'require', if any. It can be used to enable or disable specific
  55. # features.
  56. my $requested_version = 0;
  57. ################ Resident subroutines ################
  58. sub ConfigDefaults() {
  59. # Handle POSIX compliancy.
  60. if ( defined $ENV{"POSIXLY_CORRECT"} ) {
  61. $genprefix = "(--|-)";
  62. $autoabbrev = 0; # no automatic abbrev of options
  63. $bundling = 0; # no bundling of single letter switches
  64. $getopt_compat = 0; # disallow '+' to start options
  65. $order = $REQUIRE_ORDER;
  66. }
  67. else {
  68. $genprefix = "(--|-|\\+)";
  69. $autoabbrev = 1; # automatic abbrev of options
  70. $bundling = 0; # bundling off by default
  71. $getopt_compat = 1; # allow '+' to start options
  72. $order = $PERMUTE;
  73. }
  74. # Other configurable settings.
  75. $debug = 0; # for debugging
  76. $error = 0; # error tally
  77. $ignorecase = 1; # ignore case when matching options
  78. $passthrough = 0; # leave unrecognized options alone
  79. $gnu_compat = 0; # require --opt=val if value is optional
  80. $longprefix = "(--)"; # what does a long prefix look like
  81. $bundling_values = 0; # no bundling of values
  82. }
  83. # Override import.
  84. sub import {
  85. my $pkg = shift; # package
  86. my @syms = (); # symbols to import
  87. my @config = (); # configuration
  88. my $dest = \@syms; # symbols first
  89. for ( @_ ) {
  90. if ( $_ eq ':config' ) {
  91. $dest = \@config; # config next
  92. next;
  93. }
  94. push(@$dest, $_); # push
  95. }
  96. # Hide one level and call super.
  97. local $Exporter::ExportLevel = 1;
  98. push(@syms, qw(&GetOptions)) if @syms; # always export GetOptions
  99. $requested_version = 0;
  100. $pkg->SUPER::import(@syms);
  101. # And configure.
  102. Configure(@config) if @config;
  103. }
  104. ################ Initialization ################
  105. # Values for $order. See GNU getopt.c for details.
  106. ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
  107. # Version major/minor numbers.
  108. ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
  109. ConfigDefaults();
  110. ################ OO Interface ################
  111. package Getopt::Long::Parser;
  112. # Store a copy of the default configuration. Since ConfigDefaults has
  113. # just been called, what we get from Configure is the default.
  114. my $default_config = do {
  115. Getopt::Long::Configure ()
  116. };
  117. sub new {
  118. my $that = shift;
  119. my $class = ref($that) || $that;
  120. my %atts = @_;
  121. # Register the callers package.
  122. my $self = { caller_pkg => (caller)[0] };
  123. bless ($self, $class);
  124. # Process config attributes.
  125. if ( defined $atts{config} ) {
  126. my $save = Getopt::Long::Configure ($default_config, @{$atts{config}});
  127. $self->{settings} = Getopt::Long::Configure ($save);
  128. delete ($atts{config});
  129. }
  130. # Else use default config.
  131. else {
  132. $self->{settings} = $default_config;
  133. }
  134. if ( %atts ) { # Oops
  135. die(__PACKAGE__.": unhandled attributes: ".
  136. join(" ", sort(keys(%atts)))."\n");
  137. }
  138. $self;
  139. }
  140. sub configure {
  141. my ($self) = shift;
  142. # Restore settings, merge new settings in.
  143. my $save = Getopt::Long::Configure ($self->{settings}, @_);
  144. # Restore orig config and save the new config.
  145. $self->{settings} = Getopt::Long::Configure ($save);
  146. }
  147. sub getoptions {
  148. my ($self) = shift;
  149. return $self->getoptionsfromarray(\@ARGV, @_);
  150. }
  151. sub getoptionsfromarray {
  152. my ($self) = shift;
  153. # Restore config settings.
  154. my $save = Getopt::Long::Configure ($self->{settings});
  155. # Call main routine.
  156. my $ret = 0;
  157. $Getopt::Long::caller = $self->{caller_pkg};
  158. eval {
  159. # Locally set exception handler to default, otherwise it will
  160. # be called implicitly here, and again explicitly when we try
  161. # to deliver the messages.
  162. local ($SIG{__DIE__}) = 'DEFAULT';
  163. $ret = Getopt::Long::GetOptionsFromArray (@_);
  164. };
  165. # Restore saved settings.
  166. Getopt::Long::Configure ($save);
  167. # Handle errors and return value.
  168. die ($@) if $@;
  169. return $ret;
  170. }
  171. package Getopt::Long;
  172. ################ Back to Normal ################
  173. # Indices in option control info.
  174. # Note that ParseOptions uses the fields directly. Search for 'hard-wired'.
  175. use constant CTL_TYPE => 0;
  176. #use constant CTL_TYPE_FLAG => '';
  177. #use constant CTL_TYPE_NEG => '!';
  178. #use constant CTL_TYPE_INCR => '+';
  179. #use constant CTL_TYPE_INT => 'i';
  180. #use constant CTL_TYPE_INTINC => 'I';
  181. #use constant CTL_TYPE_XINT => 'o';
  182. #use constant CTL_TYPE_FLOAT => 'f';
  183. #use constant CTL_TYPE_STRING => 's';
  184. use constant CTL_CNAME => 1;
  185. use constant CTL_DEFAULT => 2;
  186. use constant CTL_DEST => 3;
  187. use constant CTL_DEST_SCALAR => 0;
  188. use constant CTL_DEST_ARRAY => 1;
  189. use constant CTL_DEST_HASH => 2;
  190. use constant CTL_DEST_CODE => 3;
  191. use constant CTL_AMIN => 4;
  192. use constant CTL_AMAX => 5;
  193. # FFU.
  194. #use constant CTL_RANGE => ;
  195. #use constant CTL_REPEAT => ;
  196. # Rather liberal patterns to match numbers.
  197. use constant PAT_INT => "[-+]?_*[0-9][0-9_]*";
  198. use constant PAT_XINT =>
  199. "(?:".
  200. "[-+]?_*[1-9][0-9_]*".
  201. "|".
  202. "0x_*[0-9a-f][0-9a-f_]*".
  203. "|".
  204. "0b_*[01][01_]*".
  205. "|".
  206. "0[0-7_]*".
  207. ")";
  208. use constant PAT_FLOAT => "[-+]?[0-9_]+(\.[0-9_]+)?([eE][-+]?[0-9_]+)?";
  209. sub GetOptions(@) {
  210. # Shift in default array.
  211. unshift(@_, \@ARGV);
  212. # Try to keep caller() and Carp consistent.
  213. goto &GetOptionsFromArray;
  214. }
  215. sub GetOptionsFromString(@) {
  216. my ($string) = shift;
  217. require Text::ParseWords;
  218. my $args = [ Text::ParseWords::shellwords($string) ];
  219. $caller ||= (caller)[0]; # current context
  220. my $ret = GetOptionsFromArray($args, @_);
  221. return ( $ret, $args ) if wantarray;
  222. if ( @$args ) {
  223. $ret = 0;
  224. warn("GetOptionsFromString: Excess data \"@$args\" in string \"$string\"\n");
  225. }
  226. $ret;
  227. }
  228. sub GetOptionsFromArray(@) {
  229. my ($argv, @optionlist) = @_; # local copy of the option descriptions
  230. my $argend = '--'; # option list terminator
  231. my %opctl = (); # table of option specs
  232. my $pkg = $caller || (caller)[0]; # current context
  233. # Needed if linkage is omitted.
  234. my @ret = (); # accum for non-options
  235. my %linkage; # linkage
  236. my $userlinkage; # user supplied HASH
  237. my $opt; # current option
  238. my $prefix = $genprefix; # current prefix
  239. $error = '';
  240. if ( $debug ) {
  241. # Avoid some warnings if debugging.
  242. local ($^W) = 0;
  243. print STDERR
  244. ("Getopt::Long $Getopt::Long::VERSION ",
  245. "called from package \"$pkg\".",
  246. "\n ",
  247. "argv: ",
  248. defined($argv)
  249. ? UNIVERSAL::isa( $argv, 'ARRAY' ) ? "(@$argv)" : $argv
  250. : "<undef>",
  251. "\n ",
  252. "autoabbrev=$autoabbrev,".
  253. "bundling=$bundling,",
  254. "bundling_values=$bundling_values,",
  255. "getopt_compat=$getopt_compat,",
  256. "gnu_compat=$gnu_compat,",
  257. "order=$order,",
  258. "\n ",
  259. "ignorecase=$ignorecase,",
  260. "requested_version=$requested_version,",
  261. "passthrough=$passthrough,",
  262. "genprefix=\"$genprefix\",",
  263. "longprefix=\"$longprefix\".",
  264. "\n");
  265. }
  266. # Check for ref HASH as first argument.
  267. # First argument may be an object. It's OK to use this as long
  268. # as it is really a hash underneath.
  269. $userlinkage = undef;
  270. if ( @optionlist && ref($optionlist[0]) and
  271. UNIVERSAL::isa($optionlist[0],'HASH') ) {
  272. $userlinkage = shift (@optionlist);
  273. print STDERR ("=> user linkage: $userlinkage\n") if $debug;
  274. }
  275. # See if the first element of the optionlist contains option
  276. # starter characters.
  277. # Be careful not to interpret '<>' as option starters.
  278. if ( @optionlist && $optionlist[0] =~ /^\W+$/
  279. && !($optionlist[0] eq '<>'
  280. && @optionlist > 0
  281. && ref($optionlist[1])) ) {
  282. $prefix = shift (@optionlist);
  283. # Turn into regexp. Needs to be parenthesized!
  284. $prefix =~ s/(\W)/\\$1/g;
  285. $prefix = "([" . $prefix . "])";
  286. print STDERR ("=> prefix=\"$prefix\"\n") if $debug;
  287. }
  288. # Verify correctness of optionlist.
  289. %opctl = ();
  290. while ( @optionlist ) {
  291. my $opt = shift (@optionlist);
  292. unless ( defined($opt) ) {
  293. $error .= "Undefined argument in option spec\n";
  294. next;
  295. }
  296. # Strip leading prefix so people can specify "--foo=i" if they like.
  297. $opt = $+ if $opt =~ /^$prefix+(.*)$/s;
  298. if ( $opt eq '<>' ) {
  299. if ( (defined $userlinkage)
  300. && !(@optionlist > 0 && ref($optionlist[0]))
  301. && (exists $userlinkage->{$opt})
  302. && ref($userlinkage->{$opt}) ) {
  303. unshift (@optionlist, $userlinkage->{$opt});
  304. }
  305. unless ( @optionlist > 0
  306. && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
  307. $error .= "Option spec <> requires a reference to a subroutine\n";
  308. # Kill the linkage (to avoid another error).
  309. shift (@optionlist)
  310. if @optionlist && ref($optionlist[0]);
  311. next;
  312. }
  313. $linkage{'<>'} = shift (@optionlist);
  314. next;
  315. }
  316. # Parse option spec.
  317. my ($name, $orig) = ParseOptionSpec ($opt, \%opctl);
  318. unless ( defined $name ) {
  319. # Failed. $orig contains the error message. Sorry for the abuse.
  320. $error .= $orig;
  321. # Kill the linkage (to avoid another error).
  322. shift (@optionlist)
  323. if @optionlist && ref($optionlist[0]);
  324. next;
  325. }
  326. # If no linkage is supplied in the @optionlist, copy it from
  327. # the userlinkage if available.
  328. if ( defined $userlinkage ) {
  329. unless ( @optionlist > 0 && ref($optionlist[0]) ) {
  330. if ( exists $userlinkage->{$orig} &&
  331. ref($userlinkage->{$orig}) ) {
  332. print STDERR ("=> found userlinkage for \"$orig\": ",
  333. "$userlinkage->{$orig}\n")
  334. if $debug;
  335. unshift (@optionlist, $userlinkage->{$orig});
  336. }
  337. else {
  338. # Do nothing. Being undefined will be handled later.
  339. next;
  340. }
  341. }
  342. }
  343. # Copy the linkage. If omitted, link to global variable.
  344. if ( @optionlist > 0 && ref($optionlist[0]) ) {
  345. print STDERR ("=> link \"$orig\" to $optionlist[0]\n")
  346. if $debug;
  347. my $rl = ref($linkage{$orig} = shift (@optionlist));
  348. if ( $rl eq "ARRAY" ) {
  349. $opctl{$name}[CTL_DEST] = CTL_DEST_ARRAY;
  350. }
  351. elsif ( $rl eq "HASH" ) {
  352. $opctl{$name}[CTL_DEST] = CTL_DEST_HASH;
  353. }
  354. elsif ( $rl eq "SCALAR" || $rl eq "REF" ) {
  355. # if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
  356. # my $t = $linkage{$orig};
  357. # $$t = $linkage{$orig} = [];
  358. # }
  359. # elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
  360. # }
  361. # else {
  362. # Ok.
  363. # }
  364. }
  365. elsif ( $rl eq "CODE" ) {
  366. # Ok.
  367. }
  368. else {
  369. $error .= "Invalid option linkage for \"$opt\"\n";
  370. }
  371. }
  372. else {
  373. # Link to global $opt_XXX variable.
  374. # Make sure a valid perl identifier results.
  375. my $ov = $orig;
  376. $ov =~ s/\W/_/g;
  377. if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
  378. print STDERR ("=> link \"$orig\" to \@$pkg","::opt_$ov\n")
  379. if $debug;
  380. eval ("\$linkage{\$orig} = \\\@".$pkg."::opt_$ov;");
  381. }
  382. elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
  383. print STDERR ("=> link \"$orig\" to \%$pkg","::opt_$ov\n")
  384. if $debug;
  385. eval ("\$linkage{\$orig} = \\\%".$pkg."::opt_$ov;");
  386. }
  387. else {
  388. print STDERR ("=> link \"$orig\" to \$$pkg","::opt_$ov\n")
  389. if $debug;
  390. eval ("\$linkage{\$orig} = \\\$".$pkg."::opt_$ov;");
  391. }
  392. }
  393. if ( $opctl{$name}[CTL_TYPE] eq 'I'
  394. && ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY
  395. || $opctl{$name}[CTL_DEST] == CTL_DEST_HASH )
  396. ) {
  397. $error .= "Invalid option linkage for \"$opt\"\n";
  398. }
  399. }
  400. $error .= "GetOptionsFromArray: 1st parameter is not an array reference\n"
  401. unless $argv && UNIVERSAL::isa( $argv, 'ARRAY' );
  402. # Bail out if errors found.
  403. die ($error) if $error;
  404. $error = 0;
  405. # Supply --version and --help support, if needed and allowed.
  406. if ( defined($auto_version) ? $auto_version : ($requested_version >= 2.3203) ) {
  407. if ( !defined($opctl{version}) ) {
  408. $opctl{version} = ['','version',0,CTL_DEST_CODE,undef];
  409. $linkage{version} = \&VersionMessage;
  410. }
  411. $auto_version = 1;
  412. }
  413. if ( defined($auto_help) ? $auto_help : ($requested_version >= 2.3203) ) {
  414. if ( !defined($opctl{help}) && !defined($opctl{'?'}) ) {
  415. $opctl{help} = $opctl{'?'} = ['','help',0,CTL_DEST_CODE,undef];
  416. $linkage{help} = \&HelpMessage;
  417. }
  418. $auto_help = 1;
  419. }
  420. # Show the options tables if debugging.
  421. if ( $debug ) {
  422. my ($arrow, $k, $v);
  423. $arrow = "=> ";
  424. while ( ($k,$v) = each(%opctl) ) {
  425. print STDERR ($arrow, "\$opctl{$k} = $v ", OptCtl($v), "\n");
  426. $arrow = " ";
  427. }
  428. }
  429. # Process argument list
  430. my $goon = 1;
  431. while ( $goon && @$argv > 0 ) {
  432. # Get next argument.
  433. $opt = shift (@$argv);
  434. print STDERR ("=> arg \"", $opt, "\"\n") if $debug;
  435. # Double dash is option list terminator.
  436. if ( defined($opt) && $opt eq $argend ) {
  437. push (@ret, $argend) if $passthrough;
  438. last;
  439. }
  440. # Look it up.
  441. my $tryopt = $opt;
  442. my $found; # success status
  443. my $key; # key (if hash type)
  444. my $arg; # option argument
  445. my $ctl; # the opctl entry
  446. ($found, $opt, $ctl, $arg, $key) =
  447. FindOption ($argv, $prefix, $argend, $opt, \%opctl);
  448. if ( $found ) {
  449. # FindOption undefines $opt in case of errors.
  450. next unless defined $opt;
  451. my $argcnt = 0;
  452. while ( defined $arg ) {
  453. # Get the canonical name.
  454. print STDERR ("=> cname for \"$opt\" is ") if $debug;
  455. $opt = $ctl->[CTL_CNAME];
  456. print STDERR ("\"$ctl->[CTL_CNAME]\"\n") if $debug;
  457. if ( defined $linkage{$opt} ) {
  458. print STDERR ("=> ref(\$L{$opt}) -> ",
  459. ref($linkage{$opt}), "\n") if $debug;
  460. if ( ref($linkage{$opt}) eq 'SCALAR'
  461. || ref($linkage{$opt}) eq 'REF' ) {
  462. if ( $ctl->[CTL_TYPE] eq '+' ) {
  463. print STDERR ("=> \$\$L{$opt} += \"$arg\"\n")
  464. if $debug;
  465. if ( defined ${$linkage{$opt}} ) {
  466. ${$linkage{$opt}} += $arg;
  467. }
  468. else {
  469. ${$linkage{$opt}} = $arg;
  470. }
  471. }
  472. elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
  473. print STDERR ("=> ref(\$L{$opt}) auto-vivified",
  474. " to ARRAY\n")
  475. if $debug;
  476. my $t = $linkage{$opt};
  477. $$t = $linkage{$opt} = [];
  478. print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
  479. if $debug;
  480. push (@{$linkage{$opt}}, $arg);
  481. }
  482. elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
  483. print STDERR ("=> ref(\$L{$opt}) auto-vivified",
  484. " to HASH\n")
  485. if $debug;
  486. my $t = $linkage{$opt};
  487. $$t = $linkage{$opt} = {};
  488. print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
  489. if $debug;
  490. $linkage{$opt}->{$key} = $arg;
  491. }
  492. else {
  493. print STDERR ("=> \$\$L{$opt} = \"$arg\"\n")
  494. if $debug;
  495. ${$linkage{$opt}} = $arg;
  496. }
  497. }
  498. elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
  499. print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
  500. if $debug;
  501. push (@{$linkage{$opt}}, $arg);
  502. }
  503. elsif ( ref($linkage{$opt}) eq 'HASH' ) {
  504. print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
  505. if $debug;
  506. $linkage{$opt}->{$key} = $arg;
  507. }
  508. elsif ( ref($linkage{$opt}) eq 'CODE' ) {
  509. print STDERR ("=> &L{$opt}(\"$opt\"",
  510. $ctl->[CTL_DEST] == CTL_DEST_HASH ? ", \"$key\"" : "",
  511. ", \"$arg\")\n")
  512. if $debug;
  513. my $eval_error = do {
  514. local $@;
  515. local $SIG{__DIE__} = 'DEFAULT';
  516. eval {
  517. &{$linkage{$opt}}
  518. (Getopt::Long::CallBack->new
  519. (name => $opt,
  520. ctl => $ctl,
  521. opctl => \%opctl,
  522. linkage => \%linkage,
  523. prefix => $prefix,
  524. ),
  525. $ctl->[CTL_DEST] == CTL_DEST_HASH ? ($key) : (),
  526. $arg);
  527. };
  528. $@;
  529. };
  530. print STDERR ("=> die($eval_error)\n")
  531. if $debug && $eval_error ne '';
  532. if ( $eval_error =~ /^!/ ) {
  533. if ( $eval_error =~ /^!FINISH\b/ ) {
  534. $goon = 0;
  535. }
  536. }
  537. elsif ( $eval_error ne '' ) {
  538. warn ($eval_error);
  539. $error++;
  540. }
  541. }
  542. else {
  543. print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
  544. "\" in linkage\n");
  545. die("Getopt::Long -- internal error!\n");
  546. }
  547. }
  548. # No entry in linkage means entry in userlinkage.
  549. elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
  550. if ( defined $userlinkage->{$opt} ) {
  551. print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
  552. if $debug;
  553. push (@{$userlinkage->{$opt}}, $arg);
  554. }
  555. else {
  556. print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
  557. if $debug;
  558. $userlinkage->{$opt} = [$arg];
  559. }
  560. }
  561. elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
  562. if ( defined $userlinkage->{$opt} ) {
  563. print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
  564. if $debug;
  565. $userlinkage->{$opt}->{$key} = $arg;
  566. }
  567. else {
  568. print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
  569. if $debug;
  570. $userlinkage->{$opt} = {$key => $arg};
  571. }
  572. }
  573. else {
  574. if ( $ctl->[CTL_TYPE] eq '+' ) {
  575. print STDERR ("=> \$L{$opt} += \"$arg\"\n")
  576. if $debug;
  577. if ( defined $userlinkage->{$opt} ) {
  578. $userlinkage->{$opt} += $arg;
  579. }
  580. else {
  581. $userlinkage->{$opt} = $arg;
  582. }
  583. }
  584. else {
  585. print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
  586. $userlinkage->{$opt} = $arg;
  587. }
  588. }
  589. $argcnt++;
  590. last if $argcnt >= $ctl->[CTL_AMAX] && $ctl->[CTL_AMAX] != -1;
  591. undef($arg);
  592. # Need more args?
  593. if ( $argcnt < $ctl->[CTL_AMIN] ) {
  594. if ( @$argv ) {
  595. if ( ValidValue($ctl, $argv->[0], 1, $argend, $prefix) ) {
  596. $arg = shift(@$argv);
  597. if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) {
  598. $arg =~ tr/_//d;
  599. $arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/
  600. ? oct($arg)
  601. : 0+$arg
  602. }
  603. ($key,$arg) = $arg =~ /^([^=]+)=(.*)/
  604. if $ctl->[CTL_DEST] == CTL_DEST_HASH;
  605. next;
  606. }
  607. warn("Value \"$$argv[0]\" invalid for option $opt\n");
  608. $error++;
  609. }
  610. else {
  611. warn("Insufficient arguments for option $opt\n");
  612. $error++;
  613. }
  614. }
  615. # Any more args?
  616. if ( @$argv && ValidValue($ctl, $argv->[0], 0, $argend, $prefix) ) {
  617. $arg = shift(@$argv);
  618. if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) {
  619. $arg =~ tr/_//d;
  620. $arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/
  621. ? oct($arg)
  622. : 0+$arg
  623. }
  624. ($key,$arg) = $arg =~ /^([^=]+)=(.*)/
  625. if $ctl->[CTL_DEST] == CTL_DEST_HASH;
  626. next;
  627. }
  628. }
  629. }
  630. # Not an option. Save it if we $PERMUTE and don't have a <>.
  631. elsif ( $order == $PERMUTE ) {
  632. # Try non-options call-back.
  633. my $cb;
  634. if ( defined ($cb = $linkage{'<>'}) ) {
  635. print STDERR ("=> &L{$tryopt}(\"$tryopt\")\n")
  636. if $debug;
  637. my $eval_error = do {
  638. local $@;
  639. local $SIG{__DIE__} = 'DEFAULT';
  640. eval {
  641. # The arg to <> cannot be the CallBack object
  642. # since it may be passed to other modules that
  643. # get confused (e.g., Archive::Tar). Well,
  644. # it's not relevant for this callback anyway.
  645. &$cb($tryopt);
  646. };
  647. $@;
  648. };
  649. print STDERR ("=> die($eval_error)\n")
  650. if $debug && $eval_error ne '';
  651. if ( $eval_error =~ /^!/ ) {
  652. if ( $eval_error =~ /^!FINISH\b/ ) {
  653. $goon = 0;
  654. }
  655. }
  656. elsif ( $eval_error ne '' ) {
  657. warn ($eval_error);
  658. $error++;
  659. }
  660. }
  661. else {
  662. print STDERR ("=> saving \"$tryopt\" ",
  663. "(not an option, may permute)\n") if $debug;
  664. push (@ret, $tryopt);
  665. }
  666. next;
  667. }
  668. # ...otherwise, terminate.
  669. else {
  670. # Push this one back and exit.
  671. unshift (@$argv, $tryopt);
  672. return ($error == 0);
  673. }
  674. }
  675. # Finish.
  676. if ( @ret && $order == $PERMUTE ) {
  677. # Push back accumulated arguments
  678. print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
  679. if $debug;
  680. unshift (@$argv, @ret);
  681. }
  682. return ($error == 0);
  683. }
  684. # A readable representation of what's in an optbl.
  685. sub OptCtl ($) {
  686. my ($v) = @_;
  687. my @v = map { defined($_) ? ($_) : ("<undef>") } @$v;
  688. "[".
  689. join(",",
  690. "\"$v[CTL_TYPE]\"",
  691. "\"$v[CTL_CNAME]\"",
  692. "\"$v[CTL_DEFAULT]\"",
  693. ("\$","\@","\%","\&")[$v[CTL_DEST] || 0],
  694. $v[CTL_AMIN] || '',
  695. $v[CTL_AMAX] || '',
  696. # $v[CTL_RANGE] || '',
  697. # $v[CTL_REPEAT] || '',
  698. ). "]";
  699. }
  700. # Parse an option specification and fill the tables.
  701. sub ParseOptionSpec ($$) {
  702. my ($opt, $opctl) = @_;
  703. # Match option spec.
  704. if ( $opt !~ m;^
  705. (
  706. # Option name
  707. (?: \w+[-\w]* )
  708. # Alias names, or "?"
  709. (?: \| (?: \? | \w[-\w]* ) )*
  710. # Aliases
  711. (?: \| (?: [^-|!+=:][^|!+=:]* )? )*
  712. )?
  713. (
  714. # Either modifiers ...
  715. [!+]
  716. |
  717. # ... or a value/dest/repeat specification
  718. [=:] [ionfs] [@%]? (?: \{\d*,?\d*\} )?
  719. |
  720. # ... or an optional-with-default spec
  721. : (?: -?\d+ | \+ ) [@%]?
  722. )?
  723. $;x ) {
  724. return (undef, "Error in option spec: \"$opt\"\n");
  725. }
  726. my ($names, $spec) = ($1, $2);
  727. $spec = '' unless defined $spec;
  728. # $orig keeps track of the primary name the user specified.
  729. # This name will be used for the internal or external linkage.
  730. # In other words, if the user specifies "FoO|BaR", it will
  731. # match any case combinations of 'foo' and 'bar', but if a global
  732. # variable needs to be set, it will be $opt_FoO in the exact case
  733. # as specified.
  734. my $orig;
  735. my @names;
  736. if ( defined $names ) {
  737. @names = split (/\|/, $names);
  738. $orig = $names[0];
  739. }
  740. else {
  741. @names = ('');
  742. $orig = '';
  743. }
  744. # Construct the opctl entries.
  745. my $entry;
  746. if ( $spec eq '' || $spec eq '+' || $spec eq '!' ) {
  747. # Fields are hard-wired here.
  748. $entry = [$spec,$orig,undef,CTL_DEST_SCALAR,0,0];
  749. }
  750. elsif ( $spec =~ /^:(-?\d+|\+)([@%])?$/ ) {
  751. my $def = $1;
  752. my $dest = $2;
  753. my $type = $def eq '+' ? 'I' : 'i';
  754. $dest ||= '$';
  755. $dest = $dest eq '@' ? CTL_DEST_ARRAY
  756. : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
  757. # Fields are hard-wired here.
  758. $entry = [$type,$orig,$def eq '+' ? undef : $def,
  759. $dest,0,1];
  760. }
  761. else {
  762. my ($mand, $type, $dest) =
  763. $spec =~ /^([=:])([ionfs])([@%])?(\{(\d+)?(,)?(\d+)?\})?$/;
  764. return (undef, "Cannot repeat while bundling: \"$opt\"\n")
  765. if $bundling && defined($4);
  766. my ($mi, $cm, $ma) = ($5, $6, $7);
  767. return (undef, "{0} is useless in option spec: \"$opt\"\n")
  768. if defined($mi) && !$mi && !defined($ma) && !defined($cm);
  769. $type = 'i' if $type eq 'n';
  770. $dest ||= '$';
  771. $dest = $dest eq '@' ? CTL_DEST_ARRAY
  772. : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
  773. # Default minargs to 1/0 depending on mand status.
  774. $mi = $mand eq '=' ? 1 : 0 unless defined $mi;
  775. # Adjust mand status according to minargs.
  776. $mand = $mi ? '=' : ':';
  777. # Adjust maxargs.
  778. $ma = $mi ? $mi : 1 unless defined $ma || defined $cm;
  779. return (undef, "Max must be greater than zero in option spec: \"$opt\"\n")
  780. if defined($ma) && !$ma;
  781. return (undef, "Max less than min in option spec: \"$opt\"\n")
  782. if defined($ma) && $ma < $mi;
  783. # Fields are hard-wired here.
  784. $entry = [$type,$orig,undef,$dest,$mi,$ma||-1];
  785. }
  786. # Process all names. First is canonical, the rest are aliases.
  787. my $dups = '';
  788. foreach ( @names ) {
  789. $_ = lc ($_)
  790. if $ignorecase > (($bundling && length($_) == 1) ? 1 : 0);
  791. if ( exists $opctl->{$_} ) {
  792. $dups .= "Duplicate specification \"$opt\" for option \"$_\"\n";
  793. }
  794. if ( $spec eq '!' ) {
  795. $opctl->{"no$_"} = $entry;
  796. $opctl->{"no-$_"} = $entry;
  797. $opctl->{$_} = [@$entry];
  798. $opctl->{$_}->[CTL_TYPE] = '';
  799. }
  800. else {
  801. $opctl->{$_} = $entry;
  802. }
  803. }
  804. if ( $dups && $^W ) {
  805. foreach ( split(/\n+/, $dups) ) {
  806. warn($_."\n");
  807. }
  808. }
  809. ($names[0], $orig);
  810. }
  811. # Option lookup.
  812. sub FindOption ($$$$$) {
  813. # returns (1, $opt, $ctl, $arg, $key) if okay,
  814. # returns (1, undef) if option in error,
  815. # returns (0) otherwise.
  816. my ($argv, $prefix, $argend, $opt, $opctl) = @_;
  817. print STDERR ("=> find \"$opt\"\n") if $debug;
  818. return (0) unless defined($opt);
  819. return (0) unless $opt =~ /^($prefix)(.*)$/s;
  820. return (0) if $opt eq "-" && !defined $opctl->{''};
  821. $opt = substr( $opt, length($1) ); # retain taintedness
  822. my $starter = $1;
  823. print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
  824. my $optarg; # value supplied with --opt=value
  825. my $rest; # remainder from unbundling
  826. # If it is a long option, it may include the value.
  827. # With getopt_compat, only if not bundling.
  828. if ( ($starter=~/^$longprefix$/
  829. || ($getopt_compat && ($bundling == 0 || $bundling == 2)))
  830. && (my $oppos = index($opt, '=', 1)) > 0) {
  831. my $optorg = $opt;
  832. $opt = substr($optorg, 0, $oppos);
  833. $optarg = substr($optorg, $oppos + 1); # retain tainedness
  834. print STDERR ("=> option \"", $opt,
  835. "\", optarg = \"$optarg\"\n") if $debug;
  836. }
  837. #### Look it up ###
  838. my $tryopt = $opt; # option to try
  839. if ( ( $bundling || $bundling_values ) && $starter eq '-' ) {
  840. # To try overrides, obey case ignore.
  841. $tryopt = $ignorecase ? lc($opt) : $opt;
  842. # If bundling == 2, long options can override bundles.
  843. if ( $bundling == 2 && length($tryopt) > 1
  844. && defined ($opctl->{$tryopt}) ) {
  845. print STDERR ("=> $starter$tryopt overrides unbundling\n")
  846. if $debug;
  847. }
  848. # If bundling_values, option may be followed by the value.
  849. elsif ( $bundling_values ) {
  850. $tryopt = $opt;
  851. # Unbundle single letter option.
  852. $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
  853. $tryopt = substr ($tryopt, 0, 1);
  854. $tryopt = lc ($tryopt) if $ignorecase > 1;
  855. print STDERR ("=> $starter$tryopt unbundled from ",
  856. "$starter$tryopt$rest\n") if $debug;
  857. # Whatever remains may not be considered an option.
  858. $optarg = $rest eq '' ? undef : $rest;
  859. $rest = undef;
  860. }
  861. # Split off a single letter and leave the rest for
  862. # further processing.
  863. else {
  864. $tryopt = $opt;
  865. # Unbundle single letter option.
  866. $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
  867. $tryopt = substr ($tryopt, 0, 1);
  868. $tryopt = lc ($tryopt) if $ignorecase > 1;
  869. print STDERR ("=> $starter$tryopt unbundled from ",
  870. "$starter$tryopt$rest\n") if $debug;
  871. $rest = undef unless $rest ne '';
  872. }
  873. }
  874. # Try auto-abbreviation.
  875. elsif ( $autoabbrev && $opt ne "" ) {
  876. # Sort the possible long option names.
  877. my @names = sort(keys (%$opctl));
  878. # Downcase if allowed.
  879. $opt = lc ($opt) if $ignorecase;
  880. $tryopt = $opt;
  881. # Turn option name into pattern.
  882. my $pat = quotemeta ($opt);
  883. # Look up in option names.
  884. my @hits = grep (/^$pat/, @names);
  885. print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
  886. "out of ", scalar(@names), "\n") if $debug;
  887. # Check for ambiguous results.
  888. unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
  889. # See if all matches are for the same option.
  890. my %hit;
  891. foreach ( @hits ) {
  892. my $hit = $opctl->{$_}->[CTL_CNAME]
  893. if defined $opctl->{$_}->[CTL_CNAME];
  894. $hit = "no" . $hit if $opctl->{$_}->[CTL_TYPE] eq '!';
  895. $hit{$hit} = 1;
  896. }
  897. # Remove auto-supplied options (version, help).
  898. if ( keys(%hit) == 2 ) {
  899. if ( $auto_version && exists($hit{version}) ) {
  900. delete $hit{version};
  901. }
  902. elsif ( $auto_help && exists($hit{help}) ) {
  903. delete $hit{help};
  904. }
  905. }
  906. # Now see if it really is ambiguous.
  907. unless ( keys(%hit) == 1 ) {
  908. return (0) if $passthrough;
  909. warn ("Option ", $opt, " is ambiguous (",
  910. join(", ", @hits), ")\n");
  911. $error++;
  912. return (1, undef);
  913. }
  914. @hits = keys(%hit);
  915. }
  916. # Complete the option name, if appropriate.
  917. if ( @hits == 1 && $hits[0] ne $opt ) {
  918. $tryopt = $hits[0];
  919. $tryopt = lc ($tryopt) if $ignorecase;
  920. print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
  921. if $debug;
  922. }
  923. }
  924. # Map to all lowercase if ignoring case.
  925. elsif ( $ignorecase ) {
  926. $tryopt = lc ($opt);
  927. }
  928. # Check validity by fetching the info.
  929. my $ctl = $opctl->{$tryopt};
  930. unless ( defined $ctl ) {
  931. return (0) if $passthrough;
  932. # Pretend one char when bundling.
  933. if ( $bundling == 1 && length($starter) == 1 ) {
  934. $opt = substr($opt,0,1);
  935. unshift (@$argv, $starter.$rest) if defined $rest;
  936. }
  937. if ( $opt eq "" ) {
  938. warn ("Missing option after ", $starter, "\n");
  939. }
  940. else {
  941. warn ("Unknown option: ", $opt, "\n");
  942. }
  943. $error++;
  944. return (1, undef);
  945. }
  946. # Apparently valid.
  947. $opt = $tryopt;
  948. print STDERR ("=> found ", OptCtl($ctl),
  949. " for \"", $opt, "\"\n") if $debug;
  950. #### Determine argument status ####
  951. # If it is an option w/o argument, we're almost finished with it.
  952. my $type = $ctl->[CTL_TYPE];
  953. my $arg;
  954. if ( $type eq '' || $type eq '!' || $type eq '+' ) {
  955. if ( defined $optarg ) {
  956. return (0) if $passthrough;
  957. warn ("Option ", $opt, " does not take an argument\n");
  958. $error++;
  959. undef $opt;
  960. undef $optarg if $bundling_values;
  961. }
  962. elsif ( $type eq '' || $type eq '+' ) {
  963. # Supply explicit value.
  964. $arg = 1;
  965. }
  966. else {
  967. $opt =~ s/^no-?//i; # strip NO prefix
  968. $arg = 0; # supply explicit value
  969. }
  970. unshift (@$argv, $starter.$rest) if defined $rest;
  971. return (1, $opt, $ctl, $arg);
  972. }
  973. # Get mandatory status and type info.
  974. my $mand = $ctl->[CTL_AMIN];
  975. # Check if there is an option argument available.
  976. if ( $gnu_compat && defined $optarg && $optarg eq '' ) {
  977. return (1, $opt, $ctl, $type eq 's' ? '' : 0) ;#unless $mand;
  978. $optarg = 0 unless $type eq 's';
  979. }
  980. # Check if there is an option argument available.
  981. if ( defined $optarg
  982. ? ($optarg eq '')
  983. : !(defined $rest || @$argv > 0) ) {
  984. # Complain if this option needs an argument.
  985. # if ( $mand && !($type eq 's' ? defined($optarg) : 0) ) {
  986. if ( $mand ) {
  987. return (0) if $passthrough;
  988. warn ("Option ", $opt, " requires an argument\n");
  989. $error++;
  990. return (1, undef);
  991. }
  992. if ( $type eq 'I' ) {
  993. # Fake incremental type.
  994. my @c = @$ctl;
  995. $c[CTL_TYPE] = '+';
  996. return (1, $opt, \@c, 1);
  997. }
  998. return (1, $opt, $ctl,
  999. defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
  1000. $type eq 's' ? '' : 0);
  1001. }
  1002. # Get (possibly optional) argument.
  1003. $arg = (defined $rest ? $rest
  1004. : (defined $optarg ? $optarg : shift (@$argv)));
  1005. # Get key if this is a "name=value" pair for a hash option.
  1006. my $key;
  1007. if ($ctl->[CTL_DEST] == CTL_DEST_HASH && defined $arg) {
  1008. ($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2)
  1009. : ($arg, defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
  1010. ($mand ? undef : ($type eq 's' ? "" : 1)));
  1011. if (! defined $arg) {
  1012. warn ("Option $opt, key \"$key\", requires a value\n");
  1013. $error++;
  1014. # Push back.
  1015. unshift (@$argv, $starter.$rest) if defined $rest;
  1016. return (1, undef);
  1017. }
  1018. }
  1019. #### Check if the argument is valid for this option ####
  1020. my $key_valid = $ctl->[CTL_DEST] == CTL_DEST_HASH ? "[^=]+=" : "";
  1021. if ( $type eq 's' ) { # string
  1022. # A mandatory string takes anything.
  1023. return (1, $opt, $ctl, $arg, $key) if $mand;
  1024. # Same for optional string as a hash value
  1025. return (1, $opt, $ctl, $arg, $key)
  1026. if $ctl->[CTL_DEST] == CTL_DEST_HASH;
  1027. # An optional string takes almost anything.
  1028. return (1, $opt, $ctl, $arg, $key)
  1029. if defined $optarg || defined $rest;
  1030. return (1, $opt, $ctl, $arg, $key) if $arg eq "-"; # ??
  1031. # Check for option or option list terminator.
  1032. if ($arg eq $argend ||
  1033. $arg =~ /^$prefix.+/) {
  1034. # Push back.
  1035. unshift (@$argv, $arg);
  1036. # Supply empty value.
  1037. $arg = '';
  1038. }
  1039. }
  1040. elsif ( $type eq 'i' # numeric/integer
  1041. || $type eq 'I' # numeric/integer w/ incr default
  1042. || $type eq 'o' ) { # dec/oct/hex/bin value
  1043. my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT;
  1044. if ( $bundling && defined $rest
  1045. && $rest =~ /^($key_valid)($o_valid)(.*)$/si ) {
  1046. ($key, $arg, $rest) = ($1, $2, $+);
  1047. chop($key) if $key;
  1048. $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
  1049. unshift (@$argv, $starter.$rest) if defined $rest && $rest ne '';
  1050. }
  1051. elsif ( $arg =~ /^$o_valid$/si ) {
  1052. $arg =~ tr/_//d;
  1053. $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
  1054. }
  1055. else {
  1056. if ( defined $optarg || $mand ) {
  1057. if ( $passthrough ) {
  1058. unshift (@$argv, defined $rest ? $starter.$rest : $arg)
  1059. unless defined $optarg;
  1060. return (0);
  1061. }
  1062. warn ("Value \"", $arg, "\" invalid for option ",
  1063. $opt, " (",
  1064. $type eq 'o' ? "extended " : '',
  1065. "number expected)\n");
  1066. $error++;
  1067. # Push back.
  1068. unshift (@$argv, $starter.$rest) if defined $rest;
  1069. return (1, undef);
  1070. }
  1071. else {
  1072. # Push back.
  1073. unshift (@$argv, defined $rest ? $starter.$rest : $arg);
  1074. if ( $type eq 'I' ) {
  1075. # Fake incremental type.
  1076. my @c = @$ctl;
  1077. $c[CTL_TYPE] = '+';
  1078. return (1, $opt, \@c, 1);
  1079. }
  1080. # Supply default value.
  1081. $arg = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : 0;
  1082. }
  1083. }
  1084. }
  1085. elsif ( $type eq 'f' ) { # real number, int is also ok
  1086. # We require at least one digit before a point or 'e',
  1087. # and at least one digit following the point and 'e'.
  1088. my $o_valid = PAT_FLOAT;
  1089. if ( $bundling && defined $rest &&
  1090. $rest =~ /^($key_valid)($o_valid)(.*)$/s ) {
  1091. $arg =~ tr/_//d;
  1092. ($key, $arg, $rest) = ($1, $2, $+);
  1093. chop($key) if $key;
  1094. unshift (@$argv, $starter.$rest) if defined $rest && $rest ne '';
  1095. }
  1096. elsif ( $arg =~ /^$o_valid$/ ) {
  1097. $arg =~ tr/_//d;
  1098. }
  1099. else {
  1100. if ( defined $optarg || $mand ) {
  1101. if ( $passthrough ) {
  1102. unshift (@$argv, defined $rest ? $starter.$rest : $arg)
  1103. unless defined $optarg;
  1104. return (0);
  1105. }
  1106. warn ("Value \"", $arg, "\" invalid for option ",
  1107. $opt, " (real number expected)\n");
  1108. $error++;
  1109. # Push back.
  1110. unshift (@$argv, $starter.$rest) if defined $rest;
  1111. return (1, undef);
  1112. }
  1113. else {
  1114. # Push back.
  1115. unshift (@$argv, defined $rest ? $starter.$rest : $arg);
  1116. # Supply default value.
  1117. $arg = 0.0;
  1118. }
  1119. }
  1120. }
  1121. else {
  1122. die("Getopt::Long internal error (Can't happen)\n");
  1123. }
  1124. return (1, $opt, $ctl, $arg, $key);
  1125. }
  1126. sub ValidValue ($$$$$) {
  1127. my ($ctl, $arg, $mand, $argend, $prefix) = @_;
  1128. if ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
  1129. return 0 unless $arg =~ /[^=]+=(.*)/;
  1130. $arg = $1;
  1131. }
  1132. my $type = $ctl->[CTL_TYPE];
  1133. if ( $type eq 's' ) { # string
  1134. # A mandatory string takes anything.
  1135. return (1) if $mand;
  1136. return (1) if $arg eq "-";
  1137. # Check for option or option list terminator.
  1138. return 0 if $arg eq $argend || $arg =~ /^$prefix.+/;
  1139. return 1;
  1140. }
  1141. elsif ( $type eq 'i' # numeric/integer
  1142. || $type eq 'I' # numeric/integer w/ incr default
  1143. || $type eq 'o' ) { # dec/oct/hex/bin value
  1144. my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT;
  1145. return $arg =~ /^$o_valid$/si;
  1146. }
  1147. elsif ( $type eq 'f' ) { # real number, int is also ok
  1148. # We require at least one digit before a point or 'e',
  1149. # and at least one digit following the point and 'e'.
  1150. # [-]NN[.NN][eNN]
  1151. my $o_valid = PAT_FLOAT;
  1152. return $arg =~ /^$o_valid$/;
  1153. }
  1154. die("ValidValue: Cannot happen\n");
  1155. }
  1156. # Getopt::Long Configuration.
  1157. sub Configure (@) {
  1158. my (@options) = @_;
  1159. my $prevconfig =
  1160. [ $error, $debug, $major_version, $minor_version,
  1161. $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
  1162. $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help,
  1163. $longprefix, $bundling_values ];
  1164. if ( ref($options[0]) eq 'ARRAY' ) {
  1165. ( $error, $debug, $major_version, $minor_version,
  1166. $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
  1167. $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help,
  1168. $longprefix, $bundling_values ) = @{shift(@options)};
  1169. }
  1170. my $opt;
  1171. foreach $opt ( @options ) {
  1172. my $try = lc ($opt);
  1173. my $action = 1;
  1174. if ( $try =~ /^no_?(.*)$/s ) {
  1175. $action = 0;
  1176. $try = $+;
  1177. }
  1178. if ( ($try eq 'default' or $try eq 'defaults') && $action ) {
  1179. ConfigDefaults ();
  1180. }
  1181. elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) {
  1182. local $ENV{POSIXLY_CORRECT};
  1183. $ENV{POSIXLY_CORRECT} = 1 if $action;
  1184. ConfigDefaults ();
  1185. }
  1186. elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
  1187. $autoabbrev = $action;
  1188. }
  1189. elsif ( $try eq 'getopt_compat' ) {
  1190. $getopt_compat = $action;
  1191. $genprefix = $action ? "(--|-|\\+)" : "(--|-)";
  1192. }
  1193. elsif ( $try eq 'gnu_getopt' ) {
  1194. if ( $action ) {
  1195. $gnu_compat = 1;
  1196. $bundling = 1;
  1197. $getopt_compat = 0;
  1198. $genprefix = "(--|-)";
  1199. $order = $PERMUTE;
  1200. $bundling_values = 0;
  1201. }
  1202. }
  1203. elsif ( $try eq 'gnu_compat' ) {
  1204. $gnu_compat = $action;
  1205. }
  1206. elsif ( $try =~ /^(auto_?)?version$/ ) {
  1207. $auto_version = $action;
  1208. }
  1209. elsif ( $try =~ /^(auto_?)?help$/ ) {
  1210. $auto_help = $action;
  1211. }
  1212. elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
  1213. $ignorecase = $action;
  1214. }
  1215. elsif ( $try eq 'ignorecase_always' or $try eq 'ignore_case_always' ) {
  1216. $ignorecase = $action ? 2 : 0;
  1217. }
  1218. elsif ( $try eq 'bundling' ) {
  1219. $bundling = $action;
  1220. $bundling_values = 0 if $action;
  1221. }
  1222. elsif ( $try eq 'bundling_override' ) {
  1223. $bundling = $action ? 2 : 0;
  1224. $bundling_values = 0 if $action;
  1225. }
  1226. elsif ( $try eq 'bundling_values' ) {
  1227. $bundling_values = $action;
  1228. $bundling = 0 if $action;
  1229. }
  1230. elsif ( $try eq 'require_order' ) {
  1231. $order = $action ? $REQUIRE_ORDER : $PERMUTE;
  1232. }
  1233. elsif ( $try eq 'permute' ) {
  1234. $order = $action ? $PERMUTE : $REQUIRE_ORDER;
  1235. }
  1236. elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
  1237. $passthrough = $action;
  1238. }
  1239. elsif ( $try =~ /^prefix=(.+)$/ && $action ) {
  1240. $genprefix = $1;
  1241. # Turn into regexp. Needs to be parenthesized!
  1242. $genprefix = "(" . quotemeta($genprefix) . ")";
  1243. eval { '' =~ /$genprefix/; };
  1244. die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@;
  1245. }
  1246. elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {
  1247. $genprefix = $1;
  1248. # Parenthesize if needed.
  1249. $genprefix = "(" . $genprefix . ")"
  1250. unless $genprefix =~ /^\(.*\)$/;
  1251. eval { '' =~ m"$genprefix"; };
  1252. die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@;
  1253. }
  1254. elsif ( $try =~ /^long_prefix_pattern=(.+)$/ && $action ) {
  1255. $longprefix = $1;
  1256. # Parenthesize if needed.
  1257. $longprefix = "(" . $longprefix . ")"
  1258. unless $longprefix =~ /^\(.*\)$/;
  1259. eval { '' =~ m"$longprefix"; };
  1260. die("Getopt::Long: invalid long prefix pattern \"$longprefix\"\n") if $@;
  1261. }
  1262. elsif ( $try eq 'debug' ) {
  1263. $debug = $action;
  1264. }
  1265. else {
  1266. die("Getopt::Long: unknown or erroneous config parameter \"$opt\"\n")
  1267. }
  1268. }
  1269. $prevconfig;
  1270. }
  1271. # Deprecated name.
  1272. sub config (@) {
  1273. Configure (@_);
  1274. }
  1275. # Issue a standard message for --version.
  1276. #
  1277. # The arguments are mostly the same as for Pod::Usage::pod2usage:
  1278. #
  1279. # - a number (exit value)
  1280. # - a string (lead in message)
  1281. # - a hash with options. See Pod::Usage for details.
  1282. #
  1283. sub VersionMessage(@) {
  1284. # Massage args.
  1285. my $pa = setup_pa_args("version", @_);
  1286. my $v = $main::VERSION;
  1287. my $fh = $pa->{-output} ||
  1288. ($pa->{-exitval} eq "NOEXIT" || $pa->{-exitval} < 2) ? \*STDOUT : \*STDERR;
  1289. print $fh (defined($pa->{-message}) ? $pa->{-message} : (),
  1290. $0, defined $v ? " version $v" : (),
  1291. "\n",
  1292. "(", __PACKAGE__, "::", "GetOptions",
  1293. " version ",
  1294. defined($Getopt::Long::VERSION_STRING)
  1295. ? $Getopt::Long::VERSION_STRING : $VERSION, ";",
  1296. " Perl version ",
  1297. $] >= 5.006 ? sprintf("%vd", $^V) : $],
  1298. ")\n");
  1299. exit($pa->{-exitval}) unless $pa->{-exitval} eq "NOEXIT";
  1300. }
  1301. # Issue a standard message for --help.
  1302. #
  1303. # The arguments are the same as for Pod::Usage::pod2usage:
  1304. #
  1305. # - a number (exit value)
  1306. # - a string (lead in message)
  1307. # - a hash with options. See Pod::Usage for details.
  1308. #
  1309. sub HelpMessage(@) {
  1310. eval {
  1311. require Pod::Usage;
  1312. import Pod::Usage;
  1313. 1;
  1314. } || die("Cannot provide help: cannot load Pod::Usage\n");
  1315. # Note that pod2usage will issue a warning if -exitval => NOEXIT.
  1316. pod2usage(setup_pa_args("help", @_));
  1317. }
  1318. # Helper routine to set up a normalized hash ref to be used as
  1319. # argument to pod2usage.
  1320. sub setup_pa_args($@) {
  1321. my $tag = shift; # who's calling
  1322. # If called by direct binding to an option, it will get the option
  1323. # name and value as arguments. Remove these, if so.
  1324. @_ = () if @_ == 2 && $_[0] eq $tag;
  1325. my $pa;
  1326. if ( @_ > 1 ) {
  1327. $pa = { @_ };
  1328. }
  1329. else {
  1330. $pa = shift || {};
  1331. }
  1332. # At this point, $pa can be a number (exit value), string
  1333. # (message) or hash with options.
  1334. if ( UNIVERSAL::isa($pa, 'HASH') ) {
  1335. # Get rid of -msg vs. -message ambiguity.
  1336. $pa->{-message} = $pa->{-msg};
  1337. delete($pa->{-msg});
  1338. }
  1339. elsif ( $pa =~ /^-?\d+$/ ) {
  1340. $pa = { -exitval => $pa };
  1341. }
  1342. else {
  1343. $pa = { -message => $pa };
  1344. }
  1345. # These are _our_ defaults.
  1346. $pa->{-verbose} = 0 unless exists($pa->{-verbose});
  1347. $pa->{-exitval} = 0 unless exists($pa->{-exitval});
  1348. $pa;
  1349. }
  1350. # Sneak way to know what version the user requested.
  1351. sub VERSION {
  1352. $requested_version = $_[1];
  1353. shift->SUPER::VERSION(@_);
  1354. }
  1355. package Getopt::Long::CallBack;
  1356. sub new {
  1357. my ($pkg, %atts) = @_;
  1358. bless { %atts }, $pkg;
  1359. }
  1360. sub name {
  1361. my $self = shift;
  1362. ''.$self->{name};
  1363. }
  1364. use overload
  1365. # Treat this object as an ordinary string for legacy API.
  1366. '""' => \&name,
  1367. fallback => 1;
  1368. 1;
  1369. ################ Documentation ################
  1370. =head1 NAME
  1371. Getopt::Long - Extended processing of command line options
  1372. =head1 SYNOPSIS
  1373. use Getopt::Long;
  1374. my $data = "file.dat";
  1375. my $length = 24;
  1376. my $verbose;
  1377. GetOptions ("length=i" => \$length, # numeric
  1378. "file=s" => \$data, # string
  1379. "verbose" => \$verbose) # flag
  1380. or die("Error in command line arguments\n");
  1381. =head1 DESCRIPTION
  1382. The Getopt::Long module implements an extended getopt function called
  1383. GetOptions(). It parses the command line from C<@ARGV>, recognizing
  1384. and removing specified options and their possible values.
  1385. This function adheres to the POSIX syntax for command
  1386. line options, with GNU extensions. In general, this means that options
  1387. have long names instead of single letters, and are introduced with a
  1388. double dash "--". Support for bundling of command line options, as was
  1389. the case with the more traditional single-letter approach, is provided
  1390. but not enabled by default.
  1391. =head1 Command Line Options, an Introduction
  1392. Command line operated programs traditionally take their arguments from
  1393. the command line, for example filenames or other information that the
  1394. program needs to know. Besides arguments, these programs often take
  1395. command line I<options> as well. Options are not necessary for the
  1396. program to work, hence the name 'option', but are used to modify its
  1397. default behaviour. For example, a program could do its job quietly,
  1398. but with a suitable option it could provide verbose information about
  1399. what it did.
  1400. Command line options come in several flavours. Historically, they are
  1401. preceded by a single dash C<->, and consist of a single letter.
  1402. -l -a -c
  1403. Usually, these single-character options can be bundled:
  1404. -lac
  1405. Options can have values, the value is placed after the option
  1406. character. Sometimes with whitespace in between, sometimes not:
  1407. -s 24 -s24
  1408. Due to the very cryptic nature of these options, another style was
  1409. developed that used long names. So instead of a cryptic C<-l> one
  1410. could use the more descriptive C<--long>. To distinguish between a
  1411. bundle of single-character options and a long one, two dashes are used
  1412. to precede the option name. Early implementations of long options used
  1413. a plus C<+> instead. Also, option values could be specified either
  1414. like
  1415. --size=24
  1416. or
  1417. --size 24
  1418. The C<+> form is now obsolete and strongly deprecated.
  1419. =head1 Getting Started with Getopt::Long
  1420. Getopt::Long is the Perl5 successor of C<newgetopt.pl>. This was the
  1421. first Perl module that provided support for handling the new style of
  1422. command line options, in particular long option names, hence the Perl5
  1423. name Getopt::Long. This module also supports single-character options
  1424. and bundling.
  1425. To use Getopt::Long from a Perl program, you must include the
  1426. following line in your Perl program:
  1427. use Getopt::Long;
  1428. This will load the core of the Getopt::Long module and prepare your
  1429. program for using it. Most of the actual Getopt::Long code is not
  1430. loaded until you really call one of its functions.
  1431. In the default configuration, options names may be abbreviated to
  1432. uniqueness, case does not matter, and a single dash is sufficient,
  1433. even for long option names. Also, options may be placed between
  1434. non-option arguments. See L<Configuring Getopt::Long> for more
  1435. details on how to configure Getopt::Long.
  1436. =head2 Simple options
  1437. The most simple options are the ones that take no values. Their mere
  1438. presence on the command line enables the option. Popular examples are:
  1439. --all --verbose --quiet --debug
  1440. Handling simple options is straightforward:
  1441. my $verbose = ''; # option variable with default value (false)
  1442. my $all = ''; # option variable with default value (false)
  1443. GetOptions ('verbose' => \$verbose, 'all' => \$all);
  1444. The call to GetOptions() parses the command line arguments that are
  1445. present in C<@ARGV> and sets the option variable to the value C<1> if
  1446. the option did occur on the command line. Otherwise, the option
  1447. variable is not touched. Setting the option value to true is often
  1448. called I<enabling> the option.
  1449. The option name as specified to the GetOptions() function is called
  1450. the option I<specification>. Later we'll see that this specification
  1451. can contain more than just the option name. The reference to the
  1452. variable is called the option I<destination>.
  1453. GetOptions() will return a true value if the command line could be
  1454. processed successfully. Otherwise, it will write error messages using
  1455. die() and warn(), and return a false result.
  1456. =head2 A little bit less simple options
  1457. Getopt::Long supports two useful variants of simple options:
  1458. I<negatable> options and I<incremental> options.
  1459. A negatable option is specified with an exclamation mark C<!> after the
  1460. option name:
  1461. my $verbose = ''; # option variable with default value (false)
  1462. GetOptions ('verbose!' => \$verbose);
  1463. Now, using C<--verbose> on the command line will enable C<$verbose>,
  1464. as expected. But it is also allowed to use C<--noverbose>, which will
  1465. disable C<$verbose> by setting its value to C<0>. Using a suitable
  1466. default value, the program can find out whether C<$verbose> is false
  1467. by default, or disabled by using C<--noverbose>.
  1468. An incremental option is specified with a plus C<+> after the
  1469. option name:
  1470. my $verbose = ''; # option variable with default value (false)
  1471. GetOptions ('verbose+' => \$verbose);
  1472. Using C<--verbose> on the command line will increment the value of
  1473. C<$verbose>. This way the program can keep track of how many times the
  1474. option occurred on the command line. For example, each occurrence of
  1475. C<--verbose> could increase the verbosity level of the program.
  1476. =head2 Mixing command line option with other arguments
  1477. Usually programs take command line options as well as other arguments,
  1478. for example, file names. It is good practice to always specify the
  1479. options first, and the other arguments last. Getopt::Long will,
  1480. however, allow the options and arguments to be mixed and 'filter out'
  1481. all the options before passing the rest of the arguments to the
  1482. program. To stop Getopt::Long from processing further arguments,
  1483. insert a double dash C<--> on the command line:
  1484. --size 24 -- --all
  1485. In this example, C<--all> will I<not> be treated as an option, but
  1486. passed to the program unharmed, in C<@ARGV>.
  1487. =head2 Options with values
  1488. For options that take values it must be specified whether the option
  1489. value is required or not, and what kind of value the option expects.
  1490. Three kinds of values are supported: integer numbers, floating point
  1491. numbers, and strings.
  1492. If the option value is required, Getopt::Long will take the
  1493. command line argument that follows the option and assign this to the
  1494. option variable. If, however, the option value is specified as
  1495. optional, this will only be done if that value does not look like a
  1496. valid command line option itself.
  1497. my $tag = ''; # option variable with default value
  1498. GetOptions ('tag=s' => \$tag);
  1499. In the option specification, the option name is followed by an equals
  1500. sign C<=> and the letter C<s>. The equals sign indicates that this
  1501. option requires a value. The letter C<s> indicates that this value is
  1502. an arbitrary string. Other possible value types are C<i> for integer
  1503. values, and C<f> for floating point values. Using a colon C<:> instead
  1504. of the equals sign indicates that the option value is optional. In
  1505. this case, if no suitable value is supplied, string valued options get
  1506. an empty string C<''> assigned, while numeric options are set to C<0>.
  1507. =head2 Options with multiple values
  1508. Options sometimes take several values. For example, a program could
  1509. use multiple directories to search for library files:
  1510. --library lib/stdlib --library lib/extlib
  1511. To accomplish this behaviour, simply specify an array reference as the
  1512. destination for the option:
  1513. GetOptions ("library=s" => \@libfiles);
  1514. Alternatively, you can specify that the option can have multiple
  1515. values by adding a "@", and pass a scalar reference as the
  1516. destination:
  1517. GetOptions ("library=s@" => \$libfiles);
  1518. Used with the example above, C<@libfiles> (or C<@$libfiles>) would
  1519. contain two strings upon completion: C<"lib/stdlib"> and
  1520. C<"lib/extlib">, in that order. It is also possible to specify that
  1521. only integer or floating point numbers are acceptable values.
  1522. Often it is useful to allow comma-separated lists of values as well as
  1523. multiple occurrences of the options. This is easy using Perl's split()
  1524. and join() operators:
  1525. GetOptions ("library=s" => \@libfiles);
  1526. @libfiles = split(/,/,join(',',@libfiles));
  1527. Of course, it is important to choose the right separator string for
  1528. each purpose.
  1529. Warning: What follows is an experimental feature.
  1530. Options can take multiple values at once, for example
  1531. --coordinates 52.2 16.4 --rgbcolor 255 255 149
  1532. This can be accomplished by adding a repeat specifier to the option
  1533. specification. Repeat specifiers are very similar to the C<{...}>
  1534. repeat specifiers that can be used with regular expression patterns.
  1535. For example, the above command line would be handled as follows:
  1536. GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);
  1537. The destination for the option must be an array or array reference.
  1538. It is also possible to specify the minimal and maximal number of
  1539. arguments an option takes. C<foo=s{2,4}> indicates an option that
  1540. takes at least two and at most 4 arguments. C<foo=s{1,}> indicates one
  1541. or more values; C<foo:s{,}> indicates zero or more option values.
  1542. =head2 Options with hash values
  1543. If the option destination is a reference to a hash, the option will
  1544. take, as value, strings of the form I<key>C<=>I<value>. The value will
  1545. be stored with the specified key in the hash.
  1546. GetOptions ("define=s" => \%defines);
  1547. Alternatively you can use:
  1548. GetOptions ("define=s%" => \$defines);
  1549. When used with command line options:
  1550. --define os=linux --define vendor=redhat
  1551. the hash C<%defines> (or C<%$defines>) will contain two keys, C<"os">
  1552. with value C<"linux"> and C<"vendor"> with value C<"redhat">. It is
  1553. also possible to specify that only integer or floating point numbers
  1554. are acceptable values. The keys are always taken to be strings.
  1555. =head2 User-defined subroutines to handle options
  1556. Ultimate control over what should be done when (actually: each time)
  1557. an option is encountered on the command line can be achieved by
  1558. designating a reference to a subroutine (or an anonymous subroutine)
  1559. as the option destination. When GetOptions() encounters the option, it
  1560. will call the subroutine with two or three arguments. The first
  1561. argument is the name of the option. (Actually, it is an object that
  1562. stringifies to the name of the option.) For a scalar or array destination,
  1563. the second argument is the value to be stored. For a hash destination,
  1564. the second argument is the key to the hash, and the third argument
  1565. the value to be stored. It is up to the subroutine to store the value,
  1566. or do whatever it thinks is appropriate.
  1567. A trivial application of this mechanism is to implement options that
  1568. are related to each other. For example:
  1569. my $verbose = ''; # option variable with default value (false)
  1570. GetOptions ('verbose' => \$verbose,
  1571. 'quiet' => sub { $verbose = 0 });
  1572. Here C<--verbose> and C<--quiet> control the same variable
  1573. C<$verbose>, but with opposite values.
  1574. If the subroutine needs to signal an error, it should call die() with
  1575. the desired error message as its argument. GetOptions() will catch the
  1576. die(), issue the error message, and record that an error result must
  1577. be returned upon completion.
  1578. If the text of the error message starts with an exclamation mark C<!>
  1579. it is interpreted specially by GetOptions(). There is currently one
  1580. special command implemented: C<die("!FINISH")> will cause GetOptions()
  1581. to stop processing options, as if it encountered a double dash C<-->.
  1582. In version 2.37 the first argument to the callback function was
  1583. changed from string to object. This was done to make room for
  1584. extensions and more detailed control. The object stringifies to the
  1585. option name so this change should not introduce compatibility
  1586. problems.
  1587. Here is an example of how to access the option name and value from within
  1588. a subroutine:
  1589. GetOptions ('opt=i' => \&handler);
  1590. sub handler {
  1591. my ($opt_name, $opt_value) = @_;
  1592. print("Option name is $opt_name and value is $opt_value\n");
  1593. }
  1594. =head2 Options with multiple names
  1595. Often it is user friendly to supply alternate mnemonic names for
  1596. options. For example C<--height> could be an alternate name for
  1597. C<--length>. Alternate names can be included in the option
  1598. specification, separated by vertical bar C<|> characters. To implement
  1599. the above example:
  1600. GetOptions ('length|height=f' => \$length);
  1601. The first name is called the I<primary> name, the other names are
  1602. called I<aliases>. When using a hash to store options, the key will
  1603. always be the primary name.
  1604. Multiple alternate names are possible.
  1605. =head2 Case and abbreviations
  1606. Without additional configuration, GetOptions() will ignore the case of
  1607. option names, and allow the options to be abbreviated to uniqueness.
  1608. GetOptions ('length|height=f' => \$length, "head" => \$head);
  1609. This call will allow C<--l> and C<--L> for the length option, but
  1610. requires a least C<--hea> and C<--hei> for the head and height options.
  1611. =head2 Summary of Option Specifications
  1612. Each option specifier consists of two parts: the name specification
  1613. and the argument specification.
  1614. The name specification contains the name of the option, optionally
  1615. followed by a list of alternative names separated by vertical bar
  1616. characters.
  1617. length option name is "length"
  1618. length|size|l name is "length", aliases are "size" and "l"
  1619. The argument specification is optional. If omitted, the option is
  1620. considered boolean, a value of 1 will be assigned when the option is
  1621. used on the command line.
  1622. The argument specification can be
  1623. =over 4
  1624. =item !
  1625. The option does not take an argument and may be negated by prefixing
  1626. it with "no" or "no-". E.g. C<"foo!"> will allow C<--foo> (a value of
  1627. 1 will be assigned) as well as C<--nofoo> and C<--no-foo> (a value of
  1628. 0 will be assigned). If the option has aliases, this applies to the
  1629. aliases as well.
  1630. Using negation on a single letter option when bundling is in effect is
  1631. pointless and will result in a warning.
  1632. =item +
  1633. The option does not take an argument and will be incremented by 1
  1634. every time it appears on the command line. E.g. C<"more+">, when used
  1635. with C<--more --more --more>, will increment the value three times,
  1636. resulting in a value of 3 (provided it was 0 or undefined at first).
  1637. The C<+> specifier is ignored if the option destination is not a scalar.
  1638. =item = I<type> [ I<desttype> ] [ I<repeat> ]
  1639. The option requires an argument of the given type. Supported types
  1640. are:
  1641. =over 4
  1642. =item s
  1643. String. An arbitrary sequence of characters. It is valid for the
  1644. argument to start with C<-> or C<-->.
  1645. =item i
  1646. Integer. An optional leading plus or minus sign, followed by a
  1647. sequence of digits.
  1648. =item o
  1649. Extended integer, Perl style. This can be either an optional leading
  1650. plus or minus sign, followed by a sequence of digits, or an octal
  1651. string (a zero, optionally followed by '0', '1', .. '7'), or a
  1652. hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case
  1653. insensitive), or a binary string (C<0b> followed by a series of '0'
  1654. and '1').
  1655. =item f
  1656. Real number. For example C<3.14>, C<-6.23E24> and so on.
  1657. =back
  1658. The I<desttype> can be C<@> or C<%> to specify that the option is
  1659. list or a hash valued. This is only needed when the destination for
  1660. the option value is not otherwise specified. It should be omitted when
  1661. not needed.
  1662. The I<repeat> specifies the number of values this option takes per
  1663. occurrence on the command line. It has the format C<{> [ I<min> ] [ C<,> [ I<max> ] ] C<}>.
  1664. I<min> denotes the minimal number of arguments. It defaults to 1 for
  1665. options with C<=> and to 0 for options with C<:>, see below. Note that
  1666. I<min> overrules the C<=> / C<:> semantics.
  1667. I<max> denotes the maximum number of arguments. It must be at least
  1668. I<min>. If I<max> is omitted, I<but the comma is not>, there is no
  1669. upper bound to the number of argument values taken.
  1670. =item : I<type> [ I<desttype> ]
  1671. Like C<=>, but designates the argument as optional.
  1672. If omitted, an empty string will be assigned to string values options,
  1673. and the value zero to numeric options.
  1674. Note that if a string argument starts with C<-> or C<-->, it will be
  1675. considered an option on itself.
  1676. =item : I<number> [ I<desttype> ]
  1677. Like C<:i>, but if the value is omitted, the I<number> will be assigned.
  1678. =item : + [ I<desttype> ]
  1679. Like C<:i>, but if the value is omitted, the current value for the
  1680. option will be incremented.
  1681. =back
  1682. =head1 Advanced Possibilities
  1683. =head2 Object oriented interface
  1684. Getopt::Long can be used in an object oriented way as well:
  1685. use Getopt::Long;
  1686. $p = Getopt::Long::Parser->new;
  1687. $p->configure(...configuration options...);
  1688. if ($p->getoptions(...options descriptions...)) ...
  1689. if ($p->getoptionsfromarray( \@array, ...options descriptions...)) ...
  1690. Configuration options can be passed to the constructor:
  1691. $p = new Getopt::Long::Parser
  1692. config => [...configuration options...];
  1693. =head2 Thread Safety
  1694. Getopt::Long is thread safe when using ithreads as of Perl 5.8. It is
  1695. I<not> thread safe when using the older (experimental and now
  1696. obsolete) threads implementation that was added to Perl 5.005.
  1697. =head2 Documentation and help texts
  1698. Getopt::Long encourages the use of Pod::Usage to produce help
  1699. messages. For example:
  1700. use Getopt::Long;
  1701. use Pod::Usage;
  1702. my $man = 0;
  1703. my $help = 0;
  1704. GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
  1705. pod2usage(1) if $help;
  1706. pod2usage(-exitval => 0, -verbose => 2) if $man;
  1707. __END__
  1708. =head1 NAME
  1709. sample - Using Getopt::Long and Pod::Usage
  1710. =head1 SYNOPSIS
  1711. sample [options] [file ...]
  1712. Options:
  1713. -help brief help message
  1714. -man full documentation
  1715. =head1 OPTIONS
  1716. =over 8
  1717. =item B<-help>
  1718. Print a brief help message and exits.
  1719. =item B<-man>
  1720. Prints the manual page and exits.
  1721. =back
  1722. =head1 DESCRIPTION
  1723. B<This program> will read the given input file(s) and do something
  1724. useful with the contents thereof.
  1725. =cut
  1726. See L<Pod::Usage> for details.
  1727. =head2 Parsing options from an arbitrary array
  1728. By default, GetOptions parses the options that are present in the
  1729. global array C<@ARGV>. A special entry C<GetOptionsFromArray> can be
  1730. used to parse options from an arbitrary array.
  1731. use Getopt::Long qw(GetOptionsFromArray);
  1732. $ret = GetOptionsFromArray(\@myopts, ...);
  1733. When used like this, options and their possible values are removed
  1734. from C<@myopts>, the global C<@ARGV> is not touched at all.
  1735. The following two calls behave identically:
  1736. $ret = GetOptions( ... );
  1737. $ret = GetOptionsFromArray(\@ARGV, ... );
  1738. This also means that a first argument hash reference now becomes the
  1739. second argument:
  1740. $ret = GetOptions(\%opts, ... );
  1741. $ret = GetOptionsFromArray(\@ARGV, \%opts, ... );
  1742. =head2 Parsing options from an arbitrary string
  1743. A special entry C<GetOptionsFromString> can be used to parse options
  1744. from an arbitrary string.
  1745. use Getopt::Long qw(GetOptionsFromString);
  1746. $ret = GetOptionsFromString($string, ...);
  1747. The contents of the string are split into arguments using a call to
  1748. C<Text::ParseWords::shellwords>. As with C<GetOptionsFromArray>, the
  1749. global C<@ARGV> is not touched.
  1750. It is possible that, upon completion, not all arguments in the string
  1751. have been processed. C<GetOptionsFromString> will, when called in list
  1752. context, return both the return status and an array reference to any
  1753. remaining arguments:
  1754. ($ret, $args) = GetOptionsFromString($string, ... );
  1755. If any arguments remain, and C<GetOptionsFromString> was not called in
  1756. list context, a message will be given and C<GetOptionsFromString> will
  1757. return failure.
  1758. As with GetOptionsFromArray, a first argument hash reference now
  1759. becomes the second argument.
  1760. =head2 Storing options values in a hash
  1761. Sometimes, for example when there are a lot of options, having a
  1762. separate variable for each of them can be cumbersome. GetOptions()
  1763. supports, as an alternative mechanism, storing options values in a
  1764. hash.
  1765. To obtain this, a reference to a hash must be passed I<as the first
  1766. argument> to GetOptions(). For each option that is specified on the
  1767. command line, the option value will be stored in the hash with the
  1768. option name as key. Options that are not actually used on the command
  1769. line will not be put in the hash, on other words,
  1770. C<exists($h{option})> (or defined()) can be used to test if an option
  1771. was used. The drawback is that warnings will be issued if the program
  1772. runs under C<use strict> and uses C<$h{option}> without testing with
  1773. exists() or defined() first.
  1774. my %h = ();
  1775. GetOptions (\%h, 'length=i'); # will store in $h{length}
  1776. For options that take list or hash values, it is necessary to indicate
  1777. this by appending an C<@> or C<%> sign after the type:
  1778. GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
  1779. To make things more complicated, the hash may contain references to
  1780. the actual destinations, for example:
  1781. my $len = 0;
  1782. my %h = ('length' => \$len);
  1783. GetOptions (\%h, 'length=i'); # will store in $len
  1784. This example is fully equivalent with:
  1785. my $len = 0;
  1786. GetOptions ('length=i' => \$len); # will store in $len
  1787. Any mixture is possible. For example, the most frequently used options
  1788. could be stored in variables while all other options get stored in the
  1789. hash:
  1790. my $verbose = 0; # frequently referred
  1791. my $debug = 0; # frequently referred
  1792. my %h = ('verbose' => \$verbose, 'debug' => \$debug);
  1793. GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
  1794. if ( $verbose ) { ... }
  1795. if ( exists $h{filter} ) { ... option 'filter' was specified ... }
  1796. =head2 Bundling
  1797. With bundling it is possible to set several single-character options
  1798. at once. For example if C<a>, C<v> and C<x> are all valid options,
  1799. -vax
  1800. will set all three.
  1801. Getopt::Long supports three styles of bundling. To enable bundling, a
  1802. call to Getopt::Long::Configure is required.
  1803. The simplest style of bundling can be enabled with:
  1804. Getopt::Long::Configure ("bundling");
  1805. Configured this way, single-character options can be bundled but long
  1806. options B<must> always start with a double dash C<--> to avoid
  1807. ambiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all valid
  1808. options,
  1809. -vax
  1810. will set C<a>, C<v> and C<x>, but
  1811. --vax
  1812. will set C<vax>.
  1813. The second style of bundling lifts this restriction. It can be enabled
  1814. with:
  1815. Getopt::Long::Configure ("bundling_override");
  1816. Now, C<-vax> will set the option C<vax>.
  1817. In all of the above cases, option values may be inserted in the
  1818. bundle. For example:
  1819. -h24w80
  1820. is equivalent to
  1821. -h 24 -w 80
  1822. A third style of bundling allows only values to be bundled with
  1823. options. It can be enabled with:
  1824. Getopt::Long::Configure ("bundling_values");
  1825. Now, C<-h24> will set the option C<h> to C<24>, but option bundles
  1826. like C<-vxa> and C<-h24w80> are flagged as errors.
  1827. Enabling C<bundling_values> will disable the other two styles of
  1828. bundling.
  1829. When configured for bundling, single-character options are matched
  1830. case sensitive while long options are matched case insensitive. To
  1831. have the single-character options matched case insensitive as well,
  1832. use:
  1833. Getopt::Long::Configure ("bundling", "ignorecase_always");
  1834. It goes without saying that bundling can be quite confusing.
  1835. =head2 The lonesome dash
  1836. Normally, a lone dash C<-> on the command line will not be considered
  1837. an option. Option processing will terminate (unless "permute" is
  1838. configured) and the dash will be left in C<@ARGV>.
  1839. It is possible to get special treatment for a lone dash. This can be
  1840. achieved by adding an option specification with an empty name, for
  1841. example:
  1842. GetOptions ('' => \$stdio);
  1843. A lone dash on the command line will now be a legal option, and using
  1844. it will set variable C<$stdio>.
  1845. =head2 Argument callback
  1846. A special option 'name' C<< <> >> can be used to designate a subroutine
  1847. to handle non-option arguments. When GetOptions() encounters an
  1848. argument that does not look like an option, it will immediately call this
  1849. subroutine and passes it one parameter: the argument name. Well, actually
  1850. it is an object that stringifies to the argument name.
  1851. For example:
  1852. my $width = 80;
  1853. sub process { ... }
  1854. GetOptions ('width=i' => \$width, '<>' => \&process);
  1855. When applied to the following command line:
  1856. arg1 --width=72 arg2 --width=60 arg3
  1857. This will call
  1858. C<process("arg1")> while C<$width> is C<80>,
  1859. C<process("arg2")> while C<$width> is C<72>, and
  1860. C<process("arg3")> while C<$width> is C<60>.
  1861. This feature requires configuration option B<permute>, see section
  1862. L<Configuring Getopt::Long>.
  1863. =head1 Configuring Getopt::Long
  1864. Getopt::Long can be configured by calling subroutine
  1865. Getopt::Long::Configure(). This subroutine takes a list of quoted
  1866. strings, each specifying a configuration option to be enabled, e.g.
  1867. C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does not
  1868. matter. Multiple calls to Configure() are possible.
  1869. Alternatively, as of version 2.24, the configuration options may be
  1870. passed together with the C<use> statement:
  1871. use Getopt::Long qw(:config no_ignore_case bundling);
  1872. The following options are available:
  1873. =over 12
  1874. =item default
  1875. This option causes all configuration options to be reset to their
  1876. default values.
  1877. =item posix_default
  1878. This option causes all configuration options to be reset to their
  1879. default values as if the environment variable POSIXLY_CORRECT had
  1880. been set.
  1881. =item auto_abbrev
  1882. Allow option names to be abbreviated to uniqueness.
  1883. Default is enabled unless environment variable
  1884. POSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.
  1885. =item getopt_compat
  1886. Allow C<+> to start options.
  1887. Default is enabled unless environment variable
  1888. POSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.
  1889. =item gnu_compat
  1890. C<gnu_compat> controls whether C<--opt=> is allowed, and what it should
  1891. do. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,
  1892. C<--opt=> will give option C<opt> and empty value.
  1893. This is the way GNU getopt_long() does it.
  1894. =item gnu_getopt
  1895. This is a short way of setting C<gnu_compat> C<bundling> C<permute>
  1896. C<no_getopt_compat>. With C<gnu_getopt>, command line handling should be
  1897. fully compatible with GNU getopt_long().
  1898. =item require_order
  1899. Whether command line arguments are allowed to be mixed with options.
  1900. Default is disabled unless environment variable
  1901. POSIXLY_CORRECT has been set, in which case C<require_order> is enabled.
  1902. See also C<permute>, which is the opposite of C<require_order>.
  1903. =item permute
  1904. Whether command line arguments are allowed to be mixed with options.
  1905. Default is enabled unless environment variable
  1906. POSIXLY_CORRECT has been set, in which case C<permute> is disabled.
  1907. Note that C<permute> is the opposite of C<require_order>.
  1908. If C<permute> is enabled, this means that
  1909. --foo arg1 --bar arg2 arg3
  1910. is equivalent to
  1911. --foo --bar arg1 arg2 arg3
  1912. If an argument callback routine is specified, C<@ARGV> will always be
  1913. empty upon successful return of GetOptions() since all options have been
  1914. processed. The only exception is when C<--> is used:
  1915. --foo arg1 --bar arg2 -- arg3
  1916. This will call the callback routine for arg1 and arg2, and then
  1917. terminate GetOptions() leaving C<"arg3"> in C<@ARGV>.
  1918. If C<require_order> is enabled, options processing
  1919. terminates when the first non-option is encountered.
  1920. --foo arg1 --bar arg2 arg3
  1921. is equivalent to
  1922. --foo -- arg1 --bar arg2 arg3
  1923. If C<pass_through> is also enabled, options processing will terminate
  1924. at the first unrecognized option, or non-option, whichever comes
  1925. first.
  1926. =item bundling (default: disabled)
  1927. Enabling this option will allow single-character options to be
  1928. bundled. To distinguish bundles from long option names, long options
  1929. I<must> be introduced with C<--> and bundles with C<->.
  1930. Note that, if you have options C<a>, C<l> and C<all>, and
  1931. auto_abbrev enabled, possible arguments and option settings are:
  1932. using argument sets option(s)
  1933. ------------------------------------------
  1934. -a, --a a
  1935. -l, --l l
  1936. -al, -la, -ala, -all,... a, l
  1937. --al, --all all
  1938. The surprising part is that C<--a> sets option C<a> (due to auto
  1939. completion), not C<all>.
  1940. Note: disabling C<bundling> also disables C<bundling_override>.
  1941. =item bundling_override (default: disabled)
  1942. If C<bundling_override> is enabled, bundling is enabled as with
  1943. C<bundling> but now long option names override option bundles.
  1944. Note: disabling C<bundling_override> also disables C<bundling>.
  1945. B<Note:> Using option bundling can easily lead to unexpected results,
  1946. especially when mixing long options and bundles. Caveat emptor.
  1947. =item ignore_case (default: enabled)
  1948. If enabled, case is ignored when matching option names. If, however,
  1949. bundling is enabled as well, single character options will be treated
  1950. case-sensitive.
  1951. With C<ignore_case>, option specifications for options that only
  1952. differ in case, e.g., C<"foo"> and C<"Foo">, will be flagged as
  1953. duplicates.
  1954. Note: disabling C<ignore_case> also disables C<ignore_case_always>.
  1955. =item ignore_case_always (default: disabled)
  1956. When bundling is in effect, case is ignored on single-character
  1957. options also.
  1958. Note: disabling C<ignore_case_always> also disables C<ignore_case>.
  1959. =item auto_version (default:disabled)
  1960. Automatically provide support for the B<--version> option if
  1961. the application did not specify a handler for this option itself.
  1962. Getopt::Long will provide a standard version message that includes the
  1963. program name, its version (if $main::VERSION is defined), and the
  1964. versions of Getopt::Long and Perl. The message will be written to
  1965. standard output and processing will terminate.
  1966. C<auto_version> will be enabled if the calling program explicitly
  1967. specified a version number higher than 2.32 in the C<use> or
  1968. C<require> statement.
  1969. =item auto_help (default:disabled)
  1970. Automatically provide support for the B<--help> and B<-?> options if
  1971. the application did not specify a handler for this option itself.
  1972. Getopt::Long will provide a help message using module L<Pod::Usage>. The
  1973. message, derived from the SYNOPSIS POD section, will be written to
  1974. standard output and processing will terminate.
  1975. C<auto_help> will be enabled if the calling program explicitly
  1976. specified a version number higher than 2.32 in the C<use> or
  1977. C<require> statement.
  1978. =item pass_through (default: disabled)
  1979. With C<pass_through> anything that is unknown, ambiguous or supplied with
  1980. an invalid option will not be flagged as an error. Instead the unknown
  1981. option(s) will be passed to the catchall C<< <> >> if present, otherwise
  1982. through to C<@ARGV>. This makes it possible to write wrapper scripts that
  1983. process only part of the user supplied command line arguments, and pass the
  1984. remaining options to some other program.
  1985. If C<require_order> is enabled, options processing will terminate at the
  1986. first unrecognized option, or non-option, whichever comes first and all
  1987. remaining arguments are passed to C<@ARGV> instead of the catchall
  1988. C<< <> >> if present. However, if C<permute> is enabled instead, results
  1989. can become confusing.
  1990. Note that the options terminator (default C<-->), if present, will
  1991. also be passed through in C<@ARGV>.
  1992. =item prefix
  1993. The string that starts options. If a constant string is not
  1994. sufficient, see C<prefix_pattern>.
  1995. =item prefix_pattern
  1996. A Perl pattern that identifies the strings that introduce options.
  1997. Default is C<--|-|\+> unless environment variable
  1998. POSIXLY_CORRECT has been set, in which case it is C<--|->.
  1999. =item long_prefix_pattern
  2000. A Perl pattern that allows the disambiguation of long and short
  2001. prefixes. Default is C<-->.
  2002. Typically you only need to set this if you are using nonstandard
  2003. prefixes and want some or all of them to have the same semantics as
  2004. '--' does under normal circumstances.
  2005. For example, setting prefix_pattern to C<--|-|\+|\/> and
  2006. long_prefix_pattern to C<--|\/> would add Win32 style argument
  2007. handling.
  2008. =item debug (default: disabled)
  2009. Enable debugging output.
  2010. =back
  2011. =head1 Exportable Methods
  2012. =over
  2013. =item VersionMessage
  2014. This subroutine provides a standard version message. Its argument can be:
  2015. =over 4
  2016. =item *
  2017. A string containing the text of a message to print I<before> printing
  2018. the standard message.
  2019. =item *
  2020. A numeric value corresponding to the desired exit status.
  2021. =item *
  2022. A reference to a hash.
  2023. =back
  2024. If more than one argument is given then the entire argument list is
  2025. assumed to be a hash. If a hash is supplied (either as a reference or
  2026. as a list) it should contain one or more elements with the following
  2027. keys:
  2028. =over 4
  2029. =item C<-message>
  2030. =item C<-msg>
  2031. The text of a message to print immediately prior to printing the
  2032. program's usage message.
  2033. =item C<-exitval>
  2034. The desired exit status to pass to the B<exit()> function.
  2035. This should be an integer, or else the string "NOEXIT" to
  2036. indicate that control should simply be returned without
  2037. terminating the invoking process.
  2038. =item C<-output>
  2039. A reference to a filehandle, or the pathname of a file to which the
  2040. usage message should be written. The default is C<\*STDERR> unless the
  2041. exit value is less than 2 (in which case the default is C<\*STDOUT>).
  2042. =back
  2043. You cannot tie this routine directly to an option, e.g.:
  2044. GetOptions("version" => \&VersionMessage);
  2045. Use this instead:
  2046. GetOptions("version" => sub { VersionMessage() });
  2047. =item HelpMessage
  2048. This subroutine produces a standard help message, derived from the
  2049. program's POD section SYNOPSIS using L<Pod::Usage>. It takes the same
  2050. arguments as VersionMessage(). In particular, you cannot tie it
  2051. directly to an option, e.g.:
  2052. GetOptions("help" => \&HelpMessage);
  2053. Use this instead:
  2054. GetOptions("help" => sub { HelpMessage() });
  2055. =back
  2056. =head1 Return values and Errors
  2057. Configuration errors and errors in the option definitions are
  2058. signalled using die() and will terminate the calling program unless
  2059. the call to Getopt::Long::GetOptions() was embedded in C<eval { ...
  2060. }>, or die() was trapped using C<$SIG{__DIE__}>.
  2061. GetOptions returns true to indicate success.
  2062. It returns false when the function detected one or more errors during
  2063. option parsing. These errors are signalled using warn() and can be
  2064. trapped with C<$SIG{__WARN__}>.
  2065. =head1 Legacy
  2066. The earliest development of C<newgetopt.pl> started in 1990, with Perl
  2067. version 4. As a result, its development, and the development of
  2068. Getopt::Long, has gone through several stages. Since backward
  2069. compatibility has always been extremely important, the current version
  2070. of Getopt::Long still supports a lot of constructs that nowadays are
  2071. no longer necessary or otherwise unwanted. This section describes
  2072. briefly some of these 'features'.
  2073. =head2 Default destinations
  2074. When no destination is specified for an option, GetOptions will store
  2075. the resultant value in a global variable named C<opt_>I<XXX>, where
  2076. I<XXX> is the primary name of this option. When a program executes
  2077. under C<use strict> (recommended), these variables must be
  2078. pre-declared with our() or C<use vars>.
  2079. our $opt_length = 0;
  2080. GetOptions ('length=i'); # will store in $opt_length
  2081. To yield a usable Perl variable, characters that are not part of the
  2082. syntax for variables are translated to underscores. For example,
  2083. C<--fpp-struct-return> will set the variable
  2084. C<$opt_fpp_struct_return>. Note that this variable resides in the
  2085. namespace of the calling program, not necessarily C<main>. For
  2086. example:
  2087. GetOptions ("size=i", "sizes=i@");
  2088. with command line "-size 10 -sizes 24 -sizes 48" will perform the
  2089. equivalent of the assignments
  2090. $opt_size = 10;
  2091. @opt_sizes = (24, 48);
  2092. =head2 Alternative option starters
  2093. A string of alternative option starter characters may be passed as the
  2094. first argument (or the first argument after a leading hash reference
  2095. argument).
  2096. my $len = 0;
  2097. GetOptions ('/', 'length=i' => $len);
  2098. Now the command line may look like:
  2099. /length 24 -- arg
  2100. Note that to terminate options processing still requires a double dash
  2101. C<-->.
  2102. GetOptions() will not interpret a leading C<< "<>" >> as option starters
  2103. if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as
  2104. option starters, use C<< "><" >>. Confusing? Well, B<using a starter
  2105. argument is strongly deprecated> anyway.
  2106. =head2 Configuration variables
  2107. Previous versions of Getopt::Long used variables for the purpose of
  2108. configuring. Although manipulating these variables still work, it is
  2109. strongly encouraged to use the C<Configure> routine that was introduced
  2110. in version 2.17. Besides, it is much easier.
  2111. =head1 Tips and Techniques
  2112. =head2 Pushing multiple values in a hash option
  2113. Sometimes you want to combine the best of hashes and arrays. For
  2114. example, the command line:
  2115. --list add=first --list add=second --list add=third
  2116. where each successive 'list add' option will push the value of add
  2117. into array ref $list->{'add'}. The result would be like
  2118. $list->{add} = [qw(first second third)];
  2119. This can be accomplished with a destination routine:
  2120. GetOptions('list=s%' =>
  2121. sub { push(@{$list{$_[1]}}, $_[2]) });
  2122. =head1 Troubleshooting
  2123. =head2 GetOptions does not return a false result when an option is not supplied
  2124. That's why they're called 'options'.
  2125. =head2 GetOptions does not split the command line correctly
  2126. The command line is not split by GetOptions, but by the command line
  2127. interpreter (CLI). On Unix, this is the shell. On Windows, it is
  2128. COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
  2129. It is important to know that these CLIs may behave different when the
  2130. command line contains special characters, in particular quotes or
  2131. backslashes. For example, with Unix shells you can use single quotes
  2132. (C<'>) and double quotes (C<">) to group words together. The following
  2133. alternatives are equivalent on Unix:
  2134. "two words"
  2135. 'two words'
  2136. two\ words
  2137. In case of doubt, insert the following statement in front of your Perl
  2138. program:
  2139. print STDERR (join("|",@ARGV),"\n");
  2140. to verify how your CLI passes the arguments to the program.
  2141. =head2 Undefined subroutine &main::GetOptions called
  2142. Are you running Windows, and did you write
  2143. use GetOpt::Long;
  2144. (note the capital 'O')?
  2145. =head2 How do I put a "-?" option into a Getopt::Long?
  2146. You can only obtain this using an alias, and Getopt::Long of at least
  2147. version 2.13.
  2148. use Getopt::Long;
  2149. GetOptions ("help|?"); # -help and -? will both set $opt_help
  2150. Other characters that can't appear in Perl identifiers are also supported
  2151. as aliases with Getopt::Long of at least version 2.39.
  2152. As of version 2.32 Getopt::Long provides auto-help, a quick and easy way
  2153. to add the options --help and -? to your program, and handle them.
  2154. See C<auto_help> in section L<Configuring Getopt::Long>.
  2155. =head1 AUTHOR
  2156. Johan Vromans <jvromans@squirrel.nl>
  2157. =head1 COPYRIGHT AND DISCLAIMER
  2158. This program is Copyright 1990,2015 by Johan Vromans.
  2159. This program is free software; you can redistribute it and/or
  2160. modify it under the terms of the Perl Artistic License or the
  2161. GNU General Public License as published by the Free Software
  2162. Foundation; either version 2 of the License, or (at your option) any
  2163. later version.
  2164. This program is distributed in the hope that it will be useful,
  2165. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2166. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2167. GNU General Public License for more details.
  2168. If you do not have a copy of the GNU General Public License write to
  2169. the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
  2170. MA 02139, USA.
  2171. =cut