Claire
Claire

Reputation: 70

How to store File::Find::name output in an array

I've managed to extract the filenames of my .txt files, but I'm having trouble storing it in an array.

Filenames:

sample1.txt sample2.txt sample3.txt

Code:

sub find_files {
    my $getfile = $File::Find::name;

    if ($getfile =~ m/txt$/) {
         my @sample;

         ($file, $path, $ext) = fileparse($getfile, qr/\..*/);

         push(@sample, "$file");
         print "$sample[0] ";
     }
}

Expected output:

sample1

Output:

sample1 sample2 sample3

Upvotes: 0

Views: 350

Answers (1)

Borodin
Borodin

Reputation: 126722

You are storing each file name in @sample, but that array is declared in far too small a scope and is discarded at the end of the if block, right after the print

This should work rather better. It's also more concise and makes sure that the items found are files, not directories

my @sample;

sub find_files {

    return unless -f and /\.txt\z/i;

    my ($file, $path, $ext) = fileparse($File::Find::name, qr/\.[^.]*\z/);

    push @sample, $file;
}

find(\&find_files, '/my/dir');
print "$_\n" for @sample;

Upvotes: 3

Related Questions