This is part 2 in my terse hashes in emacs lisp series
- Terse Hashes in Emacs Lisp
- Data::Dumper in Emacs Lisp
- Terse Hash Dereferencing
- Terse Hashes Miscellany
Another thing I like about Perl data structures, is that once I have stuffed all my data in there, I can easily see what it looks like with Data::Dumper
.
my $data = { list1 => [ { x => 'y' }, { a => 'b' }, # etc ... ], # etc ... } print Dumper($data);
And the result is:
$VAR1 = { 'list1' => [ { 'x' => 'y' }, { 'a' => 'b' } ] };
This is a big help with Exploratory Programming as you can see if you’re stuffing values in the right place.
You might be surprised to learn that I want the same functionality in Emacs Lisp.
(defun hash-dumper (hash &optional indent) (when (null indent) (setq indent 0)) (let (lines indent-string) (setq indent-string "") (dotimes (i indent) (setq indent-string (concat " " indent-string))) (maphash (lambda (k v) (if (hash-table-p v) (push (format "%s =>\n%s" k (hash-dumper v (+ indent 2))) lines) (push (format "%s => %s" k v) lines))) hash) (concat (format "%s{" indent-string) (mapconcat #'identity lines (format "\n%s " indent-string)) "}")))
And the result…
(defvar %hash) (setq %hash (_h { 1 2 'h (_h { 3 4 5 6 'h2 (_h { 1 2 3 [5 6 7] 'vh (vector (_h { 1 2 }) (_h { 3 4 })) }) }) })) ;; (insert (format "\n%s" (hash-dumper %hash))) {h => {h2 => {vh => [#<hash-table 'eql nil 1/65 0x17cce80> #<hash-table 'eql nil 1/65 0x16f0a00>] 3 => [5 6 7] 1 => 2} 5 => 6 3 => 4} 1 => 2}
Not bad, but not quite right. Fixing the problem with lists of hashes is left as an exercise for the reader.
Advertisements
As of Emacs 23.2, released just a month ago, hash tables have a printed s-exp representation, so this problem has been solved, recursively too, for any version of Emacs from here on. The normal printer and reader functions can be used now.
Since at least 2008 Emacs has also come with a JSON library, which works with hash tables. (require ‘json)
Neither of these pretty prints, with nice indenting, though. I guess that’s for another tool, like yours, to do.
Aw man, I’m a month too late (although I have a couple more ideas for my _h macro).