Perl:使用循环还是 Map/Grep?
我正在编写一个程序来逐步浏览目录树(是的,我知道 File::Find,但我正在编写一个替代程序)。
在我的程序中,我对整个目录执行 readdir
并将其放入列表中。我需要做两件事:
- 从列表中删除
.
和..
- 在每个文件上添加当前目录名称。
我可以使用循环来完成此操作,也可以使用 map
和 grep
:
# Map and Grep
my @dir_stack = readdir $dir_fh;;
@dir_stack = grep { !/^\.{1,2}$/ } @dir_stack;
@dir_stack = reverse map { "$cwd/$_" } @dir_stack;
push @stack, @dir_stack;
# Read Loop
opendir $dir_fh, $cwd;
my @dir_stack;
foreach my $file (readdir $dir_fh) {
next if $file =~ /^\.{1,2}$/; #Skip "." and ".."
unshift @dir_stack, "$cwd/$file";
}
push @stack, @dir_stack;
将 grep
和 map
结合起来怎么样? ?
opendir $dir_fh, $cwd;
my @dir_stack = readdir $dir_fh;;
@dir_stack = grep { !/^\.{1,2}$/ && {$_ = "$cwd/$_"} } @dir_stack;
push @stack, reverse @dir_stack;
我希望下周当我查看代码并尝试弄清楚发生了什么时,它可以可读。我还需要我的代码高效。
I'm writing a program to step through a directory tree (Yes, I know about File::Find, but I'm writing a replacement).
In my program, I'm doing a readdir
on a whole directory and placing it in a list. I need to do two things:
- Remove
.
and..
from the list - Prepend the current directory name on each file.
I can do this with a loop, or I can use map
and grep
:
# Map and Grep
my @dir_stack = readdir $dir_fh;;
@dir_stack = grep { !/^\.{1,2}$/ } @dir_stack;
@dir_stack = reverse map { "$cwd/$_" } @dir_stack;
push @stack, @dir_stack;
# Read Loop
opendir $dir_fh, $cwd;
my @dir_stack;
foreach my $file (readdir $dir_fh) {
next if $file =~ /^\.{1,2}$/; #Skip "." and ".."
unshift @dir_stack, "$cwd/$file";
}
push @stack, @dir_stack;
What about combining grep
and map
?
opendir $dir_fh, $cwd;
my @dir_stack = readdir $dir_fh;;
@dir_stack = grep { !/^\.{1,2}$/ && {$_ = "$cwd/$_"} } @dir_stack;
push @stack, reverse @dir_stack;
I want my code to be readable next week when I look at it and try to figure out what's going on. I also need my code to be efficient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在grep中修改
$_
?哎呀!使用匿名哈希构造函数有什么用?应该是
但是我个人发现同时使用map和grep比组合它们更具可读性。
对
reverse
的需求相当奇怪,而且它在这里比隐藏为unshift
更明显,所以这是另一个好处。Modifying
$_
in grep? yuck! And what's with using an anon hash constructor?should be
But I personally find using both map and grep more readable than combining them.
The need for
reverse
is rather odd, and it's much more visible here than hiding as aunshift
, so that's another bonus.为了使您的代码更具可读性,您只需要再添加一行:
:-)
To make your code more readable, you just need to include one more line:
:-)
听起来您可能需要
glob
代替。尽管我相信它将排除所有以.
开头的文件(即隐藏文件),而不仅仅是.
和..
。当然,路径中不能有空格。只要你喂它一条路径,它就会返回。
Sounds like you may want
glob
instead. Though I believe it will exclude all files beginning with.
(i.e. hidden files), not just.
and..
. And of course, you can't have spaces in the path.It will return as long a paths as you feed it.