1POE::Session(3) User Contributed Perl Documentation POE::Session(3)
2
3
4
6 POE::Session - a generic event-driven task
7
9 use POE; # auto-includes POE::Kernel and POE::Session
10
11 POE::Session->create(
12 inline_states => {
13 _start => sub { $_[KERNEL]->yield("next") },
14 next => sub {
15 print "tick...\n";
16 $_[KERNEL]->delay(next => 1);
17 },
18 },
19 );
20
21 POE::Kernel->run();
22 exit;
23
24 POE::Session can also dispatch to object and class methods through
25 "object_states" and "package_states" callbacks.
26
28 POE::Session and its subclasses translate events from POE::Kernel's
29 generic dispatcher into the particular calling conventions suitable for
30 application code. In design pattern parlance, POE::Session classes are
31 adapters between POE::Kernel and application code.
32
33 The sessions that POE::Kernel manages are more like generic task
34 structures. Unfortunately these two disparate concepts have virtually
35 identical names.
36
37 A note on nomenclature
38 This documentation will refer to event handlers as "states" in certain
39 unavoidable situations. Sessions were originally meant to be event-
40 driven state machines, but their purposes evolved over time. Some of
41 the legacy vocabulary lives on in the API for backward compatibility,
42 however.
43
44 Confusingly, POE::NFA is a class for implementing actual event-driven
45 state machines. Its documentation uses "state" in the proper sense.
46
48 POE::Session has two main purposes. First, it maps event names to the
49 code that will handle them. Second, it maps a consistent event
50 dispatch interface to those handlers.
51
52 Consider the "SYNOPSIS" for example. A POE::Session instance is
53 created with two "inline_states", each mapping an event name ("_start"
54 and "next") to an inline subroutine. POE::Session ensures that
55 "$_[KERNEL]" and so on are meaningful within an event handler.
56
57 Event handlers may also be object or class methods, using
58 "object_states" and "package_states" respectively. The create() syntax
59 is different than for "inline_states", but the calling convention is
60 nearly identical.
61
62 Notice that the created POE::Session object has not been saved to a
63 variable. The new POE::Session object gives itself to POE::Kernel,
64 which then manages it and all the resources it uses.
65
66 It's possible to keep references to new POE::Session objects, but it's
67 not usually necessary. If an application is not careful about cleaning
68 up these references you will create circular references, which will
69 leak memory when POE::Kernel would normally destroy the POE::Session
70 object. It is recommended that you keep the session's ID instead.
71
72 POE::Session's Calling Convention
73 The biggest syntactical hurdle most people have with POE is
74 POE::Session's unconventional calling convention. For example:
75
76 sub handle_event {
77 my ($kernel, $heap, $parameter) = @_[KERNEL, HEAP, ARG0];
78 ...;
79 }
80
81 Or the use of $_[KERNEL], $_[HEAP] and $_[ARG0] inline, as is done in
82 most examples.
83
84 What's going on here is rather basic. Perl passes parameters into
85 subroutines or methods using the @_ array. "KERNEL", "HEAP", "ARG0"
86 and others are constants exported by POE::Session (which is included
87 for free when a program uses POE).
88
89 So $_[KERNEL] is an event handler's KERNELth parameter. @_[HEAP, ARG0]
90 is a slice of @_ containing the HEAPth and ARG0th parameters.
91
92 While this looks odd, it's perfectly plain and legal Perl syntax. POE
93 uses it for a few reasons:
94
95 1. In the common case, passing parameters in @_ is faster than passing
96 hash or array references and then dereferencing them in the
97 handler.
98
99 2. Typos in hash-based parameter lists are either subtle run-time
100 errors or requires constant run-time checking. Constants are
101 either known at compile time, or are clear compile-time errors.
102
103 3. Referencing @_ offsets by constants allows parameters to move in
104 the future without breaking application code.
105
106 4. Most event handlers don't need all of @_. Slices allow handlers to
107 use only the parameters they're interested in.
108
109 POE::Session Parameters
110 Event handlers receive most of their run-time context in up to nine
111 callback parameters. POE::Kernel provides many of them.
112
113 $_[OBJECT]
114
115 $_[OBJECT] is $self for event handlers that are an object method. It
116 is the class (package) name for class-based event handlers. It is
117 undef for plain coderef callbacks, which have no special $self-ish
118 value.
119
120 "OBJECT" is always zero, since $_[0] is always $self or $class in
121 object and class methods. Coderef handlers are called with an "undef"
122 placeholder in $_[0] so that the other offsets remain valid.
123
124 It's often useful for method-based event handlers to call other methods
125 in the same object. $_[OBJECT] helps this happen.
126
127 sub ui_update_everything {
128 my $self = $_[OBJECT];
129 $self->update_menu();
130 $self->update_main_window();
131 $self->update_status_line();
132 }
133
134 You may also use method inheritance. Here we invoke
135 $self->a_method(@_). Since Perl's "->" operator unshifts $self onto
136 the beginning of @_, we must first shift a copy off to maintain POE's
137 parameter offsets:
138
139 sub a_method {
140 my $self = shift;
141 $self->SUPER::a_method( @_ );
142 # ... more work ...
143 }
144
145 $_[SESSION]
146
147 $_[SESSION] is a reference to the current session object. This lets
148 event handlers access their session's methods. Programs may also
149 compare $_[SESSION] to $_[SENDER] to verify that intra-session events
150 did not come from other sessions.
151
152 $_[SESSION] may also be used as the destination for intra-session
153 post() and call(). yield() is marginally more convenient and efficient
154 than "post($_[SESSION], ...)" however.
155
156 It is bad form to access another session directly. The recommended
157 approach is to manipulate a session through an event handler.
158
159 sub enable_trace {
160 my $previous_trace = $_[SESSION]->option( trace => 1 );
161 my $id = $_[SESSION]->ID;
162 if ($previous_trace) {
163 print "Session $id: dispatch trace is still on.\n";
164 }
165 else {
166 print "Session $id: dispatch trace has been enabled.\n";
167 }
168 }
169
170 $_[KERNEL]
171
172 The KERNELth parameter is always a reference to the application's
173 singleton POE::Kernel instance. It is most often used to call
174 POE::Kernel methods from event handlers.
175
176 # Set a 10-second timer.
177 $_[KERNEL]->delay( time_is_up => 10 );
178
179 $_[HEAP]
180
181 Every POE::Session object contains its own variable namespace known as
182 the session's "HEAP". It is modeled and named after process memory
183 heaps (not priority heaps). Heaps are by default anonymous hash
184 references, but they may be initialized in create() to be almost
185 anything. POE::Session itself never uses $_[HEAP], although some POE
186 components do.
187
188 Heaps do not overlap between sessions, although create()'s "heap"
189 parameter can be used to make this happen.
190
191 These two handlers time the lifespan of a session:
192
193 sub _start_handler {
194 $_[HEAP]{ts_start} = time();
195 }
196
197 sub _stop_handler {
198 my $time_elapsed = time() - $_[HEAP]{ts_start};
199 print "Session ", $_[SESSION]->ID, " elapsed seconds: $elapsed\n";
200 }
201
202 $_[STATE]
203
204 The STATEth handler parameter contains the name of the event being
205 dispatched in the current callback. This can be important since the
206 event and handler names may significantly differ. Also, a single
207 handler may be assigned to more than one event.
208
209 POE::Session->create(
210 inline_states => {
211 one => \&some_handler,
212 two => \&some_handler,
213 six => \&some_handler,
214 ten => \&some_handler,
215 _start => sub {
216 $_[KERNEL]->yield($_) for qw(one two six ten);
217 }
218 }
219 );
220
221 sub some_handler {
222 print(
223 "Session ", $_[SESSION]->ID,
224 ": some_handler() handled event $_[STATE]\n"
225 );
226 }
227
228 It should be noted however that having event names and handlers names
229 match will make your code easier to navigate.
230
231 $_[SENDER]
232
233 Events must come from somewhere. $_[SENDER] contains the currently
234 dispatched event's source.
235
236 $_[SENDER] is commonly used as a return address for responses. It may
237 also be compared against $_[KERNEL] to verify that timers and other
238 POE::Kernel-generated events were not spoofed.
239
240 This "echo_handler()" responds to the sender with an "echo" event that
241 contains all the parameters it received. It avoids a feedback loop by
242 ensuring the sender session and event (STATE) are not identical to the
243 current ones.
244
245 sub echo_handler {
246 return if $_[SENDER] == $_[SESSION] and $_[STATE] eq "echo";
247 $_[KERNEL]->post( $_[SENDER], "echo", @_[ARG0..$#_] );
248 }
249
250 $_[CALLER_FILE], $_[CALLER_LINE] and $_[CALLER_STATE]
251
252 These parameters are a form of caller(), but they describe where the
253 currently dispatched event originated. CALLER_FILE and CALLER_LINE are
254 fairly plain. CALLER_STATE contains the name of the event that was
255 being handled when the event was created, or when the event watcher
256 that ultimately created the event was registered.
257
258 @_[ARG0..ARG9] or @_[ARG0..$#_]
259
260 Parameters $_[ARG0] through the end of @_ contain parameters provided
261 by application code, event watchers, or higher-level libraries. These
262 parameters are guaranteed to be at the end of @_ so that @_[ARG0..$#_]
263 will always catch them all.
264
265 $#_ is the index of the last value in @_. Blame Perl if it looks odd.
266 It's merely the $#array syntax where the array name is an underscore.
267
268 Consider
269
270 $_[KERNEL]->yield( ev_whatever => qw( zero one two three ) );
271
272 The handler for ev_whatever will be called with "zero" in $_[ARG0],
273 "one" in $_[ARG1], and so on. @_[ARG0..$#_] will contain all four
274 words.
275
276 sub ev_whatever {
277 $_[OBJECT]->whatever( @_[ARG0..$#_] );
278 }
279
280 Using POE::Session With Objects
281 One session may handle events across many objects. Or looking at it
282 the other way, multiple objects can be combined into one session. And
283 what the heck---go ahead and mix in some inline code as well.
284
285 POE::Session->create(
286 object_states => [
287 $object_1 => { event_1a => "method_1a" },
288 $object_2 => { event_2a => "method_2a" },
289 ],
290 inline_states => {
291 event_3 => \&piece_of_code,
292 },
293 );
294
295 However only one handler may be assigned to a given event name.
296 Duplicates will overwrite earlier ones.
297
298 event_1a is handled by calling "$object_1->method_1a(...)". $_[OBJECT]
299 is $object_1 in this case. $_[HEAP] belongs to the session, which
300 means anything stored there will be available to any other event
301 handler regardless of the object.
302
303 event_2a is handled by calling "$object_2->method_2a(...)". In this
304 case $_[OBJECT] is $object_2. $_[HEAP] is the same anonymous hashref
305 that was passed to the event_1a handler, though. The methods are
306 resolved when the event is handled (late-binding).
307
308 event_3 is handled by calling "piece_of_code(...)". $_[OBJECT] is
309 "undef" here because there's no object. And once again, $_[HEAP] is
310 the same shared hashref that the handlers for event_1a and event_2a
311 saw.
312
313 Interestingly, there's no technical reason that a single object can't
314 handle events from more than one session:
315
316 for (1..2) {
317 POE::Session->create(
318 object_states => [
319 $object_4 => { event_4 => "method_4" },
320 ]
321 );
322 }
323
324 Now "$object_4->method_4(...)" may be called to handle events from one
325 of two sessions. In both cases, $_[OBJECT] will be $object_4, but
326 $_[HEAP] will hold data for a particular session.
327
328 The same goes for inline states. One subroutine may handle events from
329 many sessions. $_[SESSION] and $_[HEAP] can be used within the handler
330 to easily access the context of the session in which the event is being
331 handled.
332
334 POE::Session has just a few public methods.
335
336 create LOTS_OF_STUFF
337 "create()" starts a new session running. It returns a new POE::Session
338 object upon success, but most applications won't need to save it.
339
340 "create()" invokes the newly started session's _start event handler
341 before returning.
342
343 "create()" also passes the new POE::Session object to POE::Kernel.
344 POE's kernel holds onto the object in order to dispatch events to it.
345 POE::Kernel will release the object when it detects the object has
346 become moribund. This should cause Perl to destroy the object if
347 application code has not saved a copy of it.
348
349 "create()" accepts several named parameters, most of which are
350 optional. Note however that the parameters are not part of a hashref.
351
352 args => ARRAYREF
353
354 The "args" parameter accepts a reference to a list of parameters that
355 will be passed to the session's _start event handler in @_ positions
356 "ARG0" through $#_ (the end of @_).
357
358 This example would print "arg0 arg1 etc.":
359
360 POE::Session->create(
361 inline_states => {
362 _start => sub {
363 print "Session started with arguments: @_[ARG0..$#_]\n";
364 },
365 },
366 args => [ 'arg0', 'arg1', 'etc.' ],
367 );
368
369 heap => ANYTHING
370
371 The "heap" parameter allows a session's heap to be initialized
372 differently at instantiation time. Heaps are usually anonymous
373 hashrefs, but "heap" may set them to be array references or even
374 objects.
375
376 This example prints "tree":
377
378 POE::Session->create(
379 inline_states => {
380 _start => sub {
381 print "Slot 0 = $_[HEAP][0]\n";
382 },
383 },
384 heap => [ 'tree', 'bear' ],
385 );
386
387 Be careful when initializing the heap to be something that doesn't
388 behave like a hashref. Some libraries assume hashref heap semantics,
389 and they will fail if the heap doesn't work that way.
390
391 inline_states => HASHREF
392
393 "inline_states" maps events names to the subroutines that will handle
394 them. Its value is a hashref that maps event names to the coderefs of
395 their corresponding handlers:
396
397 POE::Session->create(
398 inline_states => {
399 _start => sub {
400 print "arg0=$_[ARG0], arg1=$_[ARG1], etc.=$_[ARG2]\n";
401 },
402 _stop => \&stop_handler,
403 },
404 args => [qw( arg0 arg1 etc. )],
405 );
406
407 The term "inline" comes from the fact that coderefs can be inlined
408 anonymous subroutines.
409
410 Be very careful with closures, however. "Beware circular references".
411
412 object_states => ARRAYREF
413
414 "object_states" associates one or more objects to a session and maps
415 event names to the object methods that will handle them. It's value is
416 an "ARRAYREF"; "HASHREFs" would stringify the objects, ruining them for
417 method invocation.
418
419 Here _start is handled by "$object->_session_start()" and _stop
420 triggers "$object->_session_stop()":
421
422 POE::Session->create(
423 object_states => [
424 $object => {
425 _start => '_session_start',
426 _stop => '_session_stop',
427 }
428 ]
429 );
430
431 POE::Session also supports a short form where the event and method
432 names are identical. Here _start invokes $object->_start(), and _stop
433 triggers $object->_stop():
434
435 POE::Session->create(
436 object_states => [
437 $object => [ '_start', '_stop' ],
438 ]
439 );
440
441 Methods are verified when the session is created, but also resolved
442 when the handler is called (late binding). Most of the time, a method
443 won't change. But in some circumstance, such as dynamic inheritance, a
444 method could resolve to a different subroutine.
445
446 options => HASHREF
447
448 POE::Session sessions support a small number of options, which may be
449 initially set with the "option" constructor parameter and changed at
450 run time with the "option()|/option" method.
451
452 "option" takes a hashref with option => value pairs:
453
454 POE::Session->create(
455 ... set up handlers ...,
456 options => { trace => 1, debug => 1 },
457 );
458
459 This is equivalent to the previous example:
460
461 POE::Session->create(
462 ... set up handlers ...,
463 )->option( trace => 1, debug => 1 );
464
465 The supported options and values are documented with the
466 "option()|/option" method.
467
468 package_states => ARRAYREF
469
470 "package_states" associates one or more classes to a session and maps
471 event names to the class methods that will handle them. Its function
472 is analogous to "object_states", but package names are specified rather
473 than objects.
474
475 In fact, the following documentation is a copy of the "object_states"
476 description with some word substitutions.
477
478 The value for "package_states" is an ARRAYREF to be consistent with
479 "object_states", even though class names (also known as package names)
480 are already strings, so it's not necessary to avoid stringifying them.
481
482 Here _start is handled by "$class_name->_session_start()" and _stop
483 triggers "$class_name->_session_stop()":
484
485 POE::Session->create(
486 package_states => [
487 $class_name => {
488 _start => '_session_start',
489 _stop => '_session_stop',
490 }
491 ]
492 );
493
494 POE::Session also supports a short form where the event and method
495 names are identical. Here _start invokes "$class_name->_start()", and
496 _stop triggers "$class_name->_stop()":
497
498 POE::Session->create(
499 package_states => [
500 $class_name => [ '_start', '_stop' ],
501 ]
502 );
503
504 ID
505 "ID()" returns the session instance's unique identifier. This is an
506 integer that starts at 1 and counts up forever, or until the number
507 wraps around.
508
509 It's theoretically possible that a session ID will not be unique, but
510 this requires at least 4.29 billion sessions to be created within a
511 program's lifespan. POE guarantees that no two sessions will have the
512 same ID at the same time, however; your computer doesn't have enough
513 memory to store 4.29 billion session objects.
514
515 A session's ID is unique within a running process, but multiple
516 processes are likely to have the same session IDs. If a global ID is
517 required, it will need to include both "$_[KERNEL]->ID" and
518 "$_[SESSION]->ID".
519
520 option OPTION_NAME [, OPTION_VALUE [, OPTION_NAME, OPTION_VALUE]... ]
521 "option()" sets and/or retrieves the values of various session options.
522 The options in question are implemented by POE::Session and do not have
523 any special meaning anywhere else.
524
525 It may be called with a single OPTION_NAME to retrieve the value of
526 that option.
527
528 my $trace_value = $_[SESSION]->option('trace');
529
530 "option()" sets an option's value when called with a single
531 OPTION_NAME, OPTION_VALUE pair. In this case, "option()" returns the
532 option's previous value.
533
534 my $previous_trace = $_[SESSION]->option(trace => 1);
535
536 "option()" may also be used to set the values of multiple options at
537 once. In this case, "option()" returns all the specified options'
538 previous values in an anonymous hashref:
539
540 my $previous_values = $_[SESSION]->option(
541 trace => 1,
542 debug => 1,
543 );
544
545 print "Previous option values:\n";
546 while (my ($option, $old_value) = each %$previous_values) {
547 print " $option = $old_value\n";
548 }
549
550 POE::Session currently supports three options:
551
552 The "debug" option.
553
554 The "debug" option is intended to enable additional warnings when
555 strange things are afoot within POE::Session. At this time, there is
556 only one additional warning:
557
558 ยท Redefining an event handler does not usually cause a warning, but
559 it will when the "debug" option is set.
560
561 The "default" option.
562
563 Enabling the "default" option causes unknown events to become warnings,
564 if there is no _default handler to catch them.
565
566 The class-level "POE::Session::ASSERT_STATES" flag is implemented by
567 enabling the "default" option on all new sessions.
568
569 The "trace" option.
570
571 Turn on the "trace" option to dump a log of all the events dispatched
572 to a particular session. This is a session-specific trace option that
573 allows individual sessions to be debugged.
574
575 Session-level tracing also indicates when events are redirected to
576 _default. This can be used to discover event naming errors.
577
578 User-defined options.
579
580 "option()" does not verify whether OPTION_NAMEs are known, so
581 "option()" may be used to store and retrieve user-defined information.
582
583 Choose option names with caution. There is no established convention
584 to avoid namespace collisions between user-defined options and future
585 internal options.
586
587 postback EVENT_NAME, EVENT_PARAMETERS
588 "postback()" manufactures callbacks that post POE events. It returns
589 an anonymous code reference that will post EVENT_NAME to the target
590 session, with optional EVENT_PARAMETERS in an array reference in ARG0.
591 Parameters passed to the callback will be sent in an array reference in
592 ARG1.
593
594 In other words, ARG0 allows the postback's creator to pass context
595 through the postback. ARG1 allows the caller to return information.
596
597 This example creates a coderef that when called posts "ok_button" to
598 $some_session with ARG0 containing "[ 8, 6, 7 ]".
599
600 my $postback = $some_session->postback( "ok_button", 8, 6, 7 );
601
602 Here's an example event handler for "ok_button".
603
604 sub handle_ok_button {
605 my ($creation_args, $called_args) = @_[ARG0, ARG1];
606 print "Postback created with (@$creation_args).\n";
607 print "Postback called with (@$called_args).\n";
608 }
609
610 Calling $postback->(5, 3, 0, 9) would perform the equivalent of...
611
612 $poe_kernel->post(
613 $some_session, "ok_button",
614 [ 8, 6, 7 ],
615 [ 5, 3, 0, 9 ]
616 );
617
618 This would be displayed when "ok_button" was dispatched to
619 handle_ok_button():
620
621 Postback created with (8 6 7).
622 Postback called with (5 3 0 9).
623
624 Postbacks hold references to their target sessions. Therefore sessions
625 with outstanding postbacks will remain active. Under every event loop
626 except Tk, postbacks are blessed so that DESTROY may be called when
627 their users are done. This triggers a decrement on their reference
628 counts, allowing sessions to stop.
629
630 Postbacks have one method, weaken(), which may be used to reduce their
631 reference counts upon demand. weaken() returns the postback, so you
632 can do:
633
634 my $postback = $session->postback("foo")->weaken();
635
636 Postbacks were created as a thin adapter between callback libraries and
637 POE. The problem at hand was how to turn callbacks from the Tk
638 graphical toolkit's widgets into POE events without subclassing several
639 Tk classes. The solution was to provide Tk with plain old callbacks
640 that posted POE events.
641
642 Since "postback()" and "callback()" are Session methods, they may be
643 called on $_[SESSION] or $_[SENDER], depending on particular needs.
644 There are usually better ways to interact between sessions than abusing
645 postbacks, however.
646
647 Here's a brief example of attaching a Gtk2 button to a POE event
648 handler:
649
650 my $btn = Gtk2::Button->new("Clear");
651 $btn->signal_connect( "clicked", $_[SESSION]->postback("ev_clear") );
652
653 Points to remember: The session will remain alive as long as $btn
654 exists and holds a copy of $_[SESSION]'s postback. Any parameters
655 passed by the Gtk2 button will be in ARG1.
656
657 callback EVENT_NAME, EVENT_PARAMETERS
658 callback() manufactures callbacks that use "$poe_kernel->call()" to
659 deliver POE events rather than "$poe_kernel->post()". It is identical
660 to "postback()" in every other respect.
661
662 callback() was created to avoid race conditions that arise when
663 external libraries assume callbacks will execute synchronously.
664 File::Find is an obvious (but not necessarily appropriate) example. It
665 provides a lot of information in local variables that stop being valid
666 after the callback. The information would be unavailable by the time a
667 post()ed event was dispatched.
668
669 get_heap
670 "get_heap()" returns a reference to a session's heap. This is the same
671 value as $_[HEAP] for the target session. "get_heap()" is intended to
672 be used with $poe_kernel and POE::Kernel's "get_active_session()" so
673 that libraries do not need these three common values explicitly passed
674 to them.
675
676 That is, it prevents the need for:
677
678 sub some_helper_function {
679 my ($kernel, $session, $heap, @specific_parameters) = @_;
680 ...;
681 }
682
683 Rather, helper functions may use:
684
685 use POE::Kernel; # exports $poe_kernel
686 sub some_helper_function {
687 my (@specific_parameters) = @_;
688 my $session = $poe_kernel->get_active_session();
689 my $heap = $session->get_heap();
690 }
691
692 This isn't very convenient for people writing libraries, but it makes
693 the libraries much more convenient to use.
694
695 Using "get_heap()" to break another session's encapsulation is strongly
696 discouraged.
697
698 instantiate CREATE_PARAMETERS
699 "instantiate()" creates and returns an empty POE::Session object. It
700 is called with the CREATE_PARAMETERS in a hash reference just before
701 "create()" processes them. Modifications to the CREATE_PARAMETERS will
702 affect how "create()" initializes the new session.
703
704 Subclasses may override "instantiate()" to alter the underlying
705 session's structure. They may extend "instantiate()" to add new
706 parameters to "create()".
707
708 Any parameters not recognized by "create()" must be removed from the
709 CREATE_PARAMETERS before "instantiate()" returns. "create()" will
710 croak if it discovers unknown parameters.
711
712 Be sure to return $self from instantiate.
713
714 sub instantiate {
715 my ($class, $create_params) = @_;
716
717 # Have the base class instantiate the new session.
718 my $self = $class->SUPER::instantiate($create_parameters);
719
720 # Extend the parameters recognized by create().
721 my $new_option = delete $create_parameters->{new_option};
722 if (defined $new_option) {
723 # ... customize $self here ...
724 }
725
726 return $self;
727 }
728
729 try_alloc START_ARGS
730 "try_alloc()" calls POE::Kernel's "session_alloc()" to allocate a
731 session structure and begin managing the session within POE's kernel.
732 It is called at the end of POE::Session's "create()". It returns
733 $self.
734
735 It is a subclassing hook for late session customization prior to
736 "create()" returning. It may also affect the contents of @_[ARG0..$#_]
737 that are passed to the session's _start handler.
738
739 sub try_alloc {
740 my ($self, @start_args) = @_;
741
742 # Perform late initialization.
743 # ...
744
745 # Give $self to POE::Kernel.
746 return $self->SUPER::try_alloc(@args);
747 }
748
750 Please do not define new events that begin with a leading underscore.
751 POE claims /^_/ events as its own.
752
753 POE::Session only generates one event, _default. All other internal
754 POE events are generated by (and documented in) POE::Kernel.
755
756 _default
757 _default is the "AUTOLOAD" of event handlers. If POE::Session can't
758 find a handler at dispatch time, it attempts to redirect the event to
759 _default's handler instead.
760
761 If there's no _default handler, POE::Session will silently drop the
762 event unless the "default" option is set.
763
764 To preserve the original information, the original event is slightly
765 changed before being redirected to the _default handler: The original
766 event parameters are moved to an array reference in ARG1, and the
767 original event name is passed to _default in ARG0.
768
769 sub handle_default {
770 my ($event, $args) = @_[ARG0, ARG1];
771 print(
772 "Session ", $_[SESSION]->ID,
773 " caught unhandled event $event with (@$args).\n"
774 );
775 }
776
777 _default is quite flexible. It may be used for debugging, or to handle
778 dynamically generated event names without pre-defining their handlers.
779 In the latter sense, _default performs analogously to Perl's
780 "AUTOLOAD".
781
782 _default may also be used as the default or "otherwise" clause of a
783 switch statement. Consider an input handler that throws events based
784 on a command name:
785
786 sub parse_command {
787 my ($command, @parameters) = split /\s+/, $_[ARG0];
788 $_[KERNEL]->post( "cmd_$command", @parameters );
789 }
790
791 A _default handler may be used to emit errors for unknown commands:
792
793 sub handle_default {
794 my $event = $_[ARG0];
795 return unless $event =~ /^cmd_(\S+)/;
796 warn "Unknown command: $1\n";
797 }
798
799 The _default behavior is implemented in POE::Session, so it may be
800 different for other session types.
801
802 POE::Session's Debugging Features
803 POE::Session contains one debugging assertion, for now.
804
805 ASSERT_STATES
806
807 Setting ASSERT_STATES to true causes every Session to warn when they
808 are asked to handle unknown events. Session.pm implements the guts of
809 ASSERT_STATES by defaulting the "default" option to true instead of
810 false. See the option() method earlier in this document for details
811 about the "default" option.
812
814 POE::Kernel.
815
816 The SEE ALSO section in POE contains a table of contents covering the
817 entire POE distribution.
818
820 There is a chance that session IDs may collide after Perl's integer
821 value wraps. This can occur after as few as 4.29 billion sessions.
822
823 Beware circular references
824 As you're probably aware, a circular reference is when a variable is
825 part of a reference chain that eventually refers back to itself. Perl
826 will not reclaim the memory involved in such a reference chain until
827 the chain is manually broken.
828
829 Here a POE::Session is created that refers to itself via an external
830 scalar. The event handlers import $session via closures which are in
831 turn stored within $session. Even if this session stops, the circular
832 references will remain.
833
834 my $session;
835 $session = POE::Session->create(
836 inline_states => {
837 _start => sub {
838 $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
839 $_[KERNEL]->post( $session, 'next' );
840 },
841 next => sub {
842 my $next = shift @{ $_[HEAP]->{todo} };
843 return unless $next;
844 $_[KERNEL]->post( $session, $next );
845 }
846 # ....
847 }
848 );
849
850 Reduced to its essence:
851
852 my %event_handlers;
853 $event_handler{_start} = sub { \%event_handlers };
854
855 Note also that an anonymous sub creates a closure on all lexical
856 variables in the scope it was defined in, even if it doesn't reference
857 them. $session is still being held in a circular reference here:
858
859 my $self = $package->new;
860 my $session;
861 $session = POE::Session->create(
862 inline_state => {
863 _start => sub { $self->_start( @_[ARG0..$#_] ) }
864 }
865 );
866
867 To avoid this, a session may set an alias for itself. Other parts of
868 the program may then refer to it by alias. In this case, one needn't
869 keep track of the session themselves (POE::Kernel will do it anyway).
870
871 POE::Session->create(
872 inline_states => {
873 _start => sub {
874 $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
875 $_[KERNEL]->alias_set('step_doer');
876 $_[KERNEL]->post( 'step_doer', 'next' );
877 },
878 next => sub {
879 my $next = shift @{ $_[HEAP]->{todo} };
880 return unless $next;
881 $_[KERNEL]->post( 'step_doer', $next );
882 }
883 # ....
884 }
885 );
886
887 Aliases aren't even needed in the previous example because the session
888 refers to itself. One could instead use POE::Kernel's yield() method
889 to post the event back to the current session:
890
891 next => sub {
892 my $next = shift @{ $_[HEAP]->{todo} };
893 return unless $next;
894 $_[KERNEL]->yield( $next );
895 }
896
897 Or the "$_[SESSION]" parameter passed to every event handler, but
898 yield() is more efficient.
899
900 next => sub {
901 my $next = shift @{ $_[HEAP]->{todo} };
902 return unless $next;
903 $_[KERNEL]->post( $_[SESSION], $next );
904 }
905
906 Along the same lines as "$_[SESSION]", a session can respond back to
907 the sender of an event by posting to "$_[SENDER]". This is great for
908 responding to requests.
909
910 If a program must hold onto some kind of dynamic session reference,
911 it's recommended to use the session's numeric ID rather than the object
912 itself. A session ID may be converted back into its object, but post()
913 accepts session IDs as well as objects and aliases:
914
915 my $session_id;
916 $session_id = POE::Session->create(
917 inline_states => {
918 _start => sub {
919 $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
920 $_[KERNEL]->post( $session_id, 'next' );
921 },
922 # ....
923 }
924 )->ID;
925
927 Please see POE for more information about authors and contributors.
928
929
930
931perl v5.32.0 2020-07-28 POE::Session(3)