Chüngel Chüngel - 2 years ago 175
Perl Question

Perl Dancer: Getting data from forms

I'm a Perl newbie and would like to know:

  • How can I use data from html forms with Perl dancer?

I'm struggling with the following example. I have a form on my
file like this:

<form action="/hello/:username" method="get" name="">
<h3>Please log in </h3>
<input type="text" name="username" required=""/>
<input type="password" name="senha" required=""/>
<button name="Submit" value="Login" type="Submit">Login</button>

I would like to use the username from the form and build a page which returns the typed information. So I've checked this tutorial and I've done the following in my

package Proyecto;
use Dancer ':syntax';
our $VERSION = '0.1';

get '/' => sub {
template 'index';

get '/hello/:username' => sub {
my $username= params('username');
return "Hola $username";

But it doesn't work. Do you guys know what it's missing here? Thanks!

Answer Source
<form action="/hello/:username" method="get" name="">

will call exactly /hello/:username without and replacement. HTML is unable to magically replace parts of the sourcecode - no matter if the backend is using Dancer or anything else. (JavaScript could do that.)

get '/hello/:username' => sub {

matches all calls to /hello/ followed by any string, like /hello/chungel, /hello/Larry or /hello/:username. the last one would set the value username into param('username').

You also added a form field with name="username" which ends up in two values for one key (one from the URL, one from the form).

Finally: Use a fixed URL as form action:

<form action="/hello" method="get" name="">


get '/hello' => sub {

Passing the username as HTML form value (and HTTP argument) doesn't get any advantage here.

If you really want to have the username within the URL, first use a different name in the route definition:

get '/hello/:url_username' => sub {
    return param('url_username');

Next you need to either rewrite the form action using JavaScript or rewrite the target URL using a Dancer before hook.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download