in reply to Why is "If" condition not working

If you look in the documentation for readdir you will see:

If you're planning to filetest the return values out of a readdir, you'd better prepend the directory in question. Otherwise, because we didn't chdir there, it would have been testing the wrong file.

So if you change your code as follows, it will work:

$dirname = "C:/Perl/Test/"; opendir(DIR,$dirname); @file1 = readdir(DIR); foreach $file1(@file1) { if (-f "$dirname$file1") { print("$file1\n"); } }

Since you're new to Perl, it's the perfect time to learn how to program with 'use strict' in mind. Try this:

use strict; use warnings; use autodie; my $dirname = "C:/Perl/Test/"; opendir my( $dir_handle ), $dirname; my @file1 = readdir $dir_handle; foreach my $file1 ( @file1 ) { if ( -f "$dirname$file1" ) { print "$file1\n"; } }

This is a good time to introduce grep, which can make looping tests that result in a list much simpler.

use feature qw/ say /; use strict; use warnings; use autodie; my $dirname = "C:/Perl/Test/"; opendir my( $dir_handle ), $dirname; my @files = grep { -f "$dirname$_" } readdir $dir_handle; say for @files;

say is a feature of Perl starting with 5.10. It basically just adds a "\n" to every call. my is explained best in perlsub.


Dave