Perl 进程以递归方式导入文件

perl process inlude files recursively

提问人:averlon 提问时间:8/23/2023 最后编辑:averlon 更新时间:8/24/2023 访问量:61

问:

我想递归处理文件。

我有一个配置文件,这个配置文件可以包含一个“include”语句。一旦识别出包含语句,就应处理该文件。可能会发生这种情况,在再次处理的文件中可能会显示 include-statement。

所以像这样:

  • 配置文件
  • 一级工艺线
  • 包含文件(立即处理)
    • 二级工艺线
    • -include file (process now) - 处理并关闭
    • 第二级加工线
    • 关闭文件
  • 处理更多一级行
  • 关闭文件

为此,我创建了一个子例程: 更新----呼吁更新子更新!

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 文件句柄

评论

1赞 U. Windl 8/23/2023
sub processfile($av_arr_FN[1]); 叫潜艇!也许也可以尝试使用您的代码。use warnings; use strict;
0赞 averlon 8/23/2023
@U.温德尔;你自然是对的。是一个错别字 - 已经在现实世界中纠正了。无论如何。这并不能解决问题!我目前正在研究一个带有模块“FileHandle”的解决方案。这似乎有效,但到目前为止还没有完全测试!

答:

2赞 Jim Davis 8/24/2023 #1

文件句柄是在子例程之外声明的;因此,在打开新的配置文件时会覆盖该值,然后将其关闭。

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
}

通常,您希望在实际使用变量的尽可能小的范围内声明变量。

评论

0赞 U. Windl 8/24/2023
也许更好的风格是使用 .elsenext
0赞 averlon 8/25/2023
@U.Windl谢谢。我想我必须阅读更多关于变量范围的信息。我会试一试!