perl 脚本递归列出目录中的所有文件名

发布于 2024-10-21 05:56:57 字数 498 浏览 1 评论 0原文

我已经编写了以下 perl 脚本,但问题是它总是进入其他部分并且报告不是文件。我在输入中给出的目录中确实有文件。我在这里做错了什么?

我的要求是递归访问目录中的每个文件,打开它并在字符串中读取它。但逻辑的第一部分是失败的。

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

my (@dir) = @ARGV;
find(\&process_file,@dir);

sub process_file {
    #print $File::Find::name."\n";
    my $filename = $File::Find::name;
    if( -f $filename) {
        print " This is a file :$filename \n";
    } else {
        print " This is not file :$filename \n";
    }
}

I have written following perl script but problem is its always going in else part and reporting not a file. I do have files in the directory which I am giving in input. What am I doing wrong here?

My requirement is to recursively visit every file in a directory, open it and read it in a string. But the first part of the logic is failing.

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

my (@dir) = @ARGV;
find(\&process_file,@dir);

sub process_file {
    #print $File::Find::name."\n";
    my $filename = $File::Find::name;
    if( -f $filename) {
        print " This is a file :$filename \n";
    } else {
        print " This is not file :$filename \n";
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月隐月明月朦胧 2024-10-28 05:56:57

$File::Find::name 给出相对于原始工作目录的路径。但是,File::Find 会不断更改当前工作目录,除非您另有说明。

使用 no_chdir 选项,或使用仅包含文件名部分的 -f $_ 。我推荐前者。

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

find({ wanted => \&process_file, no_chdir => 1 }, @ARGV);

sub process_file {
    if (-f $_) {
        print "This is a file: $_\n";
    } else {
        print "This is not file: $_\n";
    }
}

$File::Find::name gives the path relative to original working directory. However, File::Find keeps changing the current working directory unless you tell it otherwise.

Either use the no_chdir option, or use -f $_ which contains just the file name portion. I recommend the former.

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

find({ wanted => \&process_file, no_chdir => 1 }, @ARGV);

sub process_file {
    if (-f $_) {
        print "This is a file: $_\n";
    } else {
        print "This is not file: $_\n";
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文