【问题标题】:How to print all filenames in a directory while running line by line on all the files如何在所有文件上逐行运行时打印目录中的所有文件名
【发布时间】:2013-01-20 15:14:54
【问题描述】:

我编写的程序会逐行遍历目录和子目录中的所有文件,并执行一些包含 $counter 的命令。 我想制作一个 .txt 文件,每行如下所示:

<file name> <$counter in the beginning of the file>

例如,如果我在文件 a 中有三个文件 a.txt 、 b.txt 和 c.txt ,则计数器在文件 b 中计数为 10,它计数为 20,在文件 c 中计数为 30,文件将如下所示:

a.txt 0
b.txt 10
c.txt 20

我的程序如下所示:

use strict;
use warnings;
use File::Find;

my $dir = "C:/New Folder";   
open (MYFILE, '>>data.txt');

# fill up our argument list with file names:
find(sub { if (-f && /\.[c]$/) { push @ARGV, $File::Find::name } }, $dir);
$^I = ".bak";   # supply backup string to enable in-place edit  

foreach $argvv(@ARGV)
{
  while (<>) 
  {
     if ($prev_arg ne $argvv)
     {
       print MYFILE  "$argvv $counter\n";
       $prev_arg = $argvv;
     }   

     #some unrelated line by line code here
     close (MYFILE); 
  }
}

我试图做的是让程序在每次完成一个文件并启动另一个文件时打印文件名和计数器。

我得到的 data.txt 文件是第一个文件的名称和为目录中每个文件的每一行打印的计数器。 不用说,我完全是 Perl 的菜鸟,所以我非常感谢一些帮助。

谢谢:)

【问题讨论】:

  • 你为什么将找到的文件推送到@ARGV,而不是你声明的数组?

标签: perl filenames


【解决方案1】:

您的代码存在一些问题。

  • 您正在使用strictwarnings,但尚未声明$prev_arg$argvv。警告已告诉您有关它们的信息。
  • 您永远不会打开文件进行阅读。相反,您尝试使用-i 命令行开关和从STDIN 读取的参数列表。这对我来说毫无意义。相反,您应该使用普通数组并一个一个地打开文件。
  • 您正在使用老式的裸字文件句柄和open 的两个参数形式。相反,请使用词法文件句柄,因为它们不是全局的,而是只存在于它们周围的块中。使用open 的三参数形式,这样您就不会遇到安全问题。见here

试试这个:

use warnings;
use strict;
use File::Find;

my $dir = 'D:/temp';   

my @files;
find(
  sub {
    if (-f && /\.c.txt$/) {
      push @files, $File::Find::name }
    },
  $dir
);

open my $fh_out, '>>', 'data.txt'   # open the output filehandle
  or die $!; 
foreach my $file (@files) {         # iterate the file list
  open my $fh_in, '<', $file        # open the current file for reading
    or die $!; 
  my $counter = <$fh_in>;           # read the first line
  chomp $counter;                   # remove trailing linebreak
  close $fh_in; 
  print $fh_out "$file $counter\n"; # close the input filehandle (explicit)
}
close $fh_out;                      # close the output filehandle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2020-03-23
    • 2011-02-04
    • 1970-01-01
    相关资源
    最近更新 更多