Blessing a JSON into a perl class vs private properties -


i have json structure such as:

{   "field1" => "one",   "field2" => "two",   ... } 

i'm using perl json module, , can bless json returned me class, such as: my $result = bless($json->{output},'myclass')

so far - can create methods within myclass.pm return values of field1, field2, etc. seems via bless, have direct access set properties of object. danger can things later in code like: $result->{field1} = "anythingiwant";

...which not good. know set property _field1 indicate privacy doesn't prevent me doing $result->{_field1} = "anythingiwant";

so there best practice approach in perl handle situation? in other words, it's super convenient able bless json output class deserialize, seems dangerous. i'm looking best of both worlds can still use bless prevent client code doing anythingiwant scenario described above. i've looked moose, insideout etc i'm not sure if either of fit bill or introduce more complexity.

yes, answer bless closure.

this can give read-only access data (once drop original pointer) or both read , write access through accessor method, never directly data:

package myclass;  sub new {     $type = shift;     $class = ref $type || $type;      $self = shift;      $closure = sub {               $self->{$_[0]};         };       return bless $closure, $class; }  package main;  use strict;  $json_snippet = {   "field1" => "one",   "field2" => "two", };  $object = myclass->new($json_snippet);  print($object->("field2"), "\n");  1; 

here's introduction objects private variables


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -