Tom
Tom

Reputation: 77

always return false while judge file existence in perl

following example works perfectly for me

if(-e "/tmp/test.txt"){  
  print "the file exists\n";

}else{
  print "no file \n";
}

but if I make changes to get file dynamically it will not work and always rerun false

@files=();
$target="*";
$subdir="Y";
$dir="/tmp/";

find ( \&file_wanted, $dir);

foreach $file (@files ){

    if(-e $file){  
      print "the file exists\n";

    }else{
      print "no file \n";
    }
}

function for file_wanted attached below

sub file_wanted {

    ##########################################################
    #  $_ contains the current filename within the directory
    #  $File::Find::dir contains the current directory name
    #  $File::Find::name contains $File::Find::dir/$_
    #####################################################

    # use regular expression

    #if ( ( $target ne '*' ) &&  !( $_ =~ /$target/ )) { 
    #   return;     
    #}
    if( $target eq '*'){
       if ( $subdir eq 'Y' ) {  
        #recursive subdirectory search
        push @files, "$File::Find::name\n"  if -f; 
       } else  {            
        push @files, "$File::Find::name\n"  if -f && $File::Find::dir eq $dir ;
       }
    }else{
    if ( $subdir eq 'Y' ) {  
    #recursive subdirectory search
        push @files, "$File::Find::name\n"  if -f && $_  =~ /$target/; 
       } else  {            
        push @files, "$File::Find::name\n"  if -f && $File::Find::dir eq $dir && $_  =~ /$target/ ;
       }
   }
}

can anyone advise how this happening and thanks in advance

Upvotes: 1

Views: 177

Answers (1)

ikegami
ikegami

Reputation: 385685

You treat the elements of @files as paths, but they aren't. The elements of @files are paths concatenated with linefeeds.

Change

push @files, "$File::Find::name\n"

to

push @files, $File::Find::name

By the way, using -e that way isn't quite correct. When an error occurs, the file is reported as being non-existent even if it exists. If you wanted to handle errors, you could use the following:

if (-e $qfn) {
   # File exists
   ...
}
elsif ($!{ENOENT}) {
   # File doesn't exist
   ...
}
else {
   # Could not determine if the file exists or not. Error in $!
   ...
}

Upvotes: 3

Related Questions