有没有办法让 Perl 支持通配符命令行参数,例如 Windows 上的“*.txt”?
Is there a way to get Perl to support wildcard command-line arguments like "*.txt" on Windows?
在 *nix 系统上将通配符参数传递给 Perl 脚本时,例如
$ perl script.pl *.txt
像 Bash 这样的 shell 将扩展所有通配符 (*
、?
、[]
) 匹配项,从而用所有匹配项填充 @ARGV
。
Windows 但是,CMD 在 运行 Perl 解释器之前不会执行这样的扩展。
是否可以让 Perl 在内部处理这种扩展以模仿 *nix shell?
glob
支持通配符扩展,因此可以使用它来动态更改 @ARGV
:
BEGIN { @ARGV = map +glob, @ARGV; }
BEGIN
块内的 运行 确保 @ARGV
在其余代码被解析之前被修改,更不用说 运行:
A BEGIN
code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed.
核心模块 File::DosGlob 提供了以 Windows 用户期望的方式扩展通配符的工具,因此使用此模块提供的 glob
只是一个问题,如下所示:
use File::DosGlob qw( glob );
@ARGV = map glob, @ARGV;
请注意,使用内置 glob
执行此操作会破坏包含空格的路径,这在 Windows 上比较常见。它还会错误处理 *.*
,预计 return 所有文件。
请注意,最好在处理命令行选项后扩展模式,以避免将模式扩展为命令行选项的风险。
use File::DosGlob qw( glob );
use Getopt::Long qw( GetOptions );
GetOptions(...)
or die_usage();
@ARGV = map glob, @ARGV;
对于单行,您可以使用以下内容:
perl -MFile::DosGlob=glob -ne"BEGIN { @ARGV = map glob, @ARGV } ..." ...
BEGIN
确保代码在 -n
创建的输入读取循环开始之前是 运行。
在 *nix 系统上将通配符参数传递给 Perl 脚本时,例如
$ perl script.pl *.txt
像 Bash 这样的 shell 将扩展所有通配符 (*
、?
、[]
) 匹配项,从而用所有匹配项填充 @ARGV
。
Windows 但是,CMD 在 运行 Perl 解释器之前不会执行这样的扩展。
是否可以让 Perl 在内部处理这种扩展以模仿 *nix shell?
glob
支持通配符扩展,因此可以使用它来动态更改 @ARGV
:
BEGIN { @ARGV = map +glob, @ARGV; }
BEGIN
块内的 运行 确保 @ARGV
在其余代码被解析之前被修改,更不用说 运行:
A
BEGIN
code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed.
核心模块 File::DosGlob 提供了以 Windows 用户期望的方式扩展通配符的工具,因此使用此模块提供的 glob
只是一个问题,如下所示:
use File::DosGlob qw( glob );
@ARGV = map glob, @ARGV;
请注意,使用内置 glob
执行此操作会破坏包含空格的路径,这在 Windows 上比较常见。它还会错误处理 *.*
,预计 return 所有文件。
请注意,最好在处理命令行选项后扩展模式,以避免将模式扩展为命令行选项的风险。
use File::DosGlob qw( glob );
use Getopt::Long qw( GetOptions );
GetOptions(...)
or die_usage();
@ARGV = map glob, @ARGV;
对于单行,您可以使用以下内容:
perl -MFile::DosGlob=glob -ne"BEGIN { @ARGV = map glob, @ARGV } ..." ...
BEGIN
确保代码在 -n
创建的输入读取循环开始之前是 运行。