gpt4 book ai didi

perl - 试图在 Perl 中将子目录作为参数传递

转载 作者:行者123 更新时间:2023-12-04 00:43:11 26 4
gpt4 key购买 nike

我有一个用于读取 .html 的 Perl 程序,只有当该程序与 .html 位于同一目录中时才能运行。
我希望能够从不同的目录开始并将 html 的位置作为参数传递。程序(下面的shell例子)遍历子目录“sub”及其子目录以查找 .html,但仅当我的 perl 文件位于同一子目录“子”中时才有效。如果我把 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;
}

最佳答案

documentation of File::Find它说:

You are chdir()'d to $File::Find::dir when the function is called, unless no_chdir was specified. Note that when changing to directories is in effect the root directory (/) is a somewhat special case inasmuch as the concatenation of $File::Find::dir, '/' and $_ is not literally equal to $File::Find::name.

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

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

关于perl - 试图在 Perl 中将子目录作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16527190/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com