So you want something like
use Script (); # Data extracted from XML. my %snippets = ( onInit => 'use strict; my $x=2;', onAwaken => 'print ++$y;', ); my $script = Script->new(\%snippets); $script->onInit(); $script->onAwaken();
which outputs
Global symbol "$y" requires explicit package name in onAwaken.

If so, use the following module:

use strict; use warnings; package Script; # Constants. my @events = qw( preRestore onRestore onAttach onInit onAwaken onChange ); # Ordered. my %events = map { $events[$_] => $_ } 0..$#events; sub new { my ($class, $snippets) = @_; my @event_line_nums; my $code = "sub {\n"; $code .= " my \$event_num = shift;\n"; $code .= " goto __$events[$_] if \$event_num == $_;\n" foreach 0 .. $#events; foreach my $event (@events) { push @event_line_nums, (() = $code =~ /\n/g) + 1; if (defined $snippets->{$event}) { $code .= "__$event: 1;\n$snippets->{$event}; return;\n"; } else { $code .= "__$event: return;\n"; } } $code .= "\n}\n"; my $sub = eval $code; if ($@) { my ($error_msg, $line_num) = $@ =~ /^(.*) at \(eval \d+\) line (\d+)/s; my $error_event; foreach my $event_num (0..$#events) { last if $line_num < $event_line_nums[$event_num]; $error_event = $event_num; } die("$error_msg in $events[$error_event].\n"); } return bless($sub, $class); } sub _dispatch { my $sub = shift; my $event_num = shift; $rv = eval { $sub->($event_num, @_) }; if ($@) { my ($error_msg) = $@ =~ /^(.*) at \(eval \d+\) line /s; die("$error_msg in $events[$event_num].\n"); } return $rv; } eval "sub $_ { shift->_dispatch($events{$_}, \@_); }" foreach @events; 1;

Update:


In reply to Re: Concatenating scripts intelligently by ikegami
in thread Concatenating scripts intelligently by sfink

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.