Serializing code

(Data::Dump::Streamer)

Anton Berezin

tobez@tobez.org

Why serialize code?

 

To be able to specify now some code to execute later (possibly much later, in another process, on another machine) when a specific condition is met.

Callbacks on steroids


add_action(
   condition => ...,
   id => 42,
   action => sub {
      print "Condition is met!\n";
   });

Callback conditions

Serialized code conditions

As for callbacks, plus

Serializing modules


Most of them do not work for code, none of them works for closures.

Closures


if ($product->{state} eq "waiting") {
   my $p_name = $product->{name};
   my $p_id   = $product->{id};
   add_action(
      condition => ...,
      id => 42,
      action => sub {
         my $p = get_product($p_id);
         $p->{state} = "ready";
         $p->save_product;
         print "$p_name is ready\n";
   });
}

Data::Dump::Streamer

Data::Dump::Streamer example


my $id = 42;
my $name = "Larry Wall";
print Data::Dump::Streamer::Dump(sub {
	print "My number is $id\n";
	print "My name is $name (just kidding)\n";
})->Out();

Data::Dump::Streamer output


my ($id,$name);
$id = 42;
$name = 'Larry Wall';
$CODE1 = sub {
   print "My number is $id\n";
   print "My name is $name (just kidding)\n";
};

Dumped code evaluation


my $code = read_streamed_output(from => "somewhere");
my $CODE1 = undef;
eval $code;
unless ($@) {
    $CODE1->();
}

Pitfalls: context


use WeirdModule; # imports &weird_function
store_code_in_the_db(sub {
   weird_function(42);
});
a month later, in a code far, far away:

$CODE1->();
"Undefined subroutine &main::weird_function called"

Inside callbacks

  • require all needed modules;
  • use fully qualified subs;
  • use only simple vars from outside the sub;
  • do not ass-u-me

Thank you.

 

Thank you!

 

Any questions?