日向夏特殊応援部隊

俺様向けメモ

Data::JavaScript, Data::JavaScript::LiteObject, Data::JavaScript::Anon

pirlと共に使ってみました。淡々と紹介します。w

Data::JavaScript

pirl @> use Data::JavaScript; jsdump('hoge', 1);
"var hoge = 1;"
                                                                                                                                                                                    pirl @> use Data::JavaScript; jsdump('hoge', "hogehoge");
"var hoge = \"hogehoge\";"
                                                                                                                                                                                   pirl @> use Data::JavaScript; jsdump('hoge', [ 0 .. 10 ]);
(
  "var hoge = new Array;",
  "hoge[0] = 0;",
  "hoge[1] = 1;",
  "hoge[2] = 2;",
  "hoge[3] = 3;",
  "hoge[4] = 4;",
  "hoge[5] = 5;",
  "hoge[6] = 6;",
  "hoge[7] = 7;",
  "hoge[8] = 8;",
  "hoge[9] = 9;",
  "hoge[10] = 10;",
)
                                                                                                                                                                                    pirl @> use Data::JavaScript; jsdump('hoge', { foo => 1, bar => 2 } );
(
  "var hoge = new Object;",
  "hoge[\"bar\"] = 2;",
  "hoge[\"foo\"] = 1;",
)

もう少し複雑に、

pirl @> use Data::JavaScript; jsdump('hoge', { foo => { hoge => 1 } , bar => [ 0 .. 10 ] } );
(
  "var hoge = new Object;",
  "hoge[\"bar\"] = new Array;",
  "hoge[\"bar\"][0] = 0;",
  "hoge[\"bar\"][1] = 1;",
  "hoge[\"bar\"][2] = 2;",
  "hoge[\"bar\"][3] = 3;",
  "hoge[\"bar\"][4] = 4;",
  "hoge[\"bar\"][5] = 5;",
  "hoge[\"bar\"][6] = 6;",
  "hoge[\"bar\"][7] = 7;",
  "hoge[\"bar\"][8] = 8;",
  "hoge[\"bar\"][9] = 9;",
  "hoge[\"bar\"][10] = 10;",
  "hoge[\"foo\"] = new Object;",
  "hoge[\"foo\"][\"hoge\"] = 1;",
)

少し意地悪に、

pirl @> use Data::JavaScript; jsdump('hoge', { foo => sub { print "hoge" } } );              
("var hoge = new Object;", "")

(><)

Data::JavaScript::LiteObject

バグってる。

pirl @> use Data::JavaScript::LiteObject; jsodump(protoName => "foo", dataRef => []);
("function foo (", "", ") {\n\t", "}\n", " = new foo(", " ", ");\n")

はぁ?

pirl @> use Data::JavaScript::LiteObject; my %data = (foo => 1, bar => 2); jsodump(protoName => "foo", dataRef => \%data);      
ERROR: Can't use string ("2") as a HASH ref while "strict refs" in use at /Library/Perl/5.8.6/Data/JavaScript/LiteObject.pm line 34.

終了。

Data::JavaScript::Anon

pirl @> use Data::JavaScript::Anon; Data::JavaScript::Anon->anon_dump({ foo => 1, bar => { a => 5, b => [0 .. 10] } });         
"{ bar: { a: 5, b: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] }, foo: 1 }"

おお、優秀!

まとめ

Data::JavaScript::Anonを使いましょう。