Red Echo

January 30, 2009

Syntax for map/dictionary/hash literals in various languages:

JavaScript: { "foo" : 1, "bar": 2, "baz": 3}
Ruby: { "foo" => 1, "bar" => 2, "baz" => 3 }
Python: {"foo":1, "bar":2, "baz":3}
Clojure: {"foo" 1 "bar" 2 "baz" 3}
Perl: ("foo" => 1, "bar" => 2, "baz" => 3)

6 Comments

  1. PostScript: >

    Perl doesn’t really need the quotes, and isn’t really a hash without the curly braces (though, as a list, it has the potential to become a hash if assigned to a %-prefixed variable).

    Comment by Micah Cowan — February 2, 2009 @ 2:47 am

  2. Aw, it ate my PostScript example. I’ll try again:

    << /foo 1 /bar/ 2 /baz 3 >>

    Comment by Micah Cowan — February 2, 2009 @ 2:48 am

  3. (whoops, extra slash after /bar. *sigh*…)

    Comment by Micah Cowan — February 2, 2009 @ 2:49 am

  4. If Perl doesn’t need the quotes, how do you distinguish between a reference to something named foo and the literal string “foo”? Or does the prefix system make that confusion impossible?

    Comment by Mars Saxman — February 2, 2009 @ 11:11 am

  5. ah, I see, perl variables always begin with $ or @, so a bare identifier in a hash just becomes a string literal. clever.

    Comment by mars — February 6, 2009 @ 12:52 pm

  6. Actually, it’s magic from the => operator. It’s identical to a plain ol’ comma, except that it has the additional property of automagically quoting whatever bareword is on its left. So { foo => 1 } and { "foo", 1 } are identical in meaning. Of course, it only works that way if there’s no whitespace or punctuation in the key, so sometimes people will quote anyway, for consistency across inconsistent keys. They’ll usually still use =>, though, as it makes it a little more clear how the mapping works.

    Comment by Micah Cowan — February 18, 2009 @ 7:31 pm