POE::Session(3pm)

๐ŸŒธ POE::Session(3pm) โ€” a generic event-driven task ๐ŸŒธ

bestie, welcome to POE::Session(3pm) from User Contributed Perl Documentation. This page is giving โœจevent-driven taskโœจ energy, and it's lowkey iconic.

๐Ÿ“› NAME ๐Ÿ“›

POE::Session โ€” a generic event-driven task. periodt.


โœจ SYNOPSIS โœจ

okay so here's the vibe:

use POE; # auto-includes POE::Kernel and POE::Session

POE::Session->create(
  inline_states => {
    _start => sub { $_[KERNEL]->yield("next") },
    next   => sub {
      print "tick...\n";
      $_[KERNEL]->delay(next => 1);
    },
  },
);

POE::Kernel->run();
exit;

POE::Session can also dispatch to object and class methods through object_states and package_states callbacks. slay.


๐Ÿ’– DESCRIPTION ๐Ÿ’–

POE::Session and its subclasses translate events from POE::Kernel's generic dispatcher into the particular calling conventions suitable for application code. In design pattern parlance, POE::Session classes are adapters between POE::Kernel and application code.

The sessions that POE::Kernel manages are more like generic task structures. Unfortunately these two disparate concepts have virtually identical names. not the name collision, bestie ๐Ÿ˜ญ

๐Ÿง  A note on nomenclature ๐Ÿง 

This documentation will refer to event handlers as "states" in certain unavoidable situations. Sessions were originally meant to be event-driven state machines, but their purposes evolved over time. Some of the legacy vocabulary lives on in the API for backward compatibility, however.

Confusingly, POE::NFA is a class for implementing actual event-driven state machines. Its documentation uses "state" in the proper sense. iykyk.

โœจ USING POE::Session โœจ

okay bestie, so POE::Session is out here doing two big jobs. Job one: it maps event names โ†’ the code that's gonna handle them. Job two: it maps a consistent event dispatch interface onto those handlers. two purposes, one icon. ๐Ÿ’…

look at the SYNOPSIS for a sec. A POE::Session instance gets created with two inline_states, and each one maps an event name (_start and next) to an inline subroutine. POE::Session is the one making sure $_[KERNEL] and friends are actually meaningful inside an event handler. it's giving glue holding the whole vibe together.

and your handlers don't have to be plain coderefs either โ€” they can be object methods or class methods, using object_states and package_states respectively. the create() syntax is different from inline_states, yeah, but the calling convention is nearly identical. same energy, different fit. ๐ŸŽ€

not me pointing out the most iconic part: the POE::Session object that just got created isn't saved to a variable. it doesn't need to be! the new POE::Session object hands itself over to POE::Kernel, and POE::Kernel manages it and all the resources it uses. self-sufficient queen. ๐Ÿ‘‘

you can keep references to new POE::Session objects, but it's usually not necessary. and if an application isn't careful about cleaning up those references, you'll create circular references, which will leak memory when POE::Kernel would normally destroy the POE::Session object. so don't do that. ๐Ÿ’€

the recommendation is: keep the session's ID instead. much cleaner, no leaks, we love that for you. ๐Ÿซถ

๐ŸŒธ POE::Session's Calling Convention ๐ŸŒธ

this right here is the biggest syntactical hurdle most people hit with POE โ€” the calling convention is just... unconventional, and it trips everyone up at first. for example:

sub handle_event {
  my ($kernel, $heap, $parameter) = @_[KERNEL, HEAP, ARG0];
  ...;
}

or the inline style, using $_[KERNEL], $_[HEAP] and $_[ARG0] right there in the handler, like most examples do.

and honestly? what's happening is rather basic. Perl passes parameters into subroutines or methods using the @_ array. KERNEL, HEAP, ARG0 and the rest are just constants exported by POE::Session (which you get for free when a program uses POE).

so $_[KERNEL] is literally an event handler's KERNELth parameter. and @_[HEAP, ARG0] is a slice of @_ containing the HEAPth and ARG0th parameters. that's it. that's the whole thing. ๐Ÿ˜ญ

it looks odd, but it's perfectly plain and legal Perl syntax. POE does it for a few reasons:

  1. In the common case, passing parameters in @_ is faster than passing hash or array references and then dereferencing them in the handler. โšก
  2. Typos in hash-based parameter lists are either subtle run-time errors or require constant run-time checking. Constants are either known at compile time, or are clear compile-time errors. โœจ
  3. Referencing @_ offsets by constants allows parameters to move in the future without breaking application code. ๐Ÿ”ฎ
  4. Most event handlers don't need all of @_. Slices allow handlers to use only the parameters they're interested in. ๐Ÿ’…

๐Ÿ’– POE::Session Parameters ๐Ÿ’–

event handlers receive most of their run-time context in up to nine callback parameters. POE::Kernel provides many of them. let's meet the whole squad, one by one.

$_[OBJECT]

$_[OBJECT] is $self for event handlers that are an object method. it's the class (package) name for class-based event handlers. and it's undef for plain coderef callbacks, which have no special $self-ish value at all. ๐Ÿ™ˆ

OBJECT is always zero, since $_[0] is always $self or $class in object and class methods. coderef handlers get called with an undef placeholder in $_[0] so that all the other offsets stay valid. it's a little seat-filler so the rest of the row doesn't shift. ๐ŸŽŸ๏ธ

it's often super useful for method-based event handlers to call other methods in the same object, and $_[OBJECT] is how that happens:

sub ui_update_everything {
  my $self = $_[OBJECT];
  $self->update_menu();
  $self->update_main_window();
  $self->update_status_line();
}

you can also use method inheritance! here we invoke $self->a_method(@_). and since Perl's -> operator unshifts $self onto the beginning of @_, we have to first shift a copy off to maintain POE's parameter offsets:

sub a_method {
  my $self = shift;
  $self->SUPER::a_method( @_ );
  # ... more work ...
}

$_[SESSION]

$_[SESSION] is a reference to the current session object. this lets event handlers access their session's methods. programs may also compare $_[SESSION] to $_[SENDER] to verify that intra-session events did not come from other sessions. ๐Ÿ‘€

$_[SESSION] may also be used as the destination for intra-session post() and call(). that said, yield() is marginally more convenient and efficient than post($_[SESSION], ...). lowkey just use yield(). โœจ

it's bad form to access another session directly, bestie. the recommended approach is to manipulate a session through an event handler:

sub enable_trace {
  my $previous_trace = $_[SESSION]->option( trace => 1 );
  my $id = $_[SESSION]->ID;
  if ($previous_trace) {
    print "Session $id: dispatch trace is still on.\n";
  }
  else {
    print "Session $id: dispatch trace has been enabled.\n";
  }
}

$_[KERNEL]

the KERNELth parameter is always a reference to the application's singleton POE::Kernel instance. it's most often used to call POE::Kernel methods from event handlers:

# Set a 10-second timer.
$_[KERNEL]->delay( time_is_up => 10 );

$_[HEAP]

every POE::Session object contains its own variable namespace, known as the session's HEAP. it's modeled and named after process memory heaps โ€” not priority heaps, bestie, don't get it twisted. ๐Ÿ˜Œ heaps are by default anonymous hash references, but they may be initialized in create() to be almost anything. POE::Session itself never uses $_[HEAP], although some POE components do.

heaps do not overlap between sessions, although create()'s heap parameter can be used to make this happen. (yes, on purpose. icon behavior.)

these two handlers time the lifespan of a session:

sub _start_handler {
  $_[HEAP]{ts_start} = time();
}

sub _stop_handler {
  my $time_elapsed = time() - $_[HEAP]{ts_start};
  print "Session ", $_[SESSION]->ID, " elapsed seconds: $elapsed\n";
}

$_[STATE]

the STATEth handler parameter contains the name of the event being dispatched in the current callback. this can matter a lot, since event and handler names may significantly differ. also, a single handler may be assigned to more than one event. multitasking king. ๐Ÿ‘‘

POE::Session->create(
  inline_states => {
    one => \&some_handler,
    two => \&some_handler,
    six => \&some_handler,
    ten => \&some_handler,
    _start => sub {
      $_[KERNEL]->yield($_) for qw(one two six ten);
    }
  }
);

sub some_handler {
  print(
    "Session ", $_[SESSION]->ID,
    ": some_handler() handled event $_[STATE]\n"
  );
}

that said, it should be noted: having event names and handler names match will make your code way easier to navigate. do future-you a solid. ๐Ÿซถ

$_[SENDER]

events gotta come from somewhere. $_[SENDER] contains the currently dispatched event's source. ๐Ÿ“ฌ

$_[SENDER] is commonly used as a return address for responses. it may also be compared against $_[KERNEL] to verify that timers and other POE::Kernel-generated events were not spoofed. stay safe out there. ๐Ÿ›ก๏ธ

this echo_handler() responds to the sender with an echo event containing all the parameters it received. it avoids a feedback loop by making sure the sender session and event (STATE) aren't identical to the current ones:

sub echo_handler {
  return if $_[SENDER] == $_[SESSION] and $_[STATE] eq "echo";
  $_[KERNEL]->post( $_[SENDER], "echo", @_[ARG0..$#_] );
}

$_[CALLER_FILE], $_[CALLER_LINE] and $_[CALLER_STATE]

these parameters are a form of caller(), but they describe where the currently dispatched event originated. CALLER_FILE and CALLER_LINE are fairly plain. CALLER_STATE contains the name of the event that was being handled when the event was created, or when the event watcher that ultimately created the event was registered. it's giving detective work. ๐Ÿ”

@_[ARG0..ARG9] or @_[ARG0..$#_]

parameters $_[ARG0] through the end of @_ contain parameters provided by application code, event watchers, or higher-level libraries. these parameters are guaranteed to be at the end of @_, so that @_[ARG0..$#_] will always catch them all. no stragglers. ๐Ÿงš

$#_ is the index of the last value in @_. blame Perl if it looks odd โ€” it's merely the $#array syntax where the array name is an underscore. it's fine. it's legal. breathe. ๐Ÿ˜ฎโ€๐Ÿ’จ

consider:

$_[KERNEL]->yield( ev_whatever => qw( zero one two three ) );

the handler for ev_whatever will be called with zero in $_[ARG0], one in $_[ARG1], and so on. @_[ARG0..$#_] will contain all four words:

sub ev_whatever {
  $_[OBJECT]->whatever( @_[ARG0..$#_] );
}

๐Ÿฆ‹ Using POE::Session With Objects ๐Ÿฆ‹

one session may handle events across many objects. or, flipping it around, multiple objects can be combined into one session. and honestly? go ahead and mix in some inline code too, what the heck. chaos is a lifestyle. ๐Ÿ’…

POE::Session->create(
  object_states => [
    $object_1 => { event_1a => "method_1a" },
    $object_2 => { event_2a => "method_2a" },
  ],
  inline_states => {
    event_3 => \&piece_of_code,
  },
);

however, only one handler may be assigned to a given event name. duplicates will overwrite earlier ones. no sharing, no teamwork, one winner. ๐Ÿ’€

  • event_1a is handled by calling $object_1->method_1a(...). $_[OBJECT] is $object_1 in this case. $_[HEAP] belongs to the session, which means anything stored there will be available to any other event handler regardless of the object. ๐ŸŽ€
  • event_2a is handled by calling $object_2->method_2a(...). in this case $_[OBJECT] is $object_2. $_[HEAP] is the same anonymous hashref that was passed to the event_1a handler though. the methods are resolved when the event is handled (late-binding). โœจ
  • event_3 is handled by calling piece_of_code(...). $_[OBJECT] is undef here because there's no object. and once again, $_[HEAP] is the same shared hashref that the handlers for event_1a and event_2a saw.

and here's the wild part: there's no technical reason a single object can't handle events from more than one session:

for (1..2) {
  POE::Session->create(
    object_states => [
      $object_4 => { event_4 => "method_4" },
    ]
  );
}

now $object_4->method_4(...) may be called to handle events from one of two sessions. in both cases, $_[OBJECT] will be $object_4, but $_[HEAP] will hold data for a particular session. same queen, different rooms. ๐Ÿ‘‘

the same goes for inline states โ€” one subroutine may handle events from many sessions. $_[SESSION] and $_[HEAP] can be used within the handler to easily access the context of the session in which the event is being handled. context is everything, bestie. ๐ŸŒˆ


๐Ÿ‘‘ PUBLIC METHODS ๐Ÿ‘‘

POE::Session has just a few public methods. short and sweet, we stan a minimal API.

create LOTS_OF_STUFF

create() starts a new session running. it returns a new POE::Session object upon success, but most applications won't need to save it. (see above re: circular references โ€” you already know. ๐Ÿ’…)

create() invokes the newly started session's _start event handler before returning. so by the time you get control back, _start has already run. no cap. โœจ

create() also hands the brand-new POE::Session object over to POE::Kernel. The kernel literally holds onto it so it can dispatch events to it. When the kernel notices the object has gone moribund, it lets go โ€” which should make Perl destroy the object, unless your app code saved its own copy somewhere. ๐Ÿ’€

create() takes a bunch of named parameters, and most of them are optional. But heads up bestie: these params are not wrapped in a hashref. They're justโ€ฆ passed. That's the vibe. ๐ŸŽ€


args => ARRAYREF ๐ŸŒธ

The args parameter takes a reference to a list of parameters that get passed to the session's _start event handler, sitting in @_ at positions ARG0 through $#_ (aka the end of @_).

This example would print arg0 arg1 etc.:

POE::Session->create(
  inline_states => {
    _start => sub {
      print "Session started with arguments: @_[ARG0..$#_]\n";
    },
  },
  args => [ 'arg0', 'arg1', 'etc.' ],
);

heap => ANYTHING ๐Ÿฆ‹

The heap parameter lets a session's heap get initialized differently right at instantiation time. Heaps are usually anonymous hashrefs, but heap can set them to be array references or even objects. It's giving flexible. โœจ

This example prints tree:

POE::Session->create(
  inline_states => {
    _start => sub {
      print "Slot 0 = $_[HEAP][0]\n";
    },
  },
  heap => [ 'tree', 'bear' ],
);
โš ๏ธ Be careful when initializing the heap to something that doesn't behave like a hashref. Some libraries assume hashref heap semantics, and they will fail if the heap doesn't work that way. no cap.

inline_states => HASHREF ๐Ÿ’…

inline_states maps event names to the subroutines that handle them. Its value is a hashref mapping event names to the coderefs of their corresponding handlers:

POE::Session->create(
  inline_states => {
    _start => sub {
      print "arg0=$_[ARG0], arg1=$_[ARG1], etc.=$_[ARG2]\n";
    },
    _stop  => \&stop_handler,
  },
  args => [qw( arg0 arg1 etc. )],
);

The term "inline" comes from the fact that coderefs can be inlined anonymous subroutines. iconic behavior honestly.

๐Ÿšจ Be very careful with closures, though. โ†’ "Beware circular references". That's a whole thing, iykyk.

object_states => ARRAYREF ๐Ÿ‘‘

object_states associates one or more objects to a session and maps event names to the object methods that handle them. Its value is an ARRAYREF โ€” and yes it must be an ARRAYREF, because HASHREFs would stringify the objects, ruining them for method invocation. ๐Ÿ’€

Here _start is handled by $object->_session_start() and _stop triggers $object->_session_stop():

POE::Session->create(
  object_states => [
    $object => {
      _start => '_session_start',
      _stop  => '_session_stop',
    }
  ]
);

POE::Session also supports a short form where the event and method names are identical. Here _start invokes $object->_start(), and _stop triggers $object->_stop():

POE::Session->create(
  object_states => [
    $object => [ '_start', '_stop' ],
  ]
);

Methods are verified when the session is created, but they're also resolved when the handler is called (late binding, slay). Most of the time, a method won't change. But in some circumstances โ€” like dynamic inheritance โ€” a method could resolve to a different subroutine. ๐Ÿงš


options => HASHREF โญ

POE::Session sessions support a small number of options, which may be initially set with the option constructor parameter and changed at run time with the option() method.

option takes a hashref with option => value pairs:

POE::Session->create(
  ... set up handlers ...,
  options => { trace => 1, debug => 1 },
);

This is equivalent to the previous example:

POE::Session->create(
  ... set up handlers ...,
)->option( trace => 1, debug => 1 );

The supported options and values are documented with the option() method. ๐Ÿ‘€ (keep scrolling bestie)


package_states => ARRAYREF ๐ŸŒˆ

package_states associates one or more classes to a session and maps event names to the class methods that handle them. Its function is analogous to object_states, but package names are specified rather than objects.

In fact, the following documentation is a copy of the object_states description with some word substitutions. (the manpage said it, not me ๐Ÿ’…)

The value for package_states is an ARRAYREF to be consistent with object_states, even though class names (also known as package names) are already strings, so it's not necessary to avoid stringifying them.

Here _start is handled by $class_name->_session_start() and _stop triggers $class_name->_session_stop():

POE::Session->create(
  package_states => [
    $class_name => {
      _start => '_session_start',
      _stop  => '_session_stop',
    }
  ]
);

POE::Session also supports a short form where the event and method names are identical. Here _start invokes $class_name->_start(), and _stop triggers $class_name->_stop():

POE::Session->create(
  package_states => [
    $class_name => [ '_start', '_stop' ],
  ]
);

๐Ÿ’– ID ๐Ÿ’–

ID() returns the session instance's unique identifier. It's an integer that starts at 1 and counts up forever โ€” or until the number wraps around. ๐ŸŒ€

It's theoretically possible that a session ID will not be unique, but that requires at least 4.29 billion sessions to be created within a program's lifespan. POE guarantees that no two sessions will have the same ID at the same time, however; your computer doesn't have enough memory to store 4.29 billion session objects. (not even close bestie ๐Ÿ˜ญ)

A session's ID is unique within a running process, but multiple processes are likely to have the same session IDs. If a global ID is required, it will need to include both $_[KERNEL]->ID and $_[SESSION]->ID.


โœจ option OPTION_NAME [, OPTION_VALUE [, OPTION_NAME, OPTION_VALUE]... ] โœจ

option() sets and/or retrieves the values of various session options. The options in question are implemented by POE::Session and don't have any special meaning anywhere else. ๐Ÿ’…

It may be called with a single OPTION_NAME to retrieve the value of that option.

my $trace_value = $_[SESSION]->option('trace');

option() sets an option's value when called with a single OPTION_NAME, OPTION_VALUE pair. In this case, option() returns the option's previous value.

my $previous_trace = $_[SESSION]->option(trace => 1);

option() may also be used to set the values of multiple options at once. In this case, option() returns all the specified options' previous values in an anonymous hashref:

my $previous_values = $_[SESSION]->option(
  trace => 1,
  debug => 1,
);

print "Previous option values:\n";
while (my ($option, $old_value) = each %$previous_values) {
  print "  $option = $old_value\n";
}

POE::Session currently supports three options:


The debug option ๐ŸŽ€

The debug option is intended to enable additional warnings when strange things are afoot within POE::Session. At this time, there is only one additional warning:

  • Redefining an event handler does not usually cause a warning, but it will when the debug option is set.

The default option ๐Ÿฆ‹

Enabling the default option causes unknown events to become warnings, if there is no _default handler to catch them.

The class-level POE::Session::ASSERT_STATES flag is implemented by enabling the default option on all new sessions. periodt.


The trace option ๐Ÿ”ฅ

Turn on the trace option to dump a log of all the events dispatched to a particular session. This is a session-specific trace option that allows individual sessions to be debugged. ๐Ÿ•ต๏ธโ€โ™€๏ธ

Session-level tracing also indicates when events are redirected to _default. This can be used to discover event naming errors. lowkey a lifesaver.


User-defined options ๐Ÿ’œ

option() does not verify whether OPTION_NAMEs are known, so option() may be used to store and retrieve user-defined information.

Choose option names with caution. There is no established convention to avoid namespace collisions between user-defined options and future internal options. ๐Ÿ™ˆ

๐ŸŒธ postback EVENT_NAME, EVENT_PARAMETERS ๐ŸŒธ

postback() manufactures callbacks that post POE events. It returns an anonymous code reference that will post EVENT_NAME to the target session, with optional EVENT_PARAMETERS in an array reference in ARG0. Parameters passed to the callback will be sent in an array reference in ARG1.

In other words, ARG0 allows the postback's creator to pass context through the postback. ARG1 allows the caller to return information. it's giving bidirectional communication. โœจ

This example creates a coderef that when called posts ok_button to $some_session with ARG0 containing [ 8, 6, 7 ].

my $postback = $some_session->postback( "ok_button", 8, 6, 7 );

Here's an example event handler for ok_button.

sub handle_ok_button {
  my ($creation_args, $called_args) = @_[ARG0, ARG1];
  print "Postback created with (@$creation_args).\n";
  print "Postback called with (@$called_args).\n";
}

Calling $postback->(5, 3, 0, 9) would perform the equivalent ofโ€ฆ

$poe_kernel->post(
  $some_session, "ok_button",
  [ 8, 6, 7 ],
  [ 5, 3, 0, 9 ]
);

This would be displayed when ok_button was dispatched to handle_ok_button():

Postback created with (8 6 7).
Postback called with (5 3 0 9).

Postbacks hold references to their target sessions. Therefore sessions with outstanding postbacks will remain active. Under every event loop except Tk, postbacks are blessed so that DESTROY may be called when their users are done. This triggers a decrement on their reference counts, allowing sessions to stop. ๐Ÿ‘‘

Postbacks have one method, weaken(), which may be used to reduce their reference counts upon demand. weaken() returns the postback, so you can do:

my $postback = $session->postback("foo")->weaken();

Postbacks were created as a thin adapter between callback libraries and POE. The problem at hand was how to turn callbacks from the Tk graphical toolkit's widgets into POE events without subclassing several Tk classes. The solution was to provide Tk with plain old callbacks that posted POE events. โœจ history, bestie.

Since postback() and callback() are Session methods, they may be called on $_[SESSION] or $_[SENDER], depending on particular needs. There are usually better ways to interact between sessions than abusing postbacks, however. ๐Ÿ‘€

Here's a brief example of attaching a Gtk2 button to a POE event handler:

my $btn = Gtk2::Button->new("Clear");
$btn->signal_connect( "clicked", $_[SESSION]->postback("ev_clear") );

Points to remember: the session stays alive as long as $btn exists and is holding a copy of $_[SESSION]'s postback. And every parameter that the Gtk2 button hands over lands in ARG1. ๐Ÿ’…


callback EVENT_NAME, EVENT_PARAMETERS

callback() makes you callbacks that deliver POE events using $poe_kernel->call() instead of $poe_kernel->post(). Literally identical to postback() in every other way. no cap. โœจ

Why does callback() exist? Because external libraries be out here assuming callbacks run synchronously, and that causes race conditions ๐Ÿ˜ญ. File::Find is the obvious example (tho likeโ€ฆ not necessarily the appropriate one, bestie). It stashes a whole bunch of info in local variables that go stale the second the callback returns โ€” so by the time a post()ed event actually gets dispatched, that info is justโ€ฆ gone. poof ๐Ÿฆ‹


get_heap

get_heap() hands you a reference to a session's heap. Same value as $_[HEAP] for the session you're targeting. The whole point is to use it alongside $poe_kernel and POE::Kernel's get_active_session(), so libraries don't have to have those three common values explicitly passed in. ๐ŸŽ€

Basically, it saves you from having to do this:

sub some_helper_function {
  my ($kernel, $session, $heap, @specific_parameters) = @_;
  ...;
}

Instead, helper functions can do this:

use POE::Kernel; # exports $poe_kernel
sub some_helper_function {
  my (@specific_parameters) = @_;
  my $session = $poe_kernel->get_active_session();
  my $heap = $session->get_heap();
}

Honestly? Not super convenient for the people writing libraries, but it makes those libraries wayyy more convenient to use. and that's the tradeoff. ๐Ÿซถ

Using get_heap() to break another session's encapsulation is strongly discouraged. don't do it bestie. it's giving red flags ๐Ÿšฉ

instantiate CREATE_PARAMETERS

instantiate() creates and returns an empty POE::Session object. It gets called with the CREATE_PARAMETERS in a hash reference right before create() processes them. Any modifications you make to CREATE_PARAMETERS will affect how create() initializes the new session. ๐Ÿ‘‘

Subclasses can override instantiate() to change up the underlying session's structure. They can also extend instantiate() to add brand new parameters to create().

Any parameters that create() doesn't recognize must be removed from CREATE_PARAMETERS before instantiate() returns. create() will croak if it finds unknown parameters. ๐Ÿ˜ญ

And be sure to return $self from instantiate. fr fr.

sub instantiate {
  my ($class, $create_params) = @_;

  # Have the base class instantiate the new session.
  my $self = $class->SUPER::instantiate($create_parameters);

  # Extend the parameters recognized by create().
  my $new_option = delete $create_parameters->{new_option};
  if (defined $new_option) {
    # ... customize $self here ...
  }

  return $self;
}

try_alloc START_ARGS

try_alloc() calls POE::Kernel's session_alloc() to allocate a session structure and start managing the session inside POE's kernel. It gets called at the very end of POE::Session's create(), and it returns $self. โœจ

It's a subclassing hook for late session customization, right before create() returns. It can also mess with the contents of @_[ARG0..$#_] that get passed to the session's _start handler. ๐Ÿ‘€

sub try_alloc {
  my ($self, @start_args) = @_;

  # Perform late initialization.
  # ...

  # Give $self to POE::Kernel.
  return $self->SUPER::try_alloc(@args);
}

๐ŸŒธ POE::Session's EVENTS ๐ŸŒธ

okay important: please don't define new events that start with a leading underscore. POE claims /^_/ events as its own. that's the house's turf. ๐Ÿ’…

POE::Session only generates one event, _default. Every other internal POE event is generated by (and documented in) POE::Kernel. periodt.

_default

_default is basically the AUTOLOAD of event handlers. If POE::Session can't find a handler at dispatch time, it tries to redirect the event over to _default's handler instead. ๐Ÿฆ‹

If there's no _default handler, POE::Session will silently drop the event โ€” unless the default option is set.

To keep the original info intact, the original event gets tweaked slightly before it's redirected to the _default handler: the original event parameters get moved into an array reference in ARG1, and the original event name is passed to _default in ARG0.

sub handle_default {
  my ($event, $args) = @_[ARG0, ARG1];
  print(
    "Session ", $_[SESSION]->ID,
    " caught unhandled event $event with (@$args).\n"
  );
}

_default is lowkey so flexible. Use it for debugging, or to handle dynamically generated event names without having to pre-define their handlers. In that second sense, _default works analogously to Perl's AUTOLOAD. iconic. ๐ŸŒˆ

You can also use _default as the default / "otherwise" clause of a switch statement. Picture an input handler that throws events based on a command name:

sub parse_command {
  my ($command, @parameters) = split /\s+/, $_[ARG0];
  $_[KERNEL]->post( "cmd_$command", @parameters );
}

Then a _default handler can be used to spit out errors for unknown commands:

sub handle_default {
  my $event = $_[ARG0];
  return unless $event =~ /^cmd_(\S+)/;
  warn "Unknown command: $1\n";
}

The _default behavior is implemented in POE::Session, so heads up โ€” it may be different for other session types. ๐Ÿ‘‘

POE::Session's Debugging Features

POE::Session contains one debugging assertion, for now. just the one, we're keeping it cozy ๐ŸŽ€

ASSERT_STATES

Setting ASSERT_STATES to true makes every Session warn when they're asked to handle unknown events. Session.pm implements the guts of ASSERT_STATES by defaulting the default option to true instead of false. See the option() method earlier in this document for the deets on the default option. ๐Ÿ’œ


โญ SEE ALSO โญ

POE::Kernel.

The SEE ALSO section in POE contains a table of contents covering the entire POE distribution. iykyk.


๐Ÿ’€ BUGS ๐Ÿ’€

There is a chance that session IDs may collide after Perl's integer value wraps. This can occur after as few as 4.29 billion sessions. yeah. 4.29 billion. just letting you know ๐Ÿ™ˆ

Beware circular references

So as you're probably aware, a circular reference is when a variable is part of a reference chain that eventually refers back to itself. Perl will not reclaim the memory involved in that reference chain until the chain is manually broken. it just sits there. holding on. ๐Ÿ˜ญ

Here's a POE::Session that's created referring to itself via an external scalar. The event handlers import $session through closures, and those closures are in turn stored inside $session. Even if this session stops, the circular references will remain. they do not go away.

my $session;
$session = POE::Session->create(
  inline_states => {
    _start => sub {
      $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
      $_[KERNEL]->post( $session, 'next' );
    },
    next => sub {
      my $next = shift @{ $_[HEAP]->{todo} };
      return unless $next;
      $_[KERNEL]->post( $session, $next );
    }
    # ....
  }
);

Reduced to its essence:

my %event_handlers;
$event_handler{_start} = sub { \%event_handlers };

Also note: an anonymous sub creates a closure on all lexical variables in the scope it was defined in โ€” even if it doesn't reference them. So $session is still being held in a circular reference here:

my $self = $package->new;
my $session;
$session = POE::Session->create(
  inline_state => {
    _start => sub { $self->_start( @_[ARG0..$#_] ) }
  }
);

To dodge this, a session can set an alias for itself. Then other parts of the program can refer to it by alias. In this case you don't even need to keep track of the session yourself โ€” POE::Kernel will do it anyway. ๐Ÿ’…

POE::Session->create(
  inline_states => {
    _start => sub {
      $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
      $_[KERNEL]->alias_set('step_doer');
      $_[KERNEL]->post( 'step_doer', 'next' );
    },
    next => sub {
      my $next = shift @{ $_[HEAP]->{todo} };
      return unless $next;
      $_[KERNEL]->post( 'step_doer', $next );
    }
    # ....
  }
);

Aliases aren't even needed in the previous example, because the session refers to itself. You could instead use POE::Kernel's yield() method to post the event back to the current session:

next => sub {
  my $next = shift @{ $_[HEAP]->{todo} };
  return unless $next;
  $_[KERNEL]->yield( $next );
}

Or you could use the $_[SESSION] parameter that gets passed to every event handler โ€” but yield() is more efficient. โšก

next => sub {
  my $next = shift @{ $_[HEAP]->{todo} };
  return unless $next;
  $_[KERNEL]->post( $_[SESSION], $next );
}

Along the same lines as $_[SESSION], a session can respond back to the sender of an event by posting to $_[SENDER]. This is great for responding to requests. ๐Ÿซถ

If a program absolutely must hold onto some kind of dynamic session reference, it's recommended to use the session's numeric ID rather than the object itself. A session ID can be converted back into its object โ€” but plot twist, post() accepts session IDs as well as objects and aliases, so you might not even need to. ๐ŸŒŸ

my $session_id;
$session_id = POE::Session->create(
  inline_states => {
    _start => sub {
      $_[HEAP]->{todo} = [ qw( step1 step2 step2a ) ],
      $_[KERNEL]->post( $session_id, 'next' );
    },
    # ....
  }
)->ID;

๐Ÿ‘‘ AUTHORS & COPYRIGHTS ๐Ÿ‘‘

Please see POE for more information about authors and contributors. ๐Ÿ’–


and that's the whole page bestie, we ate and left no crumbs ๐Ÿ“โœจ this was perl v5.34.0, dated 2022-03-25, and it's POE::Session(3pm) โ€” go forth and slay your event loops ๐Ÿ’…๐ŸŽ€๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from