【问题标题】:Trying to pass a subdirectory as a parameter in Perl尝试在 Perl 中将子目录作为参数传递
【发布时间】:2013-05-07 18:57:57
【问题描述】:

我有一个 Perl 程序来读取 .html 文件,并且仅当程序与 .html 文件位于同一目录时才有效。
我希望能够从不同的目录开始并将 html 的位置作为参数传递。程序(下面的shell示例)遍历子目录“sub” 及其子目录来查找 .html,但仅当我的 perl 文件位于同一子目录“sub”中时才有效。如果我把 Perl 文件 在从子目录“sub”退一步的主目录中,它不起作用。

在 shell 中,如果我从我的主目录中键入“perl project.pl ./sub”,它会说可以 未打开 ./sub/file1.html。无此文件或目录。然而,该文件确实存在于那个确切的位置。 file1.html 是它尝试读取的第一个文件。

如果我将 shell 中的目录更改为该子目录并移动 .pl 文件 在那里,然后在 shell 中说:“perl project.pl ./”一切正常。

为了搜索目录,我一直在使用我在这里找到的 File::Find 概念: How to traverse all the files in a directory; if it has subdirectories, I want to traverse files in subdirectories too Find::File to search a directory of a list of files

#!/usr/bin/perl -w
use strict;
use warnings;
use File::Find;

find( \&directories, $ARGV[0]);

sub directories {
    $_ = $File::Find::name;

    if(/.*\.html$/){#only read file on local drive if it is an .html
        my $file = $_;
        open my $info, $file or die "Could not open $file: $!";
        while(my $line = <$info>)  {   

        #perform operations on file
        }
        close $info;
    }
    return;
}

【问题讨论】:

    标签: perl


    【解决方案1】:

    documentation of File::Find 中写道:

    当函数被调用时,你是 chdir()'d 到 $File::Find::dir, 除非指定了 no_chdir。请注意,更改目录时 实际上根目录 (/) 是一种特殊情况 因为 $File::Find::dir、'/' 和 $_ 的连接不是 字面上等于 $File::Find::name。

    所以你实际上已经在~/sub了。仅使用文件名,即$_。您不需要覆盖它。删除该行:

    $_ = $File::Find::name; 
    

    【讨论】:

      【解决方案2】:

      find 自动更改目录,使$File::Find::name 不再与当前目录相关。

      您可以删除此行以使其正常工作:

      $_ = $File::Find::name;
      

      另见File::Findno_chdir

      【讨论】:

        【解决方案3】:

        来自File::Find 文档:

        对于找到的每个文件或目录,它调用 &wanted 子例程。 (有关如何使用 &wanted 功能的详细信息,请参见下文)。 此外,对于找到的每个目录,它将 chdir() 进入该目录 目录 并继续搜索,调用 &wanted 函数 目录中的每个文件或子目录。

        (强调我的)

        它没有找到./sub/file1.html 的原因是,当调用open 时,File::Find 已经chdir 将您发送到./sub/。您应该能够以 file1.html 的身份打开文件。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-25
          • 1970-01-01
          • 1970-01-01
          • 2019-09-14
          • 2019-04-25
          • 2017-10-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多