json - Really weird perl syntax error adding TO_JSON method to package -


in adding to_json method (to convert blessed reference via json.pm) cgi::cookie if this:

package cgi::cookie; sub to_json {     return {         map { name => $_->name,               value => $_->value,               domain => $_->domain,               path => $_->path,               expires => $_->expires }             shift     } } 

syntax error @ xxx.pm line 76, near "shift " syntax error @ xxx.pm line 77, near "}" compilation failed in require @ (eval 50) line 3.

but if this:

package cgi::cookie; sub to_json {     return {         map { ''.'name' => $_->name,               value => $_->value,               domain => $_->domain,               path => $_->path,               expires => $_->expires }             shift     } } 

it works

can't life of me figure out why. quoting "name" doesn't help. have to concatenate empty string work.

i'm mystified.

the perl grammar bit ambiguous when comes blocks , anonymous hashrefs. when perl cannot guess correctly, can force correct interpretation:

  • hashref +{ ... }
  • codeblock {; ... }

forcing block after map codeblock resolves issue. thought block anonymous hash, , missed comma before shift: map can of form map expr, list, , hashref valid expression.


the sub uses misuses map assign 1 element $_. better written:

sub to_json {     $o = shift; # $_ should work well, beside point     return +{        name    => $o->name,        value   => $o->value,        domain  => $o->domain,        path    => $o->path,        expires => $o->expires,     }; } 

but abbreviated to

sub to_json {     $o = shift;     return +{        map { $_ => $o->$_() } qw/name value domain path expires/     }; } 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -