http://qs321.pair.com?node_id=382697

b888 has asked for the wisdom of the Perl Monks concerning the following question:

Greetings. I'm just starting with POE and found some problems writing code using it. I'm trying to write some kind of bot.
package Connector; use strict; use POE; use POE::Component::IRC; my $id = 0; sub new { my $class = shift; my %params = @_; my $self = bless {}, $class; $params{ALIAS} = sprintf("ib_%06d", ++$id); $params{IRC} = sprintf("i_%06d", $id); POE::Component::IRC::->new( $params{IRC} ); POE::Session->new( _start => \&_start, _connect => \&_connect, irc_001 => \&irc_001, [%params], ); return $self; } sub _start { my ($self, $heap, $kernel) = @_[OBJECT, HEAP, KERNEL]; my (%params) = @_[ARG0..$#_]; $heap = { PARAMS => { NICK => "", CONNECTED => 0, } }; $heap->{PARAMS}{NICK} = $params{Nick} if $params{Nick}; foreach my $key (keys %params){ ($key eq "ALIAS" || $key eq "IRC") ? $heap->{$key} = $params{$key} : $heap->{C_INFO}{$key} = $params{$key}; } $kernel->alias_set( $heap->{ALIAS} ); $kernel->post( $heap->{IRC}, "register", ("all") ); $kernel->yield( "_connect" ); } sub _connect { my ($kernel, $heap) = @_[KERNEL, HEAP]; $kernel->post($heap->{IRC}, "connect", { Nick => $heap->{C_INFO}{"Nick"}, Server => $heap->{C_INFO}{"Server"}, Port => $heap->{C_INFO}{"Port"}, Username => $heap->{C_INFO}{"Username"}, Ircname => $heap->{C_INFO}{"Ircname"} } ); } sub irc_001 { }
The problem is that $heap in &_connect is empty (in &_start all is ok). What is wrong?

Replies are listed 'Best First'.
Re: using POE::Component::IRC
by Mr_Person (Hermit) on Aug 13, 2004 at 21:10 UTC

    The problem is that you're assigning a new hash reference to $heap in _start. Let's see if I can explain this correctly...

    The _start sub gets called with a reference to the heap, stored internally by POE. You then store this reference in $heap and can then view or modify the real heap, but only through it's reference. In your code, you create an anonymous hash reference and assign it to $heap. This overwrites the reference that was in $heap pointing to the real "heap" location with a temporary one that goes out of scope when your sub exits. End result, it works fine within the _start sub, but after that all the changes mysteriously disappear.

    What you need to do is keep the reference in tact when you assign new values to it, with something like this:

    %$heap = ( PARAMS => { NICK => "", CONNECTED => 0, } );

    Hope that helps!

      That definitly helps. Thanks.