steve-er-rino
steve-er-rino

Reputation: 403

Find::File to search a directory of a list of files

I'm writing a Perl script and I'm new to Perl -- I have a file that contains a list of files. For each item on the list I want to search a given directory and its sub-directories to find the file return the full path. I've been unsuccessful thus far trying to use File::Find. Here's what I got:

use strict;
use warnings;
use File::Find;

my $directory = '/home/directory/';
my $input_file = '/home/directory/file_list'; 
my @file_list;


find(\&wanted, $directory);

sub wanted {
    open (FILE, $input_file);

    foreach my $file (<FILE>) {
        chomp($file);

        push ( @file_list, $file );
    }   

    close (FILE);

    return @file_list;
}

Upvotes: 1

Views: 1924

Answers (3)

titanofold
titanofold

Reputation: 2960

I find File::Find::Rule a tad easier and more elegant to use.

use File::Find::Rule;

my $path = '/some/path';
# Find all directories under $path
my @paths = File::Find::Rule->directory->in( $path );
# Find all files in $path
my @files = File::Find::Rule->file->in( $path );

The arrays contain full paths to the objects File::Find::Rule finds.

Upvotes: 2

steve-er-rino
steve-er-rino

Reputation: 403

Okay, well re-read the doc and I misunderstood the wanted subroutine. The wanted is a subroutine that is called on every file and directory that is found. So here's my code to take that into account

use strict;
use warnings;
use File::Find;

my $directory = '/home/directory/';
my $input_file = '/home/directory/file_list';
my @file_list;

open (FILE, $input_file);

foreach my $file (<FILE>) {
    chomp($file);

    push ( @file_list, $file );
}   

close (FILE);

find(\&wanted, $directory);

sub wanted {
    if ( $_ ~~ @file_list ) { 
        print "$File::Find::name\n";
    }   
    return;
}

Upvotes: 0

hd1
hd1

Reputation: 34657

File::Find is used to traverse a directory structure in the filesystem. Instead of doing what you're trying to do, namely, have the wanted subroutine read in the file, you should read in the file as follows:

use strict;
use warnings;
use vars qw/@file_list/;

my $directory = '/home/directory/';
my $input_file = '/home/directory/file_list'; 
open FILE, "$input_file" or die "$!\n";
foreach my $file (<FILE>) {
    chomp($file);

    push ( @file_list, $file );
} 
# do what you need to here with the @file_list array

Upvotes: 0

Related Questions