Build.PL100644000766000024 45515104610653 16235 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602# ========================================================================= # THIS FILE IS AUTOMATICALLY GENERATED BY MINILLA. # DO NOT EDIT DIRECTLY. # ========================================================================= use 5.008_001; use strict; use Module::Build::Tiny 0.035; Build_PL(); Changes100644000766000024 676715104610653 16270 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602Revision history for Perl extension Getopt-EX-Hashed 1.0602 2025-11-11T10:36:26Z - improve error messages for better debugging - change translation engine from DeepL to GPT-5 for Japanese documentation - improve English documentation for better clarity and translation quality 1.0601 2024-04-30T02:12:00Z - update document 1.06 2024-04-29T12:34:52Z - Support "default => \$scalar" style option storage. I guess former Getopt::Long supported this. 1.0503 2022-08-28T13:14:36Z - defining existing function causes fatal error - DESTROY() removes accessors 1.0502 2022-08-26T06:45:25Z - improve code and document 1.0501 2022-08-23T01:05:14Z - update document structure 1.05 2022-08-22T07:50:55Z - make assignable accessor as a default action (is => 'rw') - introduce ACCESSOR_LVALUE parameter (default 1) 1.04 2022-08-21T09:37:10Z - introduce assignable accessor (is => 'lv') 1.03 2021-11-19T03:28:35Z - Make "default" parameter to take coderef for lazy evaluation. 1.02 2021-11-18T05:07:22Z - When the number of parameter is not even, first parameter is taken as an 'action' if it is coderef. 1.01 2021-11-08T06:41:52Z - getopt() takes arrayref and call GetOptionsFromArray(). 1.00 2021-10-25T12:46:24Z - Version 1.00 0.9922 2021-10-17T08:05:22Z - Deprecate "re" parameter. - Improve handling of DEFAULT config parameter. 0.9921 2021-10-13T00:26:37Z - Allow must parameter to take multiple codes. - Do not require Clone.pm - Fix bug of handling coderef in any param. 0.9920 2021-09-27T07:02:57Z - Introduce "any" validator. - Copy default data not to destroy DB. 0.9919 2021-09-17T06:52:33Z - Define accessor method only once. 0.9918 2021-09-12T03:01:33Z - Unlock keys of config hash just in case. - Support odd-number parameter for short-cut for option spec. 0.9917 2021-08-24T13:56:53Z - Update the configuration semantics. 0.9916 2021-08-24T03:12:10Z - Change reset behavior. - Pointer to the configuration is now stored in a object. 0.9915 2021-08-22T14:50:29Z - Implementation and document refine. 0.9914 2021-08-19T16:44:49Z - Intoduce "min", "max", "re" validation parameters. 0.9913 2021-08-18T08:49:22Z - Add REMOVE_UNDERSCORE config parameter. - Introduce new "must" parameter. 0.9912 2021-08-13T00:45:25Z - Fix default config access bug. 0.9911 2021-08-11T15:34:09Z - Fix bug when called by Getopt::EX::Hashed->new interface. 0.9910 2021-08-11T13:14:30Z - Make config data to be stored in caller space too. 0.9909 2021-08-09T23:59:42Z - Store member metadata in caller space so that the module can be used in multiple places. 0.9908 2021-08-09T02:51:02Z - Now 'is' parameter is required to generate accessor method. 0.9907 2021-08-08T08:00:30Z - Implement accessor method generation with ACCESSOR and ACCESSOR_PREFIX config parameter. 0.9906 2021-08-01T12:32:40Z - Update the way to use Getopt::Long interface and now default and action can co-exist. 0.9905 2021-07-31T12:10:33Z - Introduce RESET_AFTER_NEW config parameter with zero default. 0.9904 2021-07-30T16:48:14Z - introduce 'action' parameter. 0.9903 2021-07-29T09:37:48Z - avoid inheritance loop when called directly. 0.9902 2021-07-28T10:18:12Z - fix the problem of previous patch does not work for v5.14. 0.9901 2021-07-27T08:20:10Z - fix bug of mixed alias with option spec. 0.99 2021-07-25T15:57:41Z - initial release LICENSE100644000766000024 4376215104610653 16016 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602This software is copyright (c) 2021 by Kazumasa Utashiro . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2021 by Kazumasa Utashiro . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Suite 500, Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2021 by Kazumasa Utashiro . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End MANIFEST.SKIP100644000766000024 7715104610653 16617 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602docs/.*\.json docs/.*\.md docs/Makefile examples docker images META.json100644000766000024 372215104610653 16402 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602{ "abstract" : "Hash object automation for Getopt::Long", "author" : [ "Kazumasa Utashiro" ], "dynamic_config" : 0, "generated_by" : "Minilla/v3.1.28", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Getopt-EX-Hashed", "no_index" : { "directory" : [ "t", "xt", "inc", "share", "eg", "examples", "author", "builder" ] }, "prereqs" : { "configure" : { "requires" : { "Module::Build::Tiny" : "0.035" } }, "develop" : { "requires" : { "Test::CPAN::Meta" : "0", "Test::MinimumVersion::Fast" : "0.04", "Test::PAUSE::Permissions" : "0.07", "Test::Pod" : "1.41", "Test::Spellunker" : "v0.2.7" } }, "runtime" : { "requires" : { "List::Util" : "0", "perl" : "v5.14.0" } }, "test" : { "requires" : { "Getopt::Long" : "0", "Test::More" : "0.98" } } }, "provides" : { "Getopt::EX::Hashed" : { "file" : "lib/Getopt/EX/Hashed.pm", "version" : "1.0602" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/kaz-utashiro/Getopt-EX-Hashed/issues" }, "homepage" : "https://github.com/kaz-utashiro/Getopt-EX-Hashed", "repository" : { "type" : "git", "url" : "https://github.com/kaz-utashiro/Getopt-EX-Hashed.git", "web" : "https://github.com/kaz-utashiro/Getopt-EX-Hashed" } }, "version" : "1.0602", "x_authority" : "cpan:UTASHIRO", "x_contributors" : [ "Kazumasa Utashiro " ], "x_serialization_backend" : "JSON::PP version 4.16", "x_static_install" : 1 } README.JA.md100644000766000024 3420015104610653 16544 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602# NAME Getopt::EX::Hashed - Getopt::Long のためのハッシュオブジェクト自動化 # VERSION Version 1.0602 # SYNOPSIS # script/foo use App::foo; App::foo->new->run(); # lib/App/foo.pm package App::foo; use Getopt::EX::Hashed; { Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); has start => ' =i s begin ' , default => 1; has end => ' =i e ' ; has file => ' =s@ f ' , any => qr/^(?!\.)/; has score => ' =i ' , min => 0, max => 100; has answer => ' =i ' , must => sub { $_[1] == 42 }; has mouse => ' =s ' , any => [ 'Frankie', 'Benjy' ]; has question => ' =s ' , any => qr/^(life|universe|everything)$/i; } no Getopt::EX::Hashed; sub run { my $app = shift; use Getopt::Long; $app->getopt or pod2usage(); if ($app->answer == 42) { $app->question //= 'life'; ... # DESCRIPTION **Getopt::EX::Hashed** は、**Getopt::Long** および **Getopt::EX::Long** を含む互換モジュール向けに、コマンドラインオプション値を格納するハッシュオブジェクトの作成を自動化するモジュールです。モジュール名は **Getopt::EX** プレフィックスを共有しますが、現時点では **Getopt::EX** 内の他のモジュールから独立して動作します。 このモジュールの主目的は、初期化と仕様の定義を一箇所に統合することです。簡易な検証インターフェースも提供します。 `is` パラメータが与えられるとアクセサメソッドが自動生成されます。同名の関数がすでに定義されている場合、プログラムは致命的エラーとなります。オブジェクトが破棄されるとアクセサは削除されます。同時に複数のオブジェクトが存在する場合、問題が発生する可能性があります。 # FUNCTION ## **has** 次の形式でオプションパラメータを宣言します。かっこは見やすさのためのもので、省略可能です。 has option_name => ( param => value, ... ); 例えば、整数値を引数に取るオプション `--number` を定義し、`-n` としても使えるようにするには、次のようにします。 has number => spec => "=i n"; アクセサは最初の名前で作成されます。この例では、アクセサは `$app->number` として定義されます。 配列リファレンスを与えると、複数の名前を一度に宣言できます。 has [ 'left', 'right' ] => ( spec => "=i" ); 名前がプラス (`+`) で始まる場合、与えたパラメータは既存の設定を更新します。 has '+left' => ( default => 1 ); `spec` パラメータについては、先頭のパラメータであればラベルを省略できます。 has left => "=i", default => 1; パラメータ数が奇数の場合、最初のパラメータは暗黙のラベルを持つものとして扱われます。コードリファレンスなら `action`、それ以外なら `spec` です。 利用可能なパラメータは以下の通りです。 - \[ **spec** => \] _string_ オプション仕様を与えます。`spec =>` ラベルは最初のパラメータである場合に限り省略できます。 _string_ では、オプション仕様とエイリアス名は空白で区切られ、順序は任意です。 整数を値に取る `--start` というオプションを用意し、`-s` や `--begin` という名前でも使えるようにするには、次のように宣言します。 has start => "=i s begin"; 上記の宣言は次の文字列にコンパイルされます。 start|s|begin=i これは `Getopt::Long` の定義に準拠しています。もちろん、次のように書くこともできます: has start => "s|begin=i"; 名前やエイリアスにアンダースコア (`_`) が含まれている場合、アンダースコアをダッシュ (`-`) に置き換えた別のエイリアス名が定義されます。 has a_to_z => "=s"; 上記の宣言は次の文字列にコンパイルされます。 a_to_z|a-to-z=s オプション spec が不要な場合は、空文字列(または空白のみの文字列)を値として与えてください。spec 文字列がなければ、そのメンバーはオプションとして扱われません。 - **alias** => _string_ 追加のエイリアス名は **alias** パラメータでも指定できます。`spec` パラメータ内のものと違いはありません。 has start => "=i", alias => "s begin"; - **is** => `ro` | `rw` アクセサメソッドを生成するには、`is` パラメータが必要です。値は読み取り専用なら `ro`、読み書き可能なら `rw` を設定します。 読み書き可能アクセサは lvalue 属性を持つため、代入できます。次のように使えます。 $app->foo //= 1; これは以下のように書くよりもずっと簡単です。 $app->foo(1) unless defined $app->foo; 以降のすべてのメンバーにアクセサを作成したい場合は、`configure` で `DEFAULT` パラメータを設定してください。 Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); 代入可能なアクセサが好きでない場合は、`ACCESSOR_LVALUE` パラメータを 0 に設定してください。アクセサは `new` の時点で生成されるため、この値はすべてのメンバーに対して有効です。 - **default** => _value_ | _coderef_ デフォルト値を設定します。デフォルトが与えられない場合、メンバーは `undef` として初期化されます。 値が ARRAY または HASH へのリファレンスである場合、各 `new` 呼び出しで浅いコピーが作成されます。これは、リファレンス自体はコピーされますが、内容は共有されることを意味します。配列やハッシュの内容を変更すると、すべてのインスタンスに影響します。 コードリファレンスが与えられた場合、**new** の時点で呼び出され、デフォルト値を取得します。これは、宣言時ではなく実行時に値を評価したい場合に有効です。デフォルトのアクションを定義したい場合は **action** パラメータを使用してください。コードリファレンス自体を初期値として設定したい場合は、コードリファレンスを返すコードリファレンスを指定する必要があります。 SCALAR へのリファレンスが与えられた場合、オプション値はハッシュオブジェクトのメンバーではなく、そのリファレンスが指すデータに保存されます。この場合、ハッシュメンバーにアクセスしても期待する値は得られません。 - \[ **action** => \] _coderef_ パラメータ `action` はオプションを処理するために呼び出されるコードリファレンスを受け取ります。`action =>` ラベルは、最初のパラメータである場合に限り省略できます。 呼び出し時には、ハッシュオブジェクトが `$_` として渡されます。 has [ qw(left right both) ] => '=i'; has "+both" => sub { $_->{left} = $_->{right} = $_[1]; }; `"<>"` を使って非オプション引数を処理できます。この場合、spec パラメータは重要ではなく、必須でもありません。 has ARGV => default => []; has "<>" => sub { push @{$_->{ARGV}}, $_[0]; }; 以下のパラメータはすべてデータ検証用です。まず `must` は汎用バリデータで、あらゆることを実装できます。他は一般的なルールのためのショートカットです。 - **must** => _coderef_ | \[ _coderef_ ... \] パラメータ `must` はオプション値を検証するコードリファレンスを受け取ります。引数は `action` と同じで、真偽値を返します。次の例では、オプション **--answer** は有効な値として 42 のみを受け付けます。 has answer => '=i', must => sub { $_[1] == 42 }; 複数のコードリファレンスが与えられた場合、すべてのコードが真を返さなければなりません。 has answer => '=i', must => [ sub { $_[1] >= 42 }, sub { $_[1] <= 42 } ]; - **min** => _number_ - **max** => _number_ 引数の最小値と最大値の制限を設定します。 - **any** => _arrayref_ | qr/_regex_/ | _coderef_ 有効な文字列パラメータのリストを設定します。各項目は文字列、正規表現リファレンス、またはコードリファレンスにできます。引数が、与えられたリストのいずれかの項目と同一、または一致する場合に有効です。値が arrayref でない場合は、単一項目のリスト(通常は regexpref か coderef)として扱われます。 以下の宣言はほぼ同等ですが、2 つ目は大文字小文字を区別しません。 has question => '=s', any => [ 'life', 'universe', 'everything' ]; has question => '=s', any => qr/^(life|universe|everything)$/i; オプション引数を使用している場合は、デフォルト値をリストに含めるのを忘れないでください。そうしないと検証エラーになります。 has question => ':s', any => [ 'life', 'universe', 'everything', '' ]; # METHOD ## **new** 新しいハッシュオブジェクトを作成するクラスメソッド。すべてのメンバーをデフォルト値で初期化し、設定に従ってアクセサメソッドを作成します。bless されたハッシュリファレンスを返します。LOCK\_KEYS が有効な場合、ハッシュキーはロックされます。 ## **optspec** `GetOptions` 関数に渡すことができるオプション仕様のリストを返します。 GetOptions($obj->optspec) `GetOptions` は、最初の引数としてハッシュリファレンスを与えることで値をハッシュに格納する機能を持ちますが、必須ではありません。 ## **getopt** \[ _arrayref_ \] オプションを処理するために、呼び出し元のコンテキストで定義された適切な関数を呼び出します。 $obj->getopt $obj->getopt(\@argv); 上記の例は、以下のコードに対するショートカットです。 GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) ## **use\_keys** _keys_ LOCK\_KEYS が有効なとき、存在しないメンバーへのアクセスはエラーになります。アクセス前に新しいメンバーキーを宣言するにはこのメソッドを使用してください。 $obj->use_keys( qw(foo bar) ); 任意のキーにアクセスしたい場合は、オブジェクトのロックを解除してください。 use Hash::Util 'unlock_keys'; unlock_keys %{$obj}; この挙動は `configure` の `LOCK_KEYS` パラメータで変更できます。 ## **configure** **label** => _value_, ... オブジェクト作成前にクラスメソッド `Getopt::EX::Hashed->configure()` を使用してください。この情報は呼び出し元パッケージごとに個別に保存されます。`new()` 呼び出し後、パッケージレベルの設定がオブジェクトにコピーされて使用されます。オブジェクトレベルの設定を更新するには `$obj->configure()` を使用します。 利用可能な設定パラメータは次のとおりです。 - **LOCK\_KEYS** (default: 1) ハッシュキーをロックします。これによりタイプミスなどで意図しないハッシュエントリが作成されるのを防ぎます。 - **REPLACE\_UNDERSCORE** (default: 1) アンダースコアをダッシュに置き換えたオプションのエイリアスを自動的に作成します。 - **REMOVE\_UNDERSCORE** (default: 0) アンダースコアを削除したオプションのエイリアスを自動的に作成します。 - **GETOPT** (default: 'GetOptions') - **GETOPT\_FROM\_ARRAY** (default: 'GetOptionsFromArray') `getopt` メソッドから呼び出される関数名を設定します。 - **ACCESSOR\_PREFIX** (default: '') 指定された場合、メンバー名の前に付加してアクセサメソッドを作成します。`ACCESSOR_PREFIX` が `opt_` と定義されていると、メンバー `file` のアクセサは `opt_file` になります。 - **ACCESSOR\_LVALUE** (default: 1) 真の場合、読み書きアクセサに lvalue 属性が付きます。その挙動が好みでない場合は 0 に設定してください。 - **DEFAULT** デフォルトパラメータを設定します。`has` が呼ばれると、DEFAULT パラメータは明示的なパラメータの前に挿入されます。両方に同じパラメータがある場合は、明示的なものが優先されます。`+` を用いる増分呼び出しには影響しません。 DEFAULT の典型的な使い方は、以降のすべてのハッシュエントリに対するアクセサメソッドを用意するための `is` です。リセットするには `DEFAULT => []` を宣言してください。 Getopt::EX::Hashed->configure(DEFAULT => [ is => 'ro' ]); ## **reset** クラスを元の状態にリセットします。 # SEE ALSO [Getopt::Long](https://metacpan.org/pod/Getopt%3A%3ALong) [Getopt::EX](https://metacpan.org/pod/Getopt%3A%3AEX), [Getopt::EX::Long](https://metacpan.org/pod/Getopt%3A%3AEX%3A%3ALong) # AUTHOR Kazumasa Utashiro # COPYRIGHT The following copyright notice applies to all the files provided in this distribution, including binary files, unless explicitly noted otherwise. Copyright 2021-2025 Kazumasa Utashiro # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. README.KO.md100644000766000024 3132515104610653 16570 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602# NAME Getopt::EX::Hashed - Getopt::Long을 위한 해시 객체 자동화 # VERSION Version 1.0602 # SYNOPSIS # script/foo use App::foo; App::foo->new->run(); # lib/App/foo.pm package App::foo; use Getopt::EX::Hashed; { Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); has start => ' =i s begin ' , default => 1; has end => ' =i e ' ; has file => ' =s@ f ' , any => qr/^(?!\.)/; has score => ' =i ' , min => 0, max => 100; has answer => ' =i ' , must => sub { $_[1] == 42 }; has mouse => ' =s ' , any => [ 'Frankie', 'Benjy' ]; has question => ' =s ' , any => qr/^(life|universe|everything)$/i; } no Getopt::EX::Hashed; sub run { my $app = shift; use Getopt::Long; $app->getopt or pod2usage(); if ($app->answer == 42) { $app->question //= 'life'; ... # DESCRIPTION **Getopt::EX::Hashed**는 **Getopt::Long** 및 **Getopt::EX::Long**을 포함한 호환 모듈용으로, 명령줄 옵션 값을 저장할 해시 객체의 생성을 자동화하는 모듈입니다. 모듈 이름은 **Getopt::EX** 접두사를 공유하지만, 지금까지는 **Getopt::EX**의 다른 모듈과 독립적으로 동작합니다. 이 모듈의 주요 목적은 초기화와 명세를 한 곳에 통합하는 것입니다. 또한 간단한 검증 인터페이스를 제공합니다. `is` 매개변수가 주어지면 접근자 메서드가 자동으로 생성됩니다. 동일한 함수가 이미 정의되어 있으면 프로그램은 치명적 오류를 발생시킵니다. 객체가 파괴될 때 접근자는 제거됩니다. 여러 객체가 동시에 존재할 때 문제를 일으킬 수 있습니다. # FUNCTION ## **has** 옵션 매개변수는 다음 형태로 선언하십시오. 괄호는 명확성을 위한 것이며 생략할 수 있습니다. has option_name => ( param => value, ... ); 예를 들어, 정수 값을 매개변수로 받는 옵션 `--number`를 정의하고, `-n`으로도 사용할 수 있게 하려면 다음과 같이 하십시오 has number => spec => "=i n"; 접근자는 첫 번째 이름으로 생성됩니다. 이 예에서 접근자는 `$app->number`로 정의됩니다. 배열 참조가 주어지면 여러 이름을 한 번에 선언할 수 있습니다. has [ 'left', 'right' ] => ( spec => "=i" ); 이름이 플러스(`+`)로 시작하면, 주어진 매개변수는 기존 설정을 갱신합니다. has '+left' => ( default => 1 ); `spec` 매개변수의 경우, 라벨은 그것이 첫 번째 매개변수라면 생략할 수 있습니다. has left => "=i", default => 1; 매개변수 개수가 홀수이면, 첫 번째 매개변수는 암시적 라벨이 있는 것으로 처리됩니다: 코드 참조이면 `action`, 그렇지 않으면 `spec`. 다음 매개변수를 사용할 수 있습니다. - \[ **spec** => \] _string_ 옵션 명세를 제공합니다. `spec =>` 라벨은 첫 번째 매개변수일 때에만 생략할 수 있습니다. _string_에서는 옵션 명세와 별칭 이름이 공백으로 구분되며, 어떤 순서로든 나타날 수 있습니다. 정수를 값으로 받는 `--start`라는 옵션을 만들고, `-s`와 `--begin`이라는 이름으로도 사용할 수 있게 하려면 다음과 같이 선언하십시오. has start => "=i s begin"; 위 선언은 다음 문자열로 컴파일됩니다. start|s|begin=i 이는 `Getopt::Long` 정의에 부합합니다. 물론 다음과 같이 작성할 수도 있습니다: has start => "s|begin=i"; 이름과 별칭에 밑줄(`_`)이 포함되어 있으면, 밑줄 대신 대시(`-`)를 사용한 또 다른 별칭 이름이 정의됩니다. has a_to_z => "=s"; 위 선언은 다음 문자열로 컴파일됩니다. a_to_z|a-to-z=s 옵션 사양이 필요하지 않다면, 값으로 빈 문자열(또는 공백만 있는 문자열)을 주십시오. 사양 문자열이 없으면 해당 멤버는 옵션으로 취급되지 않습니다. - **alias** => _string_ 추가 별칭 이름은 **alias** 매개변수로도 지정할 수 있습니다. `spec` 매개변수에 있는 것과 차이가 없습니다. has start => "=i", alias => "s begin"; - **is** => `ro` | `rw` 접근자 메서드를 만들려면 `is` 매개변수가 필요합니다. 값으로 읽기 전용은 `ro`, 읽기/쓰기는 `rw`를 설정하십시오. 읽기/쓰기 접근자는 lvalue 속성을 가지므로 대입할 수 있습니다. 다음과 같이 사용할 수 있습니다: $app->foo //= 1; 이는 다음과 같이 작성하는 것보다 훨씬 간단합니다. $app->foo(1) unless defined $app->foo; 이후 모든 멤버에 대해 접근자를 만들고 싶다면, `configure`를 사용해 `DEFAULT` 매개변수를 설정하십시오. Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); 할당 가능한 접근자가 마음에 들지 않는다면 `ACCESSOR_LVALUE` 파라미터를 0으로 설정하세요. 접근자는 `new` 시점에 생성되므로, 이 값은 모든 멤버에 대해 유효합니다. - **default** => _value_ | _coderef_ 기본값을 설정합니다. 기본값이 주어지지 않으면 멤버는 `undef`로 초기화됩니다. 값이 ARRAY 또는 HASH에 대한 참조인 경우, 각 `new` 호출마다 얕은 복사본이 생성됩니다. 이는 참조 자체는 복사되지만, 내용은 공유된다는 뜻입니다. 배열이나 해시의 내용을 수정하면 모든 인스턴스에 영향을 미칩니다. 코드 참조가 주어지면 기본값을 얻기 위해 **new** 시점에 호출됩니다. 이는 선언 시점이 아니라 실행 시점에 값을 평가하고자 할 때 효과적입니다. 기본 동작을 정의하려면 **action** 파라미터를 사용하세요. 코드 참조를 초기값으로 설정하려면, 코드 참조를 반환하는 코드 참조를 지정해야 합니다. SCALAR에 대한 참조가 주어지면, 옵션 값은 해시 객체 멤버가 아니라 해당 참조가 가리키는 데이터에 저장됩니다. 이 경우 해시 멤버에 접근해도 기대하는 값을 얻을 수 없습니다. - \[ **action** => \] _coderef_ 파라미터 `action`은 옵션을 처리하기 위해 호출되는 코드 참조를 받습니다. `action =>` 라벨은 오직 첫 번째 파라미터일 때에만 생략할 수 있습니다. 호출 시, 해시 객체가 `$_`로 전달됩니다. has [ qw(left right both) ] => '=i'; has "+both" => sub { $_->{left} = $_->{right} = $_[1]; }; 비옵션 인수를 처리하기 위해 `"<>"`에 대해 이것을 사용할 수 있습니다. 이 경우 spec 매개변수는 중요하지 않으며 필요하지 않습니다. has ARGV => default => []; has "<>" => sub { push @{$_->{ARGV}}, $_[0]; }; 다음 파라미터들은 모두 데이터 검증을 위한 것입니다. 먼저, `must`는 범용 검증기로서 무엇이든 구현할 수 있습니다. 나머지는 일반 규칙에 대한 단축형입니다. - **must** => _coderef_ | \[ _coderef_ ... \] 파라미터 `must`는 옵션 값을 검증하기 위한 코드 참조를 받습니다. `action`과 동일한 인수를 취하고 불리언을 반환합니다. 다음 예시에서 옵션 **--answer**는 유효한 값으로 오직 42만 허용합니다. has answer => '=i', must => sub { $_[1] == 42 }; 코드 참조가 여러 개 주어지면, 모든 코드가 참을 반환해야 합니다. has answer => '=i', must => [ sub { $_[1] >= 42 }, sub { $_[1] <= 42 } ]; - **min** => _number_ - **max** => _number_ 인자의 최소 및 최대 한계를 설정합니다. - **any** => _arrayref_ | qr/_regex_/ | _coderef_ 유효한 문자열 파라미터 리스트를 설정합니다. 각 항목은 문자열, 정규식 참조, 또는 코드 참조가 될 수 있습니다. 인자는 주어진 리스트의 항목과 동일하거나 일치할 때 유효합니다. 값이 arrayref가 아니면 단일 항목 리스트로 간주됩니다(보통 regexpref 또는 coderef). 다음 선언들은 거의 동등하며, 두 번째 것은 대소문자를 구분하지 않습니다. has question => '=s', any => [ 'life', 'universe', 'everything' ]; has question => '=s', any => qr/^(life|universe|everything)$/i; 선택적 인자를 사용 중이라면, 기본값을 리스트에 포함하는 것을 잊지 마세요. 그렇지 않으면 검증 오류가 발생합니다. has question => ':s', any => [ 'life', 'universe', 'everything', '' ]; # METHOD ## **new** 새 해시 객체를 생성하는 클래스 메서드입니다. 모든 멤버를 기본값으로 초기화하고 설정에 따라 접근자 메서드를 생성합니다. blessed 해시 참조를 반환합니다. LOCK\_KEYS가 활성화된 경우 해시 키는 잠깁니다. ## **optspec** `GetOptions` 함수에 전달할 수 있는 옵션 명세 리스트를 반환합니다. GetOptions($obj->optspec) `GetOptions`는 첫 번째 인수로 해시 참조를 제공하여 값을 해시에 저장하는 기능이 있지만, 반드시 그럴 필요는 없습니다. ## **getopt** \[ _arrayref_ \] 호출자의 컨텍스트에서 정의된 적절한 함수를 호출하여 옵션을 처리합니다. $obj->getopt $obj->getopt(\@argv); 위의 예제들은 다음 코드에 대한 단축형입니다. GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) ## **use\_keys** _keys_ LOCK\_KEYS가 활성화되면, 존재하지 않는 멤버에 접근할 경우 오류가 발생합니다. 접근하기 전에 새로운 멤버 키를 선언하려면 이 메서드를 사용하십시오. $obj->use_keys( qw(foo bar) ); 임의의 키에 접근하려면 객체의 잠금을 해제하세요. use Hash::Util 'unlock_keys'; unlock_keys %{$obj}; `LOCK_KEYS` 매개변수와 함께 `configure`로 이 동작을 변경할 수 있습니다. ## **configure** **label** => _value_, ... 객체를 생성하기 전에 클래스 메서드 `Getopt::EX::Hashed->configure()`를 사용하십시오. 이 정보는 호출하는 각 패키지마다 별도로 저장됩니다. `new()`를 호출한 후, 패키지 수준 구성은 객체가 사용하도록 객체에 복사됩니다. 객체 수준 구성을 업데이트하려면 `$obj->configure()`를 사용하십시오. 다음 구성 매개변수를 사용할 수 있습니다. - **LOCK\_KEYS** (default: 1) 해시 키를 잠급니다. 이는 오타나 기타 실수로 의도치 않은 해시 항목이 생성되는 것을 방지합니다. - **REPLACE\_UNDERSCORE** (default: 1) 밑줄을 대시로 바꾼 옵션 별칭을 자동으로 생성합니다. - **REMOVE\_UNDERSCORE** (default: 0) 밑줄을 제거한 옵션 별칭을 자동으로 생성합니다. - **GETOPT** (default: 'GetOptions') - **GETOPT\_FROM\_ARRAY** (default: 'GetOptionsFromArray') `getopt` 메서드에서 호출되는 함수 이름을 설정합니다. - **ACCESSOR\_PREFIX** (default: '') 지정하면, 접근자 메서드를 만들기 위해 멤버 이름 앞에 접두사가 추가됩니다. `ACCESSOR_PREFIX`가 `opt_`로 정의되어 있으면, 멤버 `file`의 접근자는 `opt_file`이 됩니다. - **ACCESSOR\_LVALUE** (default: 1) 참이면, 읽기-쓰기 접근자는 lvalue 속성을 가집니다. 그러한 동작이 마음에 들지 않으면 0으로 설정하세요. - **DEFAULT** 기본 매개변수를 설정합니다. `has`가 호출될 때 DEFAULT 매개변수가 명시적 매개변수 앞에 삽입됩니다. 둘 모두에 매개변수가 나타나면, 명시적인 것이 우선합니다. `+`가 있는 누적 호출에는 영향을 주지 않습니다. DEFAULT의 전형적인 사용은 `is`로 이후의 모든 해시 항목에 대한 접근자 메서드를 준비하는 것입니다. 재설정하려면 `DEFAULT => []`를 선언하세요. Getopt::EX::Hashed->configure(DEFAULT => [ is => 'ro' ]); ## **reset** 클래스를 원래 상태로 재설정합니다. # SEE ALSO [Getopt::Long](https://metacpan.org/pod/Getopt%3A%3ALong) [Getopt::EX](https://metacpan.org/pod/Getopt%3A%3AEX), [Getopt::EX::Long](https://metacpan.org/pod/Getopt%3A%3AEX%3A%3ALong) # AUTHOR Kazumasa Utashiro # COPYRIGHT The following copyright notice applies to all the files provided in this distribution, including binary files, unless explicitly noted otherwise. Copyright 2021-2025 Kazumasa Utashiro # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. README.ZH.md100644000766000024 2460415104610653 16602 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602# NAME Getopt::EX::Hashed - 为 Getopt::Long 提供哈希对象自动化 # VERSION Version 1.0602 # SYNOPSIS # script/foo use App::foo; App::foo->new->run(); # lib/App/foo.pm package App::foo; use Getopt::EX::Hashed; { Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); has start => ' =i s begin ' , default => 1; has end => ' =i e ' ; has file => ' =s@ f ' , any => qr/^(?!\.)/; has score => ' =i ' , min => 0, max => 100; has answer => ' =i ' , must => sub { $_[1] == 42 }; has mouse => ' =s ' , any => [ 'Frankie', 'Benjy' ]; has question => ' =s ' , any => qr/^(life|universe|everything)$/i; } no Getopt::EX::Hashed; sub run { my $app = shift; use Getopt::Long; $app->getopt or pod2usage(); if ($app->answer == 42) { $app->question //= 'life'; ... # DESCRIPTION **Getopt::EX::Hashed** 是一个模块,用于为 **Getopt::Long** 及其兼容模块(包括 **Getopt::EX::Long**)自动创建用于存储命令行选项值的哈希对象。该模块名称带有 **Getopt::EX** 前缀,但目前它可独立于 **Getopt::EX** 中的其他模块工作。 本模块的主要目标是将初始化与规范定义整合在同一处。它还提供了一个简单的校验接口。 当提供 `is` 参数时,会自动生成访问器方法。如果同名函数已存在,程序将发生致命错误。对象销毁时,访问器将被移除。当同时存在多个对象时可能出现问题。 # FUNCTION ## **has** 以如下形式声明选项参数。圆括号仅为清晰起见,可省略。 has option_name => ( param => value, ... ); 例如,要定义选项 `--number`,它接受一个整数参数,同时也可用作 `-n`,请按如下操作 has number => spec => "=i n"; 访问器将以第一个名称创建。在此示例中,访问器将定义为 `$app->number`。 如果给出数组引用,可以一次声明多个名称。 has [ 'left', 'right' ] => ( spec => "=i" ); 如果名称以加号(`+`)开头,给定参数将更新现有设置。 has '+left' => ( default => 1 ); 对于 `spec` 参数,如果它是第一个参数,标签可以省略。 has left => "=i", default => 1; 如果参数数量为奇数,第一个参数将被视为具有隐式标签:若为代码引用则为 `action`,否则为 `spec`。 可用的参数如下。 - \[ **spec** => \] _string_ 给出选项规范。仅当且仅当它是第一个参数时,可以省略 `spec =>` 标签。 在 _string_ 中,选项规范与别名以空白分隔,且可以任意顺序出现。 要声明一个名为 `--start` 的选项,它接受一个整数值,并且也可以使用名称 `-s` 和 `--begin`,如下声明。 has start => "=i s begin"; 上述声明将被编译为如下字符串。 start|s|begin=i 其符合 `Getopt::Long` 的定义。当然,你也可以这样写: has start => "s|begin=i"; 如果名称和别名包含下划线(`_`),则会再定义一个把下划线替换为短横线(`-`)的别名。 has a_to_z => "=s"; 上述声明将被编译为如下字符串。 a_to_z|a-to-z=s 如果不需要选项规范(spec),请将一个空字符串(或仅包含空白)作为值。没有 spec 字符串时,该成员不会被视为选项。 - **alias** => _string_ 也可以通过 **alias** 参数指定额外的别名名称。这与 `spec` 参数中的别名没有差别。 has start => "=i", alias => "s begin"; - **is** => `ro` | `rw` 要生成访问器方法,需要 `is` 参数。设置值 `ro` 为只读,`rw` 为读写。 读写访问器具有左值属性,因此可以被赋值。可如下使用: $app->foo //= 1; 这比下面这样写要简洁得多。 $app->foo(1) unless defined $app->foo; 如果你想为后续所有成员创建访问器,使用 `configure` 设置 `DEFAULT` 参数。 Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); 如果你不喜欢可赋值的存取器,请将 `ACCESSOR_LVALUE` 参数配置为 0。由于存取器是在调用 `new` 时生成的,该值对所有成员都有效。 - **default** => _value_ | _coderef_ 设置默认值。如果未提供默认值,成员将初始化为 `undef`。 如果该值是对 ARRAY 或 HASH 的引用,则每次调用 `new` 都会创建一个浅拷贝。这意味着复制的是引用本身,但其内容是共享的。修改数组或哈希的内容将影响所有实例。 如果提供了代码引用,它会在 **new** 时被调用以获得默认值。当你希望在执行时而非声明时计算该值时,这很有效。如果你想定义默认动作,请使用 **action** 参数。如果你想将代码引用设置为初始值,你必须指定一个返回代码引用的代码引用。 如果提供了对 SCALAR 的引用,选项值将存储在该引用所指向的数据中,而不是哈希对象成员中。在这种情况下,通过访问哈希成员无法获得期望的值。 - \[ **action** => \] _coderef_ 参数 `action` 接受用于处理该选项的代码引用。只有当它是第一个参数时,才能省略 `action =>` 标记。 调用时,哈希对象作为 `$_` 传入。 has [ qw(left right both) ] => '=i'; has "+both" => sub { $_->{left} = $_->{right} = $_[1]; }; 你可以将其用于 `"<>"` 以处理非选项参数。在这种情况下,spec 参数无关紧要且不是必需的。 has ARGV => default => []; has "<>" => sub { push @{$_->{ARGV}}, $_[0]; }; 以下参数均用于数据验证。首先,`must` 是通用验证器,几乎可以实现任何规则。其他的是常见规则的快捷方式。 - **must** => _coderef_ | \[ _coderef_ ... \] 参数 `must` 接受一个用于验证选项值的代码引用。它接受与 `action` 相同的参数并返回布尔值。下面的示例中,选项 **--answer** 只有在值为 42 时才有效。 has answer => '=i', must => sub { $_[1] == 42 }; 如果提供了多个代码引用,所有代码都必须返回真。 has answer => '=i', must => [ sub { $_[1] >= 42 }, sub { $_[1] <= 42 } ]; - **min** => _number_ - **max** => _number_ 为参数设置最小和最大限制。 - **any** => _arrayref_ | qr/_regex_/ | _coderef_ 设置有效的字符串参数列表。每个项目可以是字符串、正则表达式引用或代码引用。当参数与给定列表中的任一项相同或匹配时即为有效。如果该值不是 arrayref,则将其视为单项列表(通常是 regexpref 或 coderef)。 以下声明几乎等价,只是第二个不区分大小写。 has question => '=s', any => [ 'life', 'universe', 'everything' ]; has question => '=s', any => qr/^(life|universe|everything)$/i; 如果你使用可选参数,别忘了在列表中包含默认值。否则会导致验证错误。 has question => ':s', any => [ 'life', 'universe', 'everything', '' ]; # METHOD ## **new** 一个创建新的哈希对象的类方法。用默认值初始化所有成员,并按配置创建访问器方法。返回一个被祝福的哈希引用。如果启用了 LOCK\_KEYS,则哈希键会被锁定。 ## **optspec** 返回可传递给 `GetOptions` 函数的选项规范列表。 GetOptions($obj->optspec) `GetOptions` 具备通过将哈希引用作为第一个参数来将值存储到哈希中的能力,但这不是必需的。 ## **getopt** \[ _arrayref_ \] 调用在调用方上下文中定义的相应函数以处理选项。 $obj->getopt $obj->getopt(\@argv); 上面的示例是以下代码的简写。 GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) ## **use\_keys** _keys_ 当启用 LOCK\_KEYS 时,访问不存在的成员会导致错误。请在访问之前使用此方法声明新的成员键。 $obj->use_keys( qw(foo bar) ); 如果你想访问任意键,请解锁该对象。 use Hash::Util 'unlock_keys'; unlock_keys %{$obj}; 你可以通过带有 `LOCK_KEYS` 参数的 `configure` 来更改此行为。 ## **configure** **label** => _value_, ... 在创建对象之前,使用类方法 `Getopt::EX::Hashed->configure()`;该信息按调用包分别存储。调用 `new()` 之后,包级配置会被复制到对象中供其使用。使用 `$obj->configure()` 更新对象级配置。 可用的配置参数如下。 - **LOCK\_KEYS** (default: 1) 锁定哈希键。这可防止因拼写错误或其他失误而创建非预期的哈希条目。 - **REPLACE\_UNDERSCORE** (default: 1) 自动创建将下划线替换为连字符的选项别名。 - **REMOVE\_UNDERSCORE** (default: 0) 自动创建移除下划线的选项别名。 - **GETOPT** (default: 'GetOptions') - **GETOPT\_FROM\_ARRAY** (default: 'GetOptionsFromArray') 设置从 `getopt` 方法调用的函数名。 - **ACCESSOR\_PREFIX** (default: '') 当指定时,它会被前置到成员名以生成访问器方法。如果 `ACCESSOR_PREFIX` 定义为 `opt_`,则成员 `file` 的访问器将是 `opt_file`。 - **ACCESSOR\_LVALUE** (default: 1) 如果为真,读写访问器具有 lvalue 属性。如果你不喜欢这种行为,请设为零。 - **DEFAULT** 设置默认参数。当调用 `has` 时,DEFAULT 参数会插入到显式参数之前。若两者都有同一参数,则以显式参数为准。带有 `+` 的增量调用不受影响。 DEFAULT 的典型用法是使用 `is` 为随后的所有哈希条目准备访问器方法。声明 `DEFAULT => []` 可重置。 Getopt::EX::Hashed->configure(DEFAULT => [ is => 'ro' ]); ## **reset** 将类重置为初始状态。 # SEE ALSO [Getopt::Long](https://metacpan.org/pod/Getopt%3A%3ALong) [Getopt::EX](https://metacpan.org/pod/Getopt%3A%3AEX), [Getopt::EX::Long](https://metacpan.org/pod/Getopt%3A%3AEX%3A%3ALong) # AUTHOR Kazumasa Utashiro # COPYRIGHT The following copyright notice applies to all the files provided in this distribution, including binary files, unless explicitly noted otherwise. Copyright 2021-2025 Kazumasa Utashiro # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. README.md100644000766000024 2735515104610653 16270 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602[![Actions Status](https://github.com/kaz-utashiro/Getopt-EX-Hashed/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/kaz-utashiro/Getopt-EX-Hashed/actions?workflow=test) [![MetaCPAN Release](https://badge.fury.io/pl/Getopt-EX-Hashed.svg)](https://metacpan.org/release/Getopt-EX-Hashed) # NAME Getopt::EX::Hashed - Hash object automation for Getopt::Long # VERSION Version 1.0602 # SYNOPSIS # script/foo use App::foo; App::foo->new->run(); # lib/App/foo.pm package App::foo; use Getopt::EX::Hashed; { Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); has start => ' =i s begin ' , default => 1; has end => ' =i e ' ; has file => ' =s@ f ' , any => qr/^(?!\.)/; has score => ' =i ' , min => 0, max => 100; has answer => ' =i ' , must => sub { $_[1] == 42 }; has mouse => ' =s ' , any => [ 'Frankie', 'Benjy' ]; has question => ' =s ' , any => qr/^(life|universe|everything)$/i; } no Getopt::EX::Hashed; sub run { my $app = shift; use Getopt::Long; $app->getopt or pod2usage(); if ($app->answer == 42) { $app->question //= 'life'; ... # DESCRIPTION **Getopt::EX::Hashed** is a module to automate the creation of a hash object to store command line option values for **Getopt::Long** and compatible modules including **Getopt::EX::Long**. The module name shares the **Getopt::EX** prefix, but it works independently from other modules in **Getopt::EX**, so far. The major objective of this module is integrating initialization and specification into a single place. It also provides a simple validation interface. Accessor methods are automatically generated when `is` parameter is given. If the same function is already defined, the program causes fatal error. Accessors are removed when the object is destroyed. Problems may occur when multiple objects are present at the same time. # FUNCTION ## **has** Declare option parameters in the following form. The parentheses are for clarity only and may be omitted. has option_name => ( param => value, ... ); For example, to define the option `--number`, which takes an integer value as a parameter, and also can be used as `-n`, do the following has number => spec => "=i n"; The accessor is created with the first name. In this example, the accessor will be defined as `$app->number`. If an array reference is given, multiple names can be declared at once. has [ 'left', 'right' ] => ( spec => "=i" ); If the name starts with plus (`+`), the given parameter updates the existing setting. has '+left' => ( default => 1 ); As for the `spec` parameter, the label can be omitted if it is the first parameter. has left => "=i", default => 1; If the number of parameters is odd, the first parameter is treated as having an implicit label: `action` if it is a code reference, `spec` otherwise. Following parameters are available. - \[ **spec** => \] _string_ Give option specification. `spec =>` label can be omitted if and only if it is the first parameter. In _string_, option spec and alias names are separated by white space, and can show up in any order. To have an option called `--start` that takes an integer as its value and can also be used with the names `-s` and `--begin`, declare as follows. has start => "=i s begin"; The above declaration will be compiled into the following string. start|s|begin=i which conforms to the `Getopt::Long` definition. Of course, you can write it as: has start => "s|begin=i"; If the name and aliases contain underscore (`_`), another alias name is defined with dash (`-`) in place of underscores. has a_to_z => "=s"; The above declaration will be compiled into the following string. a_to_z|a-to-z=s If no option spec is needed, give an empty (or white space only) string as a value. Without a spec string, the member will not be treated as an option. - **alias** => _string_ Additional alias names can be specified by the **alias** parameter too. There is no difference from the ones in the `spec` parameter. has start => "=i", alias => "s begin"; - **is** => `ro` | `rw` To produce an accessor method, the `is` parameter is necessary. Set the value `ro` for read-only, `rw` for read-write. Read-write accessor has lvalue attribute, so it can be assigned to. You can use like this: $app->foo //= 1; This is much simpler than writing as in the following. $app->foo(1) unless defined $app->foo; If you want to make accessors for all following members, use `configure` to set the `DEFAULT` parameter. Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); If you don't like assignable accessors, configure the `ACCESSOR_LVALUE` parameter to 0. Because accessors are generated at the time of `new`, this value is effective for all members. - **default** => _value_ | _coderef_ Set default value. If no default is given, the member is initialized as `undef`. If the value is a reference to an ARRAY or HASH, a shallow copy is created for each `new` call. This means the reference itself is copied, but the contents are shared. Modifying the array or hash contents will affect all instances. If a code reference is given, it is called at the time of **new** to get default value. This is effective when you want to evaluate the value at the time of execution, rather than declaration. If you want to define a default action, use the **action** parameter. If you want to set code reference as the initial value, you must specify a code reference that returns a code reference. If a reference to SCALAR is given, the option value is stored in the data indicated by the reference, not in the hash object member. In this case, the expected value cannot be obtained by accessing the hash member. - \[ **action** => \] _coderef_ Parameter `action` takes code reference which is called to process the option. `action =>` label can be omitted if and only if it is the first parameter. When called, hash object is passed as `$_`. has [ qw(left right both) ] => '=i'; has "+both" => sub { $_->{left} = $_->{right} = $_[1]; }; You can use this for `"<>"` to handle non-option arguments. In that case, the spec parameter does not matter and is not required. has ARGV => default => []; has "<>" => sub { push @{$_->{ARGV}}, $_[0]; }; Following parameters are all for data validation. First, `must` is a generic validator and can implement anything. Others are shortcuts for common rules. - **must** => _coderef_ | \[ _coderef_ ... \] Parameter `must` takes a code reference to validate option values. It takes the same arguments as `action` and returns a boolean. With the following example, option **--answer** takes only 42 as a valid value. has answer => '=i', must => sub { $_[1] == 42 }; If multiple code references are given, all code must return true. has answer => '=i', must => [ sub { $_[1] >= 42 }, sub { $_[1] <= 42 } ]; - **min** => _number_ - **max** => _number_ Set the minimum and maximum limit for the argument. - **any** => _arrayref_ | qr/_regex_/ | _coderef_ Set the valid string parameter list. Each item can be a string, a regex reference, or a code reference. The argument is valid when it is the same as, or matches any item of the given list. If the value is not an arrayref, it is taken as a single item list (regexpref or coderef usually). Following declarations are almost equivalent, except second one is case insensitive. has question => '=s', any => [ 'life', 'universe', 'everything' ]; has question => '=s', any => qr/^(life|universe|everything)$/i; If you are using optional argument, don't forget to include default value in the list. Otherwise it causes validation error. has question => ':s', any => [ 'life', 'universe', 'everything', '' ]; # METHOD ## **new** A class method that creates a new hash object. Initializes all members with their default values and creates accessor methods as configured. Returns a blessed hash reference. The hash keys are locked if LOCK\_KEYS is enabled. ## **optspec** Returns the option specification list which can be passed to the `GetOptions` function. GetOptions($obj->optspec) `GetOptions` has the capability of storing values in a hash by giving the hash reference as the first argument, but it is not necessary. ## **getopt** \[ _arrayref_ \] Calls the appropriate function defined in the caller's context to process options. $obj->getopt $obj->getopt(\@argv); The above examples are shortcuts for the following code. GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) ## **use\_keys** _keys_ When LOCK\_KEYS is enabled, accessing a non-existent member causes an error. Use this method to declare new member keys before accessing them. $obj->use_keys( qw(foo bar) ); If you want to access arbitrary keys, unlock the object. use Hash::Util 'unlock_keys'; unlock_keys %{$obj}; You can change this behavior by `configure` with `LOCK_KEYS` parameter. ## **configure** **label** => _value_, ... Use class method `Getopt::EX::Hashed->configure()` before creating an object; this information is stored separately for each calling package. After calling `new()`, the package-level configuration is copied into the object for its use. Use `$obj->configure()` to update object-level configuration. The following configuration parameters are available. - **LOCK\_KEYS** (default: 1) Lock hash keys. This prevents typos or other mistakes from creating unintended hash entries. - **REPLACE\_UNDERSCORE** (default: 1) Automatically create option aliases with underscores replaced by dashes. - **REMOVE\_UNDERSCORE** (default: 0) Automatically create option aliases with underscores removed. - **GETOPT** (default: 'GetOptions') - **GETOPT\_FROM\_ARRAY** (default: 'GetOptionsFromArray') Set the function name called from the `getopt` method. - **ACCESSOR\_PREFIX** (default: '') When specified, it will be prepended to the member name to make the accessor method. If `ACCESSOR_PREFIX` is defined as `opt_`, the accessor for member `file` will be `opt_file`. - **ACCESSOR\_LVALUE** (default: 1) If true, read-write accessors have the lvalue attribute. Set to zero if you don't like that behavior. - **DEFAULT** Set default parameters. When `has` is called, DEFAULT parameters are inserted before the explicit parameters. If a parameter appears in both, the explicit one takes precedence. Incremental calls with `+` are not affected. A typical use of DEFAULT is `is` to prepare accessor methods for all following hash entries. Declare `DEFAULT => []` to reset. Getopt::EX::Hashed->configure(DEFAULT => [ is => 'ro' ]); ## **reset** Reset the class to the original state. # SEE ALSO [Getopt::Long](https://metacpan.org/pod/Getopt%3A%3ALong) [Getopt::EX](https://metacpan.org/pod/Getopt%3A%3AEX), [Getopt::EX::Long](https://metacpan.org/pod/Getopt%3A%3AEX%3A%3ALong) # AUTHOR Kazumasa Utashiro # COPYRIGHT The following copyright notice applies to all the files provided in this distribution, including binary files, unless explicitly noted otherwise. Copyright 2021-2025 Kazumasa Utashiro # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. cpanfile100644000766000024 31715104610653 16442 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602requires 'List::Util'; requires 'perl', 'v5.14.0'; on configure => sub { requires 'Module::Build::Tiny', '0.035'; }; on test => sub { requires 'Getopt::Long'; requires 'Test::More', '0.98'; }; Hashed.JA.pod100644000766000024 3524115104610653 20123 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0602/docs=encoding utf-8 =head1 NAME Getopt::EX::Hashed - Getopt::Long のためのハッシュオブジェクト自動化 =head1 VERSION Version 1.0602 =head1 SYNOPSIS # script/foo use App::foo; App::foo->new->run(); # lib/App/foo.pm package App::foo; use Getopt::EX::Hashed; { Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); has start => ' =i s begin ' , default => 1; has end => ' =i e ' ; has file => ' =s@ f ' , any => qr/^(?!\.)/; has score => ' =i ' , min => 0, max => 100; has answer => ' =i ' , must => sub { $_[1] == 42 }; has mouse => ' =s ' , any => [ 'Frankie', 'Benjy' ]; has question => ' =s ' , any => qr/^(life|universe|everything)$/i; } no Getopt::EX::Hashed; sub run { my $app = shift; use Getopt::Long; $app->getopt or pod2usage(); if ($app->answer == 42) { $app->question //= 'life'; ... =cut =head1 DESCRIPTION B は、B および B を含む互換モジュール向けに、コマンドラインオプション値を格納するハッシュオブジェクトの作成を自動化するモジュールです。モジュール名は B プレフィックスを共有しますが、現時点では B 内の他のモジュールから独立して動作します。 このモジュールの主目的は、初期化と仕様の定義を一箇所に統合することです。簡易な検証インターフェースも提供します。 C パラメータが与えられるとアクセサメソッドが自動生成されます。同名の関数がすでに定義されている場合、プログラムは致命的エラーとなります。オブジェクトが破棄されるとアクセサは削除されます。同時に複数のオブジェクトが存在する場合、問題が発生する可能性があります。 =head1 FUNCTION =head2 B 次の形式でオプションパラメータを宣言します。かっこは見やすさのためのもので、省略可能です。 has option_name => ( param => value, ... ); 例えば、整数値を引数に取るオプション C<--number> を定義し、C<-n> としても使えるようにするには、次のようにします。 has number => spec => "=i n"; アクセサは最初の名前で作成されます。この例では、アクセサは C<< $app->number >> として定義されます。 配列リファレンスを与えると、複数の名前を一度に宣言できます。 has [ 'left', 'right' ] => ( spec => "=i" ); 名前がプラス (C<+>) で始まる場合、与えたパラメータは既存の設定を更新します。 has '+left' => ( default => 1 ); C パラメータについては、先頭のパラメータであればラベルを省略できます。 has left => "=i", default => 1; パラメータ数が奇数の場合、最初のパラメータは暗黙のラベルを持つものとして扱われます。コードリファレンスなら C、それ以外なら C です。 利用可能なパラメータは以下の通りです。 =over 7 =item [ B => ] I オプション仕様を与えます。C<< spec => >> ラベルは最初のパラメータである場合に限り省略できます。 I では、オプション仕様とエイリアス名は空白で区切られ、順序は任意です。 整数を値に取る C<--start> というオプションを用意し、C<-s> や C<--begin> という名前でも使えるようにするには、次のように宣言します。 has start => "=i s begin"; 上記の宣言は次の文字列にコンパイルされます。 start|s|begin=i これは C の定義に準拠しています。もちろん、次のように書くこともできます: has start => "s|begin=i"; 名前やエイリアスにアンダースコア (C<_>) が含まれている場合、アンダースコアをダッシュ (C<->) に置き換えた別のエイリアス名が定義されます。 has a_to_z => "=s"; 上記の宣言は次の文字列にコンパイルされます。 a_to_z|a-to-z=s オプション spec が不要な場合は、空文字列(または空白のみの文字列)を値として与えてください。spec 文字列がなければ、そのメンバーはオプションとして扱われません。 =item B => I 追加のエイリアス名は B パラメータでも指定できます。C パラメータ内のものと違いはありません。 has start => "=i", alias => "s begin"; =item B => C | C アクセサメソッドを生成するには、C パラメータが必要です。値は読み取り専用なら C、読み書き可能なら C を設定します。 読み書き可能アクセサは lvalue 属性を持つため、代入できます。次のように使えます。 $app->foo //= 1; これは以下のように書くよりもずっと簡単です。 $app->foo(1) unless defined $app->foo; 以降のすべてのメンバーにアクセサを作成したい場合は、C で C パラメータを設定してください。 Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); 代入可能なアクセサが好きでない場合は、C パラメータを 0 に設定してください。アクセサは C の時点で生成されるため、この値はすべてのメンバーに対して有効です。 =item B => I | I デフォルト値を設定します。デフォルトが与えられない場合、メンバーは C として初期化されます。 値が ARRAY または HASH へのリファレンスである場合、各 C 呼び出しで浅いコピーが作成されます。これは、リファレンス自体はコピーされますが、内容は共有されることを意味します。配列やハッシュの内容を変更すると、すべてのインスタンスに影響します。 コードリファレンスが与えられた場合、B の時点で呼び出され、デフォルト値を取得します。これは、宣言時ではなく実行時に値を評価したい場合に有効です。デフォルトのアクションを定義したい場合は B パラメータを使用してください。コードリファレンス自体を初期値として設定したい場合は、コードリファレンスを返すコードリファレンスを指定する必要があります。 SCALAR へのリファレンスが与えられた場合、オプション値はハッシュオブジェクトのメンバーではなく、そのリファレンスが指すデータに保存されます。この場合、ハッシュメンバーにアクセスしても期待する値は得られません。 =item [ B => ] I パラメータ C はオプションを処理するために呼び出されるコードリファレンスを受け取ります。C<< action => >> ラベルは、最初のパラメータである場合に限り省略できます。 呼び出し時には、ハッシュオブジェクトが C<$_> として渡されます。 has [ qw(left right both) ] => '=i'; has "+both" => sub { $_->{left} = $_->{right} = $_[1]; }; C<< "<>" >> を使って非オプション引数を処理できます。この場合、spec パラメータは重要ではなく、必須でもありません。 has ARGV => default => []; has "<>" => sub { push @{$_->{ARGV}}, $_[0]; }; =back 以下のパラメータはすべてデータ検証用です。まず C は汎用バリデータで、あらゆることを実装できます。他は一般的なルールのためのショートカットです。 =over 7 =item B => I | [ I ... ] パラメータ C はオプション値を検証するコードリファレンスを受け取ります。引数は C と同じで、真偽値を返します。次の例では、オプション B<--answer> は有効な値として 42 のみを受け付けます。 has answer => '=i', must => sub { $_[1] == 42 }; 複数のコードリファレンスが与えられた場合、すべてのコードが真を返さなければなりません。 has answer => '=i', must => [ sub { $_[1] >= 42 }, sub { $_[1] <= 42 } ]; =item B => I =item B => I 引数の最小値と最大値の制限を設定します。 =item B => I | qr/I/ | I 有効な文字列パラメータのリストを設定します。各項目は文字列、正規表現リファレンス、またはコードリファレンスにできます。引数が、与えられたリストのいずれかの項目と同一、または一致する場合に有効です。値が arrayref でない場合は、単一項目のリスト(通常は regexpref か coderef)として扱われます。 以下の宣言はほぼ同等ですが、2 つ目は大文字小文字を区別しません。 has question => '=s', any => [ 'life', 'universe', 'everything' ]; has question => '=s', any => qr/^(life|universe|everything)$/i; オプション引数を使用している場合は、デフォルト値をリストに含めるのを忘れないでください。そうしないと検証エラーになります。 has question => ':s', any => [ 'life', 'universe', 'everything', '' ]; =back =head1 METHOD =head2 B 新しいハッシュオブジェクトを作成するクラスメソッド。すべてのメンバーをデフォルト値で初期化し、設定に従ってアクセサメソッドを作成します。bless されたハッシュリファレンスを返します。LOCK_KEYS が有効な場合、ハッシュキーはロックされます。 =head2 B C 関数に渡すことができるオプション仕様のリストを返します。 GetOptions($obj->optspec) C は、最初の引数としてハッシュリファレンスを与えることで値をハッシュに格納する機能を持ちますが、必須ではありません。 =head2 B [ I ] オプションを処理するために、呼び出し元のコンテキストで定義された適切な関数を呼び出します。 $obj->getopt $obj->getopt(\@argv); 上記の例は、以下のコードに対するショートカットです。 GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) =head2 B I LOCK_KEYS が有効なとき、存在しないメンバーへのアクセスはエラーになります。アクセス前に新しいメンバーキーを宣言するにはこのメソッドを使用してください。 $obj->use_keys( qw(foo bar) ); 任意のキーにアクセスしたい場合は、オブジェクトのロックを解除してください。 use Hash::Util 'unlock_keys'; unlock_keys %{$obj}; この挙動は C の C パラメータで変更できます。 =head2 B B