Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl dancer - how pass additional arguments to method hander subroutines?

Tags:

perl

dancer

Is there a way to pass additional variables to a method handler subroutine? I generally dislike using global variables outside the subroutine's scope. I have things like database connection and class instances which I would like the handlers to have access to, without using globals. Using debug to console, looks like @_ is empty for each handler call.

#!/usr/bin/perl

use strict;

use Dancer;
use Data::Dumper;

set('logger' => 'console');

my $somevar = SomeClass->new();

get('/' => sub{
  debug(Dumper(@_));
  debug($somevar);
  return('hello world');
});
like image 772
Douglas Mauch Avatar asked Oct 22 '22 12:10

Douglas Mauch


1 Answers

One way is to use the vars hash that Dancer provides. Here I use a before hook to set up a database handle:

use strict;
use warnings;
use Dancer;
use DBI;

hook 'before' => sub {
    var dbh => DBI->connect_cached(...);
};

get '/' => sub { 
    my $qry = vars->{dbh}->prepare("SQL");
    ...
    return "Something, something, query results";
};
like image 118
RickF Avatar answered Nov 15 '22 11:11

RickF