两种形式的 Perl 文件名通配符命令的区别 [英] Difference between two forms of Perl filename wildcard command

查看:31
本文介绍了两种形式的 Perl 文件名通配符命令的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl 文件名通配符命令有两种形式:<>glob.但是我发现这两种形式的效果是有区别的:

There are two forms of Perl filename wildcard command: <> and glob. But I found there is difference between the effect of these two forms:

我想使用以下代码检索所有具有相似名称的文件:

I want to retrieve all the files with similar names, using following code:

my @files = <"rawdata/*_${term}_*.csv">;   #(1)

和另一种格式:

my @files = glob "rawdata/*_${term}_*.csv";  #(2)

我希望使用这两个代码获得相同的结果.但是有区别:如果 $term 是一个没有空格的字符串(或者说,一个单词),那么 (2) 运行良好,但 (1) 不起作用;如果 $term 是一个带空格的字符串(或者说,几个单词),那么 (1) 效果很好,(2) 不起作用.

I expect to get the same result using these two codes. But there is difference: if the $term is a string without spaces (or to say, one word), then (2) works well, but (1) doesn't work; if the $term is a string with spaces (or to say, several words), then (1) works well, (2) doesn't work.

这两个表达有什么区别吗?非常感谢.

Is there any difference between these two expressions? Thanks a lot.

推荐答案

等价于 glob "SomeStuff"(除了所有与 <> 也用于从文件句柄读取——参见 perldoc perlop 并在那里寻找 I/O Operators).因此,您的示例并不等效.你应该使用

<SomeStuff> is equivalent to glob "SomeStuff" (apart from all the ambiguities with <> also being used for reading from file handles -- see perldoc perlop and look for I/O Operators there). Therefore your examples aren't equivalent. You should use

my @files = glob "\"rawdata/*_${term}_*.csv\"";  #(2)

相反.

然而,至于为什么模式中的空间会有所不同:perldoc -f glob 讲述了这个故事.普通的 glob(因此通过 glob 实现的 <>)将空格视为模式分隔符.该文档还提到了 File::Glob 及其函数 bsd_glob,它不将空格视为模式分隔符.因此,请考虑使用它:

However, as to why space in the pattern makes a difference: perldoc -f glob tells the story. The normal glob (and therefore <> which is implemented via glob) treat whitespace as a pattern separator. The documentation also mentions File::Glob and its function bsd_glob which does not treat spaces as pattern separators. Therefore consider using this instead:

use File::Glob ':glob';

my $term1  = "some stuff";
my @files1 = glob "dir/${term1}*";
my $term2  = "more";
my @files2 = glob "dir/${term2}*";

print join(' :: ', sort @files1), "\n", join(' :: ', sort @files2), "\n";

我刚刚创建的一些文件的可能输出:

Possible output with some files I just created:

[0 mosu@tionne ~/tmp] ~/test/test1.pl
dir/some stuff is betther than other stuff.doc :: dir/some stuffy teachers.txt
dir/more beer.txt :: dir/more_is_less.csv

这篇关于两种形式的 Perl 文件名通配符命令的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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