A Perl script to delete binary files

As a quick note and a little bit of source code sharing, I wrote the following Perl script to delete all of the binary files it finds in a list of files it’s given. I named this script deleteBinaryFiles.pl, and it should be called like this:

deleteBinaryFiles.pl listOfFilesToLookAt

where listOfFilesToLookAt is a file that contains a list of filenames, with one filename per line.

Given that brief introduction, here’s the source code:

#!/usr/bin/perl -w

# ---------------------------------------------------------------
# this script takes a filename as input.
# that file should contain a list of all files (not directories)
#      that this script should examine.
# this script will delete all binary files that are in that list.
# ---------------------------------------------------------------

# 1) open the file that has a list of all of the files that need to be looked at.
#    get this filename from the command line.
$num_args = $#ARGV + 1;
if ($num_args != 1) {
    print "\nUsage: deleteBinaryFiles.pl filename\n";

$listOfFiles = $ARGV[0];

# 2) now go through all of the files in that file.
#    if any of them are binary files, delete them.
open(FILE, $listOfFiles) or die "Could not read from '$listOfFiles', cowardly quitting. $!";

while (<FILE>) {
    $currFile = $_;
    if (-B $currFile) {
        unlink($currFile) or die "Could not delete '$currFile'\n";
        print "   deleted: $currFile\n";


Possibly the only two important things about this example are:

  • The -B file test operator determines if the current file is a binary file.
  • The Perl unlink function is used to delete a file.

I just thought I’d share this source code here, so as a quick summary, if you wanted to see some Perl source code that shows (a) how to check to see if a file is a binary file, and (b) how to delete files in Perl, I hope this is helpful