Search code examples
perlmojolicious

Why is this hash value undefined?


So i have the feeling that this is some stupid mistake on my part, but i can't figure out what is happening.

Some context first: I am playing around with webRTC, building a small videochat app with perl and js. I was afraid to get stuck on the webRTC part, but it turns out i'm stuck with perl.

At the top of my file i instantiate a hash like this

helper clients => sub { state $clients = {} } 

whenever a someone makes a get on / i check if i have an UID for the current client. if not i generate and store it. I then check if the client is already in the clients hash.

if (!$self->session('uid')) {
   $self->session('uid' => sha256_hex($self->tx . irand()));
} 
if (!exists $self->clients->{$self->session('uid')}) {
    $self->clients->{$self->session('uid')} = $self->tx;
}

the problem appears in my signaling server. when i use the value from the decoded json i get an undefined error. Do note that the loop is useless, i made it in order to debug.

here is the relevant code:

$self->on(
    message => sub {
        my ( $ws, $message ) = @_;

        my $json = decode_json($message);
        for (keys %{$self->clients}) {
            app->log->info('$_ is a => ' . $_);
            # $_  => 0d96bc9bb05feb9a7c2889209ee777affcaa11252be54ca7ddc349889978850f
            app->log->info('json uid => ' . $json->{'uid'}); 
            # json uid => 0d96bc9bb05feb9a7c2889209ee777affcaa11252be54ca7ddc349889978850f
            app->log->info('remote address with $_   => ' . $self->clients->{$_}->remote_address);
            # remote address with $_   => 127.0.0.1 
            app->log->info('remote address with string => ' . $self->clients->{'0d96bc9bb05feb9a7c2889209ee777affcaa11252be54ca7ddc349889978850f'}->remote_address);     
            # remote address with string => 127.0.0.1
            app->log->info('remote address with json_ => ' . $self->clients->{$json->{'uid'}}->remote_address);
            #  Can't call method "remote_address" on an undefined value at blabla   
        }
        ....
    }
);

The thing that i dont understand is that $_ and $json->{'uid'} hold identical values, so why is the first working and not the second ?


Solution

  • They obviously don't hold identical values. Trailing whitespace?

    use Data::Dumper qw( Dumper );
    
    {
        local $Data::Dumper::Useqq = 1;
        print(Dumper($json->{uid}));
    }
    

    Or in your case, app->log->info instead of print.