0

我有点陷入关于如何从 perl 脚本中声明 grep 的问题。我想要做的是让我的 perl 脚本执行以下命令:

cat config.ini | grep -v "^#" | grep -v "^$"

通常,此表达式将清理/过滤所有以 # 和 $ 开头的条目并打印配置的变量。

但是我不知道如何声明它。我已经使用了下一个表达式,但是当我要引入 grep # 或 $ 时,它失败了

system("(cat config.ini| grep ........);

有什么建议吗?

4

3 回答 3

4
cat config.ini | grep -v "^#" | grep -v "^$"

是一种糟糕的写作方式

grep -v "^[#$]" config.ini

产生字符串

grep -v "^[#$]" config.ini

您可以使用字符串文字

'grep -v "^[#$]" config.ini'

所以

system('grep -v "^[#$]" config.ini');
die("Killed by signal ".($? & 0x7F)."\n") if $? & 0x7F;
die("Exited with error ".($? >> 8)."\n") if $? >> 8;

system('grep -v "^[#$]" config.ini');

简称

system('/bin/sh', '-c', 'grep -v "^[#$]" config.ini');

但是我们不需要shell,所以可以使用以下代码:

system('grep', '-v', '^[#$]', 'config.ini');
die("Killed by signal ".($? & 0x7F)."\n") if $? & 0x7F;
die("Exited with error ".($? >> 8)."\n") if $? >> 8;

但是在 Perl 中这样做会更干净、更健壮。

open(my $fh, '<', 'config.ini')
   or die($!);

while (<$fh>) {
   print if !/^[#$]/;
}
于 2015-06-30T12:54:23.563 回答
3

如果您grep从 Perl 程序内部进行外部调用,那么您做错了。没有什么grep是 Perl 不能为你做的。

while (<$input_filehandle>) {
  next if /^[#$]/; # Skip comment lines or empty lines.

  # Do something with your data, which is in $_
}

更新:进一步考虑这一点,我想我会稍微不同地写它。

while (<$input_filehandle>) {
  # Split on comment character - this allows comments to start
  # anywhere on the line.
  my ($line, $comment) = split /#/, $_, 2;

  # Check for non-whitespace characters in the remaining input.
  next unless $line =~ /\S/;

  # Do something with your data, which is in $_
}
于 2015-06-30T12:54:44.487 回答
0
print if !(/^#/|/^$/);

I did try using the expression suggested but didn't work as good as this one, is there a way to reduce it or write ir in a better way?

于 2015-07-16T11:53:37.457 回答