Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Created November 11, 2015 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XoseLluis/7d7c9b2f1c71fee153dc to your computer and use it in GitHub Desktop.
Save XoseLluis/7d7c9b2f1c71fee153dc to your computer and use it in GitHub Desktop.
TypedSerializer.pm
package City;
use strict;
use warnings;
sub New
{
my ($type, $name) = @_;
my $self = {
name => $name,
};
return bless $self, $type;
}
sub SaySomething
{
my $self = shift;
return $self->{"name"} . " is saying something";
}
1;
package Person;
use strict;
use warnings;
sub New
{
print "Person::new called\n";
my $type = shift;
my $name = shift;
# Reference to empty hash
my $self = {
name => $name,
lastName => undef,
city => undef,
places => {
Asturies => "Uvieu",
Germany => "Berlin",
France => "Toulouse"
}
};
return bless $self, $type;
}
sub SayHi
{
my $self = shift;
return $self->{"name"} . " is saying Hi";
}
sub SetName{
my ($self, $name) = @_;
$self->{name} = $name;
}
sub GetName{
my $self = shift;
return $self->{name};
}
sub SetCity{
my ($self, $city) = @_;
$self->{city} = $city;
}
sub GetCity{
my $self = shift;
return $self->{city};
}
1;
package TypedSerializer;
use strict;
#Data::Dumper::Dump stringifies the content of the object and wraps it in a call to bless with the corresponding type,
#the main problem is that it adds this assignment " $VAR1 = bless(" ,
#if we pass this string directly to eval, it will fail because of that "$VAR1 = ", so we just need to remove "$VAR1 = " from the string
#so we either use Terse to directly prevent it from going to the string, or we just remove it with substr or a regex
use Data::Dumper;
sub New{
my ($class) = @_;
my $self = {
};
return bless $self, $class;
}
sub Serialize{
my ($self, $item) = @_;
my $str = Dumper($item);
return substr($str, length('$VAR1 = '));
}
#bear in mind that when the object is deserialized, the "constructor", New, is not called
sub Deserialize{
my ($self, $str) = @_;
return eval $str;
}
1;
package TypedSerializerTest;
use 5.010;
use strict;
use warnings;
use Person;
use City;
use TypedSerializer;
my $p1 = Person->New("Francois");
$p1->SetCity(City->New("Paris"));
print $p1->SayHi() . "\n";
my $serializer = TypedSerializer->New();
my $serializedSt = $serializer->Serialize($p1);
print "serialization done\n";
print "serialized object:\n" . $serializedSt . "\n";
my $p2 = $serializer->Deserialize($serializedSt);
print "deserialization done\n";
print "- p2 type: " . ref($p2) . "\n";
print "- p2.City type: " . ref($p2->GetCity()) . "\n";
print $p2->SayHi() . "\n";
print $p2->GetCity()->SaySomething() . "\n";
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment