I miss perl's -B

| | Comments (1)

Perl has a bunch of tests in form of -X path (e.g., -f path returns true if path exists and is a file). We have a direct analog with the test method (e.g., test ?f, path). The one we're missing is -B, which tests whether or not a file is (probably) a binary file. It is great for things like Find-based scripts. Recently I needed it for a script I was writing so I didn't have to keep adding file extensions I didn't want to process. Here it is:

class File
  def self.binary? (path)
    s = (File.read(path, 4096) || "").split(//)
    ((s.size - s.grep(" ".."~").size) / s.size.to_f) > 0.30
  end
end

Now you can write things like:

Find.find dir do |f|
  next if File.binary? f
  # ... process text files only ...
end

1 Comments

Do you want 4096 or File.blksize(path)? Anyway, nice. :)

  • Dan

Leave a comment