perl进程递归地插入文件

1hdlvixo  于 12个月前  发布在  Perl
关注(0)|答案(1)|浏览(142)

我想递归地处理文件。
我有一个配置文件,这个配置文件可以包含一个“include”语句。一旦确定了include-statment,该文件将被处理。它可能会发生,在再次处理的文件中,一个include-statement可能会出现。
比如说

  • config文件
  • 第一级工艺路线
  • 包括文件(正在处理)
    • 二级工艺线
    • -包含文件(立即处理)-处理并关闭
    • 处理第二级的更多行
    • 关闭文件
  • 处理更多第一级行
  • 关闭文件

为此,我创建了一个子例程:Update - call for sub updated!

my $av_fn_FH;
my $av_tmp_LINE;
my @av_arr_FN;
sub processfile
{
  open($av_fn_FH, "<", "$_[0]")
  while($av_tmp_LINE = readline($av_fn_FH)) 
  { 
    if ( substr($av_tmp_LINE,0,7) eq "include" )
    {
      @av_arr_FN = split(" ", $av_tmp_LINE); # get the filename from the include statement
      processfile($av_arr_FN[1]); # process the include file
    }
    # do something with "normal" lines
  }
  close($av_fn_FH);
}

这种递归调用子程序的方式不起作用。一旦从子程序返回,HANDLE就被报告为已关闭。
打开语句的文档说:“将内部FILEHANDLE与EXPR指定的外部文件关联。”我希望FILEHANDLE是唯一的!
我会apreciate一些提示如何做到这一点!

laawzig2

laawzig21#

你的文件句柄是在子例程的外部声明的;所以当你打开一个新的配置文件时,你可以覆盖这个值,然后关闭它。

sub processfile
{
    open(my $fh, "<", $_[0])
        or die "Can't open $_[0]: $!";

    while(my $line = readline($fh)) { 
        if ($line =~ /^include\s+(\S+)/) {
            # $1 is the filename after "include "
            processfile($1);   # process the include filename
            next; # skip "normal" stuff below
        }
        # do something with "normal" lines
    }
    close($fh); # optional; closes anywhen when $fh goes out of scope
}

一般来说,你想在尽可能小的范围内声明变量,在那里它们被实际使用。

相关问题