初学Perl之四

初学Perl之五

大头 posted @ 2008-11-17 05:21PM in 娱乐 with tags Perl

今天要读取目录中的文件,把所有的txt文件打开用之前的程序分析一下。

先用的是foreach,后来改用while,运行报错,加打印信息看到readdir读进来的文件先是 . 和 .. 。不知道如何筛选目录下读出的文件,搜到一个perl学习笔记,那里找到了实例。

  1. next unless $file =~ /\.TXT$/;

现在可以筛选出所有的txt文件了。

但是有个问题,程序如下:

  1. opendir DH, $dir_to_process;
  2. while($file = readdir DH)
  3. #foreach $file (readdir DH)
  4. {
  5.         print $file, "\n";
  6.         next unless $file =~ /\.TXT$/;
  7.         print "one file in $dir_to_process is $file\n";
  8.         open(FILE, "<$file") or die "open error: $!";
  9.         while(<FILE>)
  10.         {
  11.                 #do something.
  12.         }
  13.         close(FILE);
  14. }

readdir读出一个文件,打印出文件名,然后看是否是txt文件,是的话打印“one file in xxx ……”,然后打开这个文件,一行一行读取。现象是这样,读取某一个文件的时候,报出了open error: No such file or directory。

而这个文件是存在,并且之前打印文件名,打印“one file in xxx ……”都有。可是在打开文件时却出错,说文件不存在,为什么?

Comments Feed


* Login
*