http://hi.baidu.com/dayouluo/blog/item/09ef2e730727ff0c8601b062.html

刚开始接触Perl,之前对脚本语言接触的也不多,php也只是略知一二。

最近使用了Perl中的glob函数,觉得真的很神奇。

之前我对于目录中的文件读取操作比较复杂,首先是用opendir打开目录,再用readdir读取目录中的文件。最近在读别人的代码时发现了 glob,最初以为是定义为全局变量的标示符(和局部变量的标示符my有些类似 perl笛卡尔积_职场 ),后来经过调试之后,发现了Glob的真正作用。它非常方便的就可以读取某个目录下的文件名。

比如要读取/home/globtest目录中的所有.pl文件,可以这样写:

@plFiles = glob '/home/globtest/*.pl';

而且可以使用其他的通配符,比如:?,[ ]

看了glob的文档之后,还发现了glob的另一个作用,可以做类似笛卡尔积的操作。

比如文档中的例子是

  @many = glob "{apple,tomato,cherry}={green,yellow,red}";

把@many数组输出就能看到会显示:

1 apple=green
2 apple=yellow
3 apple=red
4 tomato=green
5 tomato=yellow
6 tomato=red
7 cherry=green
8 cherry=yellow
9 cherry=red
   

对于多组{ }也是可以支持的,我测试了

1 @many glob "{a,b,c}={d,e,f,g}={x,y,z}";

得到了预想中的结果。

在测试中我发现glob对于空白符的处理有些特殊,而且似乎用转义字符时也会有问题。

具体的原因应该在平时使用glob时会慢慢的了解吧~ perl笛卡尔积_休闲_02

下面是Perl中关于Glob的文档:

glob

In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell /bin/csh would do. In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted. This is the internal function implementing the <*.c> operator, but you can use it directly. If EXPR is omitted, $_ is used. The <*.c> operator is discussed in more detail in I/O Operators in perlop.

Note that glob splits its arguments on whitespace and treats each segment as separate pattern. As such, glob("*.c *.h") matches all files with a .c or .h extension. The expression glob(".* *") matchs all files in the current working directory.

If non-empty braces are the only wildcard characters used in the glob, no filenames are matched, but potentially many strings are returned. For example, this produces nine strings, one for each pairing of fruits and colors:

1 @many glob "{apple,tomato,cherry}={green,yellow,red}";

Beginning with v5.6.0, this operator is implemented using the standard File::Glob extension. See File::Glob for details, including bsd_glob which does not treat whitespace as a pattern separator.