perl 进程递归地包含文件

问题描述 投票:0回答:1

我想递归处理文件。

我有一个配置文件,该配置文件可以包含“include”语句。一旦识别出包含语句,就应处理该文件。有可能在再次处理的文件中出现包含语句。

所以像这样:

  • 配置文件
  • 第一级工艺线
  • 包含文件(立即处理)
    • 二级工艺线
    • -包含文件(立即处理)-处理并关闭
    • 进一步处理第二级的线路
    • 关闭文件
  • 处理更多第一级线
  • 关闭文件

为了进行管理,我创建了一个子例程: 更新 ---- 求子更新!

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 就会被报告为已关闭。

open 语句的文档说:“将内部 FILEHANDLE 与 EXPR 指定的外部文件关联起来。” 我希望 FILEHANDLE 是独一无二的!

我希望得到一些如何完成此操作的提示!

perl filehandle
1个回答
0
投票

您的文件句柄在子例程之外声明;因此,当您打开新的配置文件并关闭它时,您会覆盖该值。

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

  while(my $av_tmp_LINE = readline($av_fn_FH)) 
  { 
    if ( substr($av_tmp_LINE,0,7) eq "include" )
    {
      my @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);
}

一般来说,您希望在实际使用变量的尽可能小的范围内声明变量。

© www.soinside.com 2019 - 2024. All rights reserved.