Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete a file that does not have a file extension?

Tags:

perl

How do you delete a file that does not have a file extension?

I'm using Strawberry Perl 5.32.1.1 64 bit version. Here is what I have:

unlink glob "$dir/*.*";

I've also tried the following:

my @file_list;
opendir(my $dh, $dir) || die "can't opendir $dir: $!";
while (readdir $dh){
    next unless -f;    
    push @file_list, $_;
}
closedir $dh;

unlink @file_list;

The result of this is that all files with an extension are deleted,
but those files without an extension remain undeleted.

like image 580
Albertus Avatar asked Dec 14 '22 06:12

Albertus


2 Answers

You don't really explain what the problem is, so this is just a guess.

You're using readdir() to get a list of files to delete and then passing that list to unlink(). The problem here is that the filenames that you get back from readdir() do not include the directory name that you originally passed to readdir(). So you need to populate your array like this:

push @file_list, "$dir/$_";

In a comment you say:

I'm testing unlink glob "$dir/."; but the files without file extensions are not deleted.

Well, if you think about it, you're only asking for files with an extension. If the pattern you pass to glob() contains *.*, then it will only return files that match that pattern (i.e. files with a dot and more text after the dot).

The solution would seem to be to simplify the pattern that you are passing to glob() so it's just *.

unlink glob "$dir/*";

That will, of course, try to delete directories as well, so you might want this instead:

unlink grep { -f } glob "$dir/*";
like image 108
Dave Cross Avatar answered Jan 04 '23 23:01

Dave Cross


You expect glob to perform DOS-like globbing, but the glob function provides csh-like globbing.

  • glob("*.*") matches all files that contains a ., ignoring files with a leading dot.
  • glob("*") matches all files, ignoring files with a leading dot.
  • glob("* .*") matches all files.

Note that every kind of file is matched. This includes directories. In particular, note that . and .. are matched by .*.

If you want DOS-style globs, you can use File::DosGlob.

like image 38
ikegami Avatar answered Jan 05 '23 00:01

ikegami