Perl文件::查找不起作用

时间:2015-12-16 03:43:47

标签: perl

我想使用Perl File :: Find在目录中搜索字符串,但它不起作用。它给了我一个错误:

  

C:/Perl64/bin/perl.exe D:/DUAN/MailScanner/GetMailForwarder.pl

     

打开文件时出错:D:\ DUAN \ MailScanner \ valiases权限被拒绝

     

流程已完成退出代码13

这是我的代码:

#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
use Data::Dump qw(dump);

my @dirs = 'D:\DUAN\MailScanner\valiases';

## main processing done here
my @found_files = ();
my $pattern = qr/World/;

find( \&wanted, @dirs );

sub wanted
{
    next if ($File::Find::name =~ m/^\./);

    open my $file, '<', $File::Find::name or die "Error openning file: $File::Find::name $!\n";

    while( defined(my $line = <$file>) )
    {
        if ($line =~ /$pattern/)
        {
            push @found_files, $_;
            last;
        }
    }

    close ($file);
}

foreach my $file(@found_files)
{
    print $file, "\n";
}

1 个答案:

答案 0 :(得分:1)

很高兴看到使用严格; - 干得好! 以下次要代码mod应该可以帮助您了解您遇到的任何问题。

use strict;
use warnings;
use File::Find;
use Data::Dump qw(dump);

my @dirs = ('D:\DUAN\MailScanner\valiases', 'D:\DUAN\additionalPath');
foreach my $dir (@dirs)
{
    print "WARNING: $dir is not a directory/folder.\n" unless ( -d $dir );
}

## main processing done here
my @found_files = ();
my $pattern = qr/World/;

find( \&wanted, @dirs );

sub wanted
{
    next if ($File::Find::name =~ m/^\./);
    if (-r $File::Find::name)
    {
        open my $file, '<', $File::Find::name or die "Error reading file: $File::Find::name $!\n";

        while ( my $line = <$file> )
        {
            if ($line =~ m/$pattern/)
            {
                push @found_files, $_;
                last;
            }
        }

        close ($file);
    }
    else
    {
        print "WARNING: $File::Find::name is not readable. Skipping...\n";
    }
}

foreach my $file (@found_files)
{
    print "$file\n";
}