Perl Dancer route patterns

In this tutorial, we will learn about the route patterns or look deeper into routing with Perl Dancer and how we can get more of it?
Submitted by Godwill Tetah, on December 03, 2020

Perl Dancer offers a simple way of creating and manipulating routes just like other web frameworks and languages. In this tutorial, we will be using the get method to work with our routes.

In Perl dancer, a route may just be a simple slash / which signifies the default route or it can be a word (token) of your choice or which describes the information available on that route. For example, I might create a route like /about which simply displays information about me when accessed.

A route may contain more than one token or another route. For example, /members/Carine where Carine is the name of a member.

A route can be set up to collect any name after the member's main route for example and display it to welcome that member. This can be done using the param() method.

Take a look at the code below,

index.pl

use Dancer;

get '/members/:firstname' => sub {
    "Welcome Here " . param('firstname');
};

dance;

Output:

Perl Dancer route patterns (1)
  • You can see the way my input after /members in the URL path was gotten and used the welcome the member.
  • Also, notice the concatenation using the dot sign. in the body of the subroutine.

Now let's say we decided that adding a name after the member's route is optional. We can make it optional and also use the OR operator so that anyone who doesn’t add a name is referred to anonymous.

Now, let's modify our code.

index.pl

use Dancer;

get '/members/:firstname?' => sub {
    "Welcome Here " . ( param('firstname') || "Anonymous" );
};

dance;

Output:

Perl Dancer route patterns (2)
  • Notice the question sign which makes the firstname optional.
  • Equally take note of the modification at the body of the subroutine.



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.