在 Perl 脚本中处理命令行参数的正确方法是什么?
我正在尝试创建一个在运行时接受命令行参数的脚本/应用程序。当然,这是日常工作,但由于这是我第一次这样做,因此我正在寻求一些指导。假设我的脚本可以采用这些类型的命令行参数:
script -a -p /path/to/pipe -l mail.Error -m [email protected]
script -a -l mail.Error -m [email protected] -p /path/to/pipe
and so on....
由于命令行脚本的灵活性,您可以传递给它的参数可以采用多种顺序,并且可能会丢失/具有无效参数。现在,我知道可以通过非常严格地限制参数的显示方式来解决这个问题(首先 -a
,然后带有路径的 -p
,然后 - l
带有日志设施/优先级,最后 -m
带有有效的电子邮件)并测试它们所有可能出现的情况。
但必须有更好的方法。这(对我来说)效率非常低,我想知道是否有更好的方法来做事。我想保持尽可能的灵活性,让事情正常运转,而不是专注于严格的使用。
I'm trying to create a script/application which accepts command line arguments when run. Of course, this is a day-to-day thing, but seeing as this is the first time I'm doing it, I'm looking for some guidance. Let's say my script can take these kinds of command line arguments:
script -a -p /path/to/pipe -l mail.Error -m [email protected]
script -a -l mail.Error -m [email protected] -p /path/to/pipe
and so on....
Due to the flexible nature of command line scripts, the arguments you can pass to it can some in a variety of orders and could be missing/have invalid arguments. Now, I know this can be solved by being very strict about how the arguments must show up (first -a
, then -p
with a path, then -l
with a log facility/priority and finally -m
with a valid email) and by testing all possible occurrences of them.
But there has to be a better way. This is incredibly inefficient (to me) and I was wondering if there was a better way of doing things. I want to remain as flexible as possible and just make things work instead of focusing on strict usage.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我使用 Getopt::Long 作为参数。
未经测试的示例:
I use Getopt::Long for arguments.
Untested example:
如果您只需要 1 个字符的选项,请使用 Getopt::Std;如果您想支持更长的参数名称,请使用 Getopt::Long。
Use
Getopt::Std
if you only want 1-character options,Getopt::Long
if you want to support longer argument names.Getopt::Long 可以自动将您的命令行解析为哈希变量。命令行上的顺序并不重要。您可以通过检查哈希键来检查是否给出了选项。
Getopt::Long can automatically parse your command line into a hash variable. The order on the command line does not matter. You can check if options are given or not by checking hash keys.