有没有办法让Perl支持通配符命令行参数,例如"* .txt"?在Windows上? [英] Is there a way to get Perl to support wildcard command-line arguments like "*.txt" on Windows?

查看:100
本文介绍了有没有办法让Perl支持通配符命令行参数,例如"* .txt"?在Windows上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在* nix系统上将通配符传递给Perl脚本时,例如

When passing wildcard arguments to a Perl script on *nix systems, like

$ perl script.pl *.txt

像Bash这样的shell将扩展所有通配符( * ? [] )匹配,从而填充 @ARGV 并具有所有匹配项.

shells like Bash will expand all wildcard (*, ?, []) matches, consequently populating @ARGV with all matches.

但是,Windows CMD在运行Perl解释器之前不会执行这种扩展.

Windows CMD, however, doesn't perform such an expansion before running the Perl interpreter.

是否有可能让Perl在内部处理此扩展以模仿* nix shell?

Is it possible to get Perl to handle this expansion internally to mimic *nix shells?

推荐答案

核心模块 File :: DosGlob提供了以Windows用户期望的方式扩展通配符的工具,因此使用此模块提供的 glob 只是一个问题,如下所示:

Core module File::DosGlob provides the tools to expand wildcards in the manner a Windows user would expect, so it's just a question to use the glob provided by this module as follows:

use File::DosGlob qw( glob );

@ARGV = map glob, @ARGV;


请注意,使用内置的 glob 进行此操作会破坏包含空格的路径,这在Windows中是相对常见的情况.它还可能会误处理 *.* ,这将返回所有文件.


Note that doing this using the builtin glob would break paths that contain spaces, a relatively common occurrence on Windows. It would also mishandle *.*, which is expected to return all files.

请注意,最好在处理命令行选项后扩展模式,以免冒将模式扩展为命令行选项的风险.

Note that it's best to expand the patterns after processing command-line options to avoid risking expanding the pattern into a command-line option.

use File::DosGlob qw( glob );
use Getopt::Long  qw( GetOptions );

GetOptions(...)
   or die_usage();

@ARGV = map glob, @ARGV;


对于单排,您可以使用以下内容:


For a one-liner, you could use the following:

perl -MFile::DosGlob=glob -ne"BEGIN { @ARGV = map glob, @ARGV } ..." ...

BEGIN 确保在 -n 创建的输入读取循环开始之前运行代码.

The BEGIN ensures the code is run before the input-reading loop created by -n starts.

这篇关于有没有办法让Perl支持通配符命令行参数,例如"* .txt"?在Windows上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆