Build.PL100644000766000024 45514614051562 16237 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601# ========================================================================= # 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 641114614051562 16254 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601Revision history for Perl extension Getopt-EX-Hashed 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 4376214614051562 16020 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601This 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 7714614051562 16621 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601docs/.*\.json docs/.*\.md docs/Makefile examples docker images META.json100644000766000024 373014614051562 16403 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601{ "abstract" : "Hash store object automation for Getopt::Long", "author" : [ "Kazumasa Utashiro" ], "dynamic_config" : 0, "generated_by" : "Minilla/v3.1.23", "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.0601" } }, "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.0601", "x_authority" : "cpan:UTASHIRO", "x_contributors" : [ "Kazumasa Utashiro " ], "x_serialization_backend" : "JSON::PP version 4.12", "x_static_install" : 1 } README.JA.md100644000766000024 3315014614051562 16551 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601# NAME Getopt::EX::Hashed - Getopt::Long 用ハッシュ格納オブジェクトの自動化 # VERSION Version 1.0601 # 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, ... ); たとえば、整数値をパラメータとしてとり、`-n`としても使えるオプション`--number`を定義するには、次のようにします。 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' ] ); `configure`で`DEFAULT`パラメータを設定します。アクセサは`new`時に生成されるので、この値はすべてのメンバに有効です。 - **default** => _value_ | _coderef_ デフォルト値を設定します。デフォルト値が指定されない場合、メンバは`undef`として初期化されます。 値が ARRAY または HASH の参照の場合、同じメンバを持つ新しい参照が割り当てられます。つまり、メンバ・データは複数の`new`呼び出しで共有されます。`new`を複数回呼び出してメンバ・データを変更する場合は注意してください。 コード・リファレンスが与えられると、**new**の実行時に呼び出され、デフォルト値が得られます。これは、宣言ではなく実行時に値を評価したい場合に有効です。デフォルトのアクションを定義したい場合は、**action**パラメータを使用します。 SCALARへの参照が与えられた場合、オプション値はハッシュオブジェクトメンバではなく、参照が示すデータに格納されます。この場合、ハッシュ・メンバにアクセスしても期待値は得られません。 - \[ **action** => \] _coderef_ パラメータ `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_/ 有効な文字列パラメータリストを設定します。各項目は文字列または正規表現参照です。引数は、指定されたリストのいずれかの項目と同じか一致する場合に有効です。値がarrayrefでない場合は、単一の項目リスト(通常は正規表現)とみなされます。 以下の宣言はほぼ等価ですが、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** 初期化されたハッシュオブジェクトを取得するクラスメソッド。 ## **optspec** `GetOptions`関数に渡すことができるオプション指定リストを返します。 GetOptions($obj->optspec) `GetOptions`は、ハッシュ参照を第1引数に与えることで、ハッシュに値を格納する機能を持っていますが、これは必要ありません。 ## **getopt** \[ _arrayref_ \] オプションを処理するために、呼び出し元のコンテキストで定義された適切な関数を呼び出します。 $obj->getopt $obj->getopt(\@argv); 上記の例は、以下のコードのショートカットです。 GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) ## **use\_keys** _keys_ ハッシュキーは`Hash::Util::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) trueを指定すると、読み書き可能なアクセサは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-2024 Kazumasa Utashiro # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. # POD ERRORS Hey! **The above document had some coding errors, which are explained below:** - Around line 153: Unterminated C< ... > sequence README.KO.md100644000766000024 3045314614051562 16573 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601# NAME Getopt::EX::Hashed - Getopt::Long용 해시 저장소 객체 자동화 # VERSION Version 1.0601 # 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, ... ); 예를 들어 정수 값을 매개변수로 사용하며 `-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_에서 옵션 사양 및 별칭 이름은 공백으로 구분되며 어떤 순서로든 표시될 수 있습니다. 정수를 값으로 사용하고 `-s` 및 `--begin`이라는 이름으로도 사용할 수 있는 `--start`라는 옵션을 가지려면 다음과 같이 선언합니다. 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`로 초기화됩니다. 값이 배열 또는 해시 참조인 경우 동일한 멤버를 가진 새 참조가 할당됩니다. 즉, 멤버 데이터가 여러 `new` 호출에 걸쳐 공유됩니다. `new`를 여러 번 호출하여 멤버 데이터를 변경하는 경우 주의하세요. 코드 참조가 주어지면 **new** 시점에 호출되어 기본값을 가져옵니다. 선언이 아닌 실행 시점에 값을 평가하려는 경우에 효과적입니다. 기본 동작을 정의하려면 **action** 매개변수를 사용합니다. SCALAR에 대한 참조가 주어지면 옵션 값은 해시 객체 멤버가 아닌 참조가 나타내는 데이터에 저장됩니다. 이 경우 해시 멤버에 액세스하여 예상 값을 얻을 수 없습니다. - \[ **action** => \] _coderef_ 매개변수 `action`은 옵션을 처리하기 위해 호출되는 코드 참조를 받습니다. `action =>` 레이블은 첫 번째 파라미터인 경우에만 생략할 수 있습니다. 호출되면 해시 객체가 `$_`로 전달됩니다. has [ qw(left right both) ] => '=i'; has "+both" => sub { $_->{left} = $_->{right} = $_[1]; }; 이를 `"<>"`에 사용하여 모든 것을 잡을 수 있습니다. 이 경우 사양 매개변수는 중요하지 않으며 필요하지 않습니다. has ARGV => default => []; has "<>" => sub { push @{$_->{ARGV}}, $_[0]; }; 다음 매개변수는 모두 데이터 유효성 검사를 위한 것입니다. 첫 번째 `must`는 일반적인 유효성 검사기이며 무엇이든 구현할 수 있습니다. 나머지는 일반적인 규칙에 대한 지름길입니다. - **must** => _coderef_ | \[ _coderef_ ... \] 매개변수 `must`는 옵션 값의 유효성을 검사하기 위해 코드 참조를 받습니다. `action`과 동일한 인수를 받고 부울을 반환합니다. 다음 예제에서 옵션 **--답변**은 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_/ 유효한 문자열 매개변수 목록을 설정합니다. 각 항목은 문자열 또는 정규식 참조입니다. 인수는 주어진 목록의 모든 항목과 같거나 일치하는 경우에 유효합니다. 값이 arrayref가 아닌 경우 단일 항목 목록으로 간주됩니다(일반적으로 regexpref). 다음 선언은 두 번째 선언이 대소문자를 구분하지 않는다는 점을 제외하면 거의 동일합니다. 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** 초기화된 해시 객체를 가져오는 클래스 메서드. ## **optspec** `GetOptions` 함수에 전달할 수 있는 옵션 사양 목록을 반환합니다. GetOptions($obj->optspec) `GetOptions`에는 해시 참조를 첫 번째 인자로 제공하여 값을 해시에 저장하는 기능이 있지만, 반드시 필요한 것은 아닙니다. ## **getopt** \[ _arrayref_ \] 호출자의 컨텍스트에 정의된 적절한 함수를 호출하여 옵션을 처리합니다. $obj->getopt $obj->getopt(\@argv); 위의 예는 다음 코드를 위한 단축키입니다. GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) ## **use\_keys** _keys_ 해시 키는 `Hash::Util::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_`로 정의된 경우, 멤버 `파일`에 대한 접근자는 `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-2024 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 2433714614051562 16607 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601# NAME Getopt::EX::Hashed - Getopt::Long 的哈希存储对象自动化 # VERSION Version 1.0601 # 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` 并更改成员数据,请务必小心。 如果给出代码引用,则在 **new** 时调用该代码引用以获取默认值。当您想在执行时而不是在声明时评估值时,这种方法非常有效。如果要定义默认操作,请使用 **action** 参数。 如果给出 SCALAR 的引用,则选项值将存储在引用所指示的数据中,而不是哈希对象成员中。在这种情况下,无法通过访问哈希对象成员获得预期值。 - \[ **action** => \] _coderef_ 参数 `action` 带有处理选项时调用的代码引用。如果 `> 标签是第一个参数,则可以省略。 调用时,哈希对象作为 `$_` 传递。 has [ qw(left right both) ] => '=i'; has "+both" => sub { $_->{left} = $_->{right} = $_[1]; }; 您可以将其用于 `"<>">> 来捕获所有内容。在这种情况下,规格参数并不重要,也不是必需的。` has ARGV => default => []; has "<>" => sub { push @{$_->{ARGV}}, $_[0]; }; 以下参数均用于数据验证。首先,`must` 是一个通用验证器,可以实现任何功能。其他参数是通用规则的快捷方式。 - **must** => _coderef_ | \[ _coderef_ ... \] 参数 `must` 需要一个代码引用来验证选项值。它接收与 `action` 相同的参数,并返回布尔值。在下一个例子中,选项 **--answer** 只接受 42 作为有效值。 has answer => '=i', must => sub { $_[1] == 42 }; 如果给出多个代码引用,则所有代码都必须返回 true。 has answer => '=i', must => [ sub { $_[1] >= 42 }, sub { $_[1] <= 42 } ]; - **min** => _number_ - **max** => _number_ 设置参数的最小和最大限制。 - **any** => _arrayref_ | qr/_regex_/ 设置有效的字符串参数列表。每项都是字符串或 regex 引用。当参数与给定列表中的任何一项相同或匹配时,参数有效。如果参数值不是数组反射,则将其视为单项列表(通常是 regexpref)。 以下声明几乎等同,只是第二个声明不区分大小写。 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** 获取初始化哈希对象的类方法。 ## **optspec** 返回可提供给 `GetOptions` 函数的选项说明列表。 GetOptions($obj->optspec) `GetOptions` 可以通过将哈希引用作为第一个参数,将值存储在哈希对象中,但这并不是必须的。 ## **getopt** \[ _arrayref_ \] 调用调用者上下文中定义的适当函数来处理选项。 $obj->getopt $obj->getopt(\@argv); 以上示例是以下代码的快捷方式。 GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) ## **use\_keys** _keys_ 由于哈希键受 `Hash::Util::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) 如果设置为 true,读写访问器将具有 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-2024 Kazumasa Utashiro # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. # POD ERRORS Hey! **The above document had some coding errors, which are explained below:** - Around line 153: Unterminated C< ... > sequence README.md100644000766000024 2615214614051562 16264 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601[![Actions Status](https://github.com/kaz-utashiro/Getopt-EX-Hashed/workflows/test/badge.svg)](https://github.com/kaz-utashiro/Getopt-EX-Hashed/actions) [![MetaCPAN Release](https://badge.fury.io/pl/Getopt-EX-Hashed.svg)](https://metacpan.org/release/Getopt-EX-Hashed) # NAME Getopt::EX::Hashed - Hash store object automation for Getopt::Long # VERSION Version 1.0601 # 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 a hash object to store command line option values for **Getopt::Long** and compatible modules including **Getopt::EX::Long**. Module name shares **Getopt::EX** prefix, but it works independently from other modules in **Getopt::EX**, so far. Major objective of this module is integrating initialization and specification into single place. It also provides 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 a 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 array reference is given, multiple names can be declared at once. has [ 'left', 'right' ] => ( spec => "=i" ); If the name start with plus (`+`), given parameter updates existing setting. has '+left' => ( default => 1 ); As for `spec` parameter, label can be omitted if it is the first parameter. has left => "=i", default => 1; If the number of parameter is not even, default label is assumed to be exist at the head: `action` if the first parameter is 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"; Above declaration will be compiled into the next string. start|s|begin=i which conform to `Getopt::Long` definition. Of course, you can write as this: 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"; Above declaration will be compiled into the next string. a_to_z|a-to-z=s If nothing special is necessary, give empty (or white space only) string as a value. Otherwise, it is not considered as an option. - **alias** => _string_ Additional alias names can be specified by **alias** parameter too. There is no difference with ones in `spec` parameter. has start => "=i", alias => "s begin"; - **is** => `ro` | `rw` To produce accessor method, `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 accessor for all following members, use `configure` to set `DEFAULT` parameter. Getopt::EX::Hashed->configure( DEFAULT => [ is => 'rw' ] ); If you don't like assignable accessor, configure `ACCESSOR_LVALUE` parameter to 0. Because accessor is 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 for ARRAY or HASH, new reference with same member is assigned. This means that member data is shared across multiple `new` calls. Please be careful if you call `new` multiple times and alter the member data. 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 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 catch everything. In that case, spec parameter does not matter and 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 shortcut for common rules. - **must** => _coderef_ | \[ _coderef_ ... \] Parameter `must` takes a code reference to validate option values. It takes same arguments as `action` and returns boolean. With next example, option **--answer** takes only 42 as a valid value. has answer => '=i', must => sub { $_[1] == 42 }; If multiple code reference is given, all code have to 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_/ Set the valid string parameter list. Each item is a string or a regex reference. The argument is valid when it is same as, or match to any item of the given list. If the value is not an arrayref, it is taken as a single item list (regexpref 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** Class method to get initialized hash object. ## **optspec** Return option specification list which can be given to `GetOptions` function. GetOptions($obj->optspec) `GetOptions` has a capability of storing values in a hash, by giving the hash reference as a first argument, but it is not necessary. ## **getopt** \[ _arrayref_ \] Call appropriate function defined in caller's context to process options. $obj->getopt $obj->getopt(\@argv); Above examples are shortcut for following code. GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) ## **use\_keys** _keys_ Because hash keys are protected by `Hash::Util::lock_keys`, accessing non-existent member causes an error. Use this function to declare new member key before use. $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 in the area unique for calling package. After calling `new()`, package unique configuration is copied in the object, and it is used for further operation. Use `$obj->configure()` to update object unique configuration. There are following configuration parameters. - **LOCK\_KEYS** (default: 1) Lock hash keys. This avoids accidental access to non-existent hash entry. - **REPLACE\_UNDERSCORE** (default: 1) Produce alias with underscores replaced by dash. - **REMOVE\_UNDERSCORE** (default: 0) Produce alias with underscores removed. - **GETOPT** (default: 'GetOptions') - **GETOPT\_FROM\_ARRAY** (default: 'GetOptionsFromArray') Set function name called from `getopt` method. - **ACCESSOR\_PREFIX** (default: '') When specified, it is prepended to the member name to make accessor method. If `ACCESSOR_PREFIX` is defined as `opt_`, accessor for member `file` will be `opt_file`. - **ACCESSOR\_LVALUE** (default: 1) If true, read-write accessors have lvalue attribute. Set zero if you don't like that behavior. - **DEFAULT** Set default parameters. At the call for `has`, DEFAULT parameters are inserted before argument parameters. So if both include same parameter, later one in argument list has precedence. Incremental call with `+` is not affected. Typical use of DEFAULT is `is` to prepare accessor method 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-2024 Kazumasa Utashiro # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. cpanfile100644000766000024 31714614051562 16444 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601requires '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 3245514614051562 20131 0ustar00utashirostaff000000000000Getopt-EX-Hashed-1.0601/docs=encoding utf-8 =head1 NAME Getopt::EX::Hashed - Getopt::Long 用ハッシュ格納オブジェクトの自動化 =head1 VERSION Version 1.0601 =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<-n>としても使えるオプションC<--number>を定義するには、次のようにします。 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 特に何もする必要がない場合は、空文字列(または空白のみ)を値として与えます。そうでない場合は、オプションとはみなされません。 =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でCパラメータを設定します。アクセサはC時に生成されるので、この値はすべてのメンバに有効です。 =item B => I | I デフォルト値を設定します。デフォルト値が指定されない場合、メンバはCとして初期化されます。 値が ARRAY または HASH の参照の場合、同じメンバを持つ新しい参照が割り当てられます。つまり、メンバ・データは複数のC呼び出しで共有されます。Cを複数回呼び出してメンバ・データを変更する場合は注意してください。 コード・リファレンスが与えられると、Bの実行時に呼び出され、デフォルト値が得られます。これは、宣言ではなく実行時に値を評価したい場合に有効です。デフォルトのアクションを定義したい場合は、Bパラメータを使用します。 SCALARへの参照が与えられた場合、オプション値はハッシュオブジェクトメンバではなく、参照が示すデータに格納されます。この場合、ハッシュ・メンバにアクセスしても期待値は得られません。 =item [ B => ] I パラメータ C は、オプションを処理するために呼び出されるコード参照をとます。C<> ラベルは、それが最初のパラメータである場合に限り、省略することができます。 呼び出されたとき、ハッシュオブジェクトは 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/ 有効な文字列パラメータリストを設定します。各項目は文字列または正規表現参照です。引数は、指定されたリストのいずれかの項目と同じか一致する場合に有効です。値がarrayrefでない場合は、単一の項目リスト(通常は正規表現)とみなされます。 以下の宣言はほぼ等価ですが、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 初期化されたハッシュオブジェクトを取得するクラスメソッド。 =head2 B C関数に渡すことができるオプション指定リストを返します。 GetOptions($obj->optspec) Cは、ハッシュ参照を第1引数に与えることで、ハッシュに値を格納する機能を持っていますが、これは必要ありません。 =head2 B [ I ] オプションを処理するために、呼び出し元のコンテキストで定義された適切な関数を呼び出します。 $obj->getopt $obj->getopt(\@argv); 上記の例は、以下のコードのショートカットです。 GetOptions($obj->optspec) GetOptionsFromArray(\@argv, $obj->optspec) =head2 B I ハッシュキーはCによって保護されているため、存在しないメンバにアクセスするとエラーになります。この関数を使用して、新しいメンバー・キーを宣言してから使用してください。 $obj->use_keys( qw(foo bar) ); 任意のキーにアクセスしたい場合は、オブジェクトのロックを解除してください。 use Hash::Util 'unlock_keys'; unlock_keys %{$obj}; この動作はCのCパラメータで変更できます。 =head2 B B