arvindmarlabs has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl use Net::FTP; use Net::FTP::File; my $directory = '/tmp/bkp'; opendir (DIR, $directory) or die $!; while (my $file = readdir(DIR)) { next unless ($file =~ m/\.gz$/); print $file; if( -e $file)
In this script i am trying to get the value in "$file" but the if condition fails like "files not exists" filename like : sample.tar.gz Also how to ignore the . and .. files in directory

Replies are listed 'Best First'.
Re: Need Urgent help in perl
by choroba (Cardinal) on Jul 15, 2015 at 12:45 UTC
    This is a common problem. readdir returns just the file names, not the path, so you have to prepend the directory name:
    my $full_file = "$directory/$file";

    To skip the dot and double dot, just add

    next if $file =~ /^\.{1,2}$/; # or next if $file eq '.' || $file eq '..'; # ...

    at the beginning of the while readdir loop.

    Update: See also File::Find or File::Find::Rule for alternative approaches to walk a directory structure.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Need Urgent help in perl (glob)
by tye (Sage) on Jul 15, 2015 at 13:43 UTC
    for my $file ( glob "$directory/*.gz" ) { ... }

    - tye        

Re: Need Urgent help in perl
by zwon (Abbot) on Jul 15, 2015 at 20:27 UTC
    I'd recommend Path::Tiny for dealing with files
    use Path::Tiny; my $dir = path('/tmp/bkp'); for my $file ($dir->children(qr/\.gz$/)) { say $file; if ($file->exists) { ... } }