Feeds:
Posts
Comments

Posts Tagged ‘data dumper’

This is part 2 in my terse hashes in emacs lisp series

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.

Read Full Post »

Follow

Get every new post delivered to your Inbox.