Reputation: 3022
I am trying to list out all text
files in a directory using perl
. The below does run but the resulting file is empty. This seems close but maybe it is not what I need. Thank you :).
get_list.pl
#!/bin/perl
# create a list of all *.txt files in the current directory
opendir(DIR, ".");
@files = grep(/\..txt$/,readdir(DIR));
closedir(DIR);
# print all the filenames in our array
foreach $file (@files) {
print "$file\n";
}
Upvotes: 0
Views: 132
Reputation: 17711
You have one excess dot:
@files = grep(/\..txt$/,readdir(DIR));
should be:
@files = grep(/\.txt$/,readdir(DIR));
Upvotes: 2
Reputation: 53478
As written, your grep is wrong:
@files = grep(/\..txt$/,readdir(DIR));
In regular expressions - .
means any character. So you will find a file called
fish.mtxt
But not a file called
fish.txt
Because of that dot.
You probably want to grep /\.txt/, readdir(DIR)
But personally, I wouldn't bother, and just use glob
instead.
foreach my $file (glob "*.txt") {
print $file,"\n";
}
Also - turn on use strict;
use warnings;
. Consider them mandatory until you know why you want to turn them off. (There are occasions, but you'll know what they are if you ever REALLY NEED to).
Upvotes: 5