Reputation: 1075
I have a directory, /home/textfile/.
I want to use a Perl script to check to see if *.txt file exist in this directory or not. If they do, I want to have it say "Text files exist". Otherwise, if there are no text files in the directory I want it to say "No text files exist".
The text files could have any name. I just want to check if there is a text file in that directory, /home/textfile.
Below is the script I am trying to use:
$filedir = "/home/textfile/";
chdir($filedir);
if (-e "`ls *.txt`")
{
print STDOUT "Text file exist"
}
else
{
print STDOUT "No text file exist"
}
How can I fix this script so it will do what I am looking for it to do?
Upvotes: 0
Views: 2154
Reputation: 61510
From perldoc
about the -X file test operators:
A file test, where X is one of the letters listed below. This unary operator takes one argument, either a filename, a filehandle, or a dirhandle, and tests the associated file to see if something is true about it.
In wrapping the ls
command in double quotes, you are hoping to test the filenames that are returned by ls
, but in reality you are testing for the existence of a file named 'ls *.txt'
.
There are a couple of options. You could use ls
in a separate step to get all of the text file names and then test for the existence of a single one.
my @text_files = `ls *.txt`;
chomp(@text_files);
if ( -e $text_files[0] ) {
...
}
else {
...
}
But since ls
will only return existing files, the -e
check here is not needed at all. You can simply say:
my @text_files = `ls *.txt`;
if ( @text_files ) {
print "Text file exist"
}
else {
print "No Text file exist"
}
I should also note that, since you don't use $dir
in your ls
command, you are not actually looking in the $dir
directory but the current working directory. You would need to add $dir
to the ls
command:
my @text_files = `ls $dir/*.txt`;
if ( @text_files ) {
print "Text file exist"
}
else {
print "No Text file exist"
}
Alternatively, you can use the glob
builtin instead of shelling out to ls
and let Perl manage how to actually read the files. This is generally the more robust and maintainable solution:
my @text_files = glob("$dir/*.txt");
if ( @text_files ) {
print "Text file exist"
}
else {
print "No Text file exist"
}
Upvotes: 0
Reputation: 126732
It's simplest to use glob
to get a list of all files ending with .txt
in that directory. It avoids shelling out to use ls
Like this
use strict;
use warnings;
my $dir = '/home/textfile';
my @files = glob "$dir/*.txt";
print "No " unless @files;
print "Text file exist\n";
Upvotes: 3