linux - 如何让 Perl 遍历目录中的所有文件?

标签 linux perl bash

我有一个包含 Perl 脚本

open (FILE, '<', "$ARGV[0]") || die "Unable to open $ARGV[0]\n";

while (defined (my $line = <FILE>)) {
  # do stuff
}

close FILE;

我想在目录中的所有 .pp 文件上运行这个脚本,所以我用 Bash 编写了一个包装器脚本

#!/bin/bash
for f in /etc/puppet/nodes/*.pp; do
    /etc/puppet/nodes/brackets.pl $f
done

问题

是否可以避免包装器脚本并让 Perl 脚本来代替它?

最佳答案

是的。

for f in ...; 转换为 Perl

  • 对于我的 $f (...) { ... }(在列表的情况下)或
  • while (my $f = ...) { ... }(在迭代器的情况下)。

您使用的 glob 表达式 (/etc/puppet/nodes/*.pp) 可以通过 glob function 在 Perl 中计算: glob '/etc/puppet/nodes/*.pp'

连同一些样式改进:

use strict; use warnings;
use autodie;  # automatic error handling

while (defined(my $file = glob '/etc/puppet/nodes/*.pp')) {
  open my $fh, "<", $file;  # lexical file handles, automatic error handling

  while (defined( my $line = <$fh> )) {
    do stuff;
  }
  close $fh;
}

然后:

$ /etc/puppet/nodes/brackets.pl

关于linux - 如何让 Perl 遍历目录中的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18252875/

相关文章:

从另一个 Perl 脚本内部调用时,Perl 搜索和替换命令不起作用

regex - 如何从 Perl 中的逗号分隔字符串中提取单词?

python - 是否有与 perl 的 module-starter 等效的 python?

ruby - 尝试安装 bro 页面 : mime-types requires Ruby version >= 1. 9.2

linux - Shell for 循环,在声明处停止

c - 在这两个函数中为什么需要执行WATCHDOG_RESET()?

linux - shell脚本中的奇怪输出

bash - 如何让带重音的字母在 bash 上实际工作?

linux - 如何使用 find 更改文件和目录名称?

c - Interbench 基准代码