曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3825|回复: 0
打印 上一主题 下一主题

文件名通配(glob 操作符 与 < > 表示法)

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
跳转到指定楼层
楼主
发表于 2011-10-11 12:54:00 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
Perl 程序可以接受命令行中的 * 通配符。
先编写一个简单的 Perl 程序:
# cat >show-args
foreach $arg (@ARGV) {
        print "one arg is $arg\n";
}
这里直接使用 cat > 命令形式在命令行中编写的内容输送到 show-args 这个文件中,注意编写完时只要按下 Ctrl + D 即可。

运行下面一小段脚本创建 10 个空的文本文件:
[Bash shell] 纯文本查看 复制代码
for i in {1..10}
do
        touch test$i.txt
done



运行上面的 show-args :
# perl show-args *.txt
one arg is test10.txt
one arg is test1.txt
one arg is test2.txt
one arg is test3.txt
one arg is test4.txt
one arg is test5.txt
one arg is test6.txt
one arg is test7.txt
one arg is test8.txt
one arg is test9.txt
上面命令行中给出的 *.txt 在展开并匹配当前目录下所有的 txt 格式的文件名就放在 @ARGV 变量里。


在程序内部可以使用 *.txt 这样的匹配,此时使用 glob 操作符就可以到达目的。比如:
[Perl] 纯文本查看 复制代码
#!/usr/bin/perl

my @all_files = glob "*";
my @txt_files = glob "*.txt";

foreach (@all_files) {
        print "$_ ";
}
print "\n";

foreach (@txt_files) {
        print "$_ ";
}
print "\n";


运行输出:
# ./glob.pl
glob.pl show-args temp.sh test1.txt test10.txt test2.txt test3.txt test4.txt test5.txt test6.txt test7.txt test8.txt test9.txt
test1.txt test10.txt test2.txt test3.txt test4.txt test5.txt test6.txt test7.txt test8.txt test9.txt
实际上,在 glob 操作符诞生之前,还有另外一种语法,它和 glob 的效果一样,这种写法使用 <> 操作符(<> 里面接一个句柄时它就是一个
钻石操作符
)。对于上面的例子,只需要将开头两句改写成如下语句即又同样效果:
my @all_files = <*>;
my @txt_files = <*.txt>;
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-19 07:21 , Processed in 0.062074 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表