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

About this Entry

This page contains a single entry by zenspider published on August 18, 2006 12:59 AM.

New and Improved: better full text searching for ri/rdoc/gems was the previous entry in this blog.

risearch getting popular is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Pages

Powered by Movable Type 4.32-en