Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

How to use Perl in web pages?

by kitsune (Acolyte)
on Jun 06, 2009 at 21:32 UTC ( #769162=perlquestion: print w/replies, xml ) Need Help??
kitsune has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone,

I've been using PHP on my website for awhile now and recently, it has been driving me crazy! I decided that moving to Perl would be beneficial. However, I do not know the first step in using Perl in web pages. In PHP, it is simple. You enclose the code in <?php and ?>. Is there something like this for Perl too? If not, how do Perl programmers embed Perl into their websites.


Replies are listed 'Best First'.
Re: How to use Perl in web pages?
by Corion (Pope) on Jun 06, 2009 at 21:57 UTC

    The simplest of all ways is to use the CGI module and just print out your HTML:

    #!/usr/bin/perl -w use strict; use CGI; my $q = CGI->new; my $name = $q->param('name'); print $q->header(); # just ignore the man behind the curtain print '<html><title>First page</title><body>'; if (defined $name) { print "<h1>Hello $name</h1>"; } else { print "<h1>Please enter your name</h1><form action=''><input name= +"name" type="text"></form>"; }; print '</html>';

    In short time though, you will want to move to one of the templating systems. If you feel at home with the code-intermingled-with-HTML way of PHP, then Mason might be your thing. If you want to get away as far as possible from that, take a look at Petal, HTML::Seamstress and HTML::Template. The Template Toolkit has its own powerful programming language built in, so you can get more creative with these templates, but, again, beware of the danger of mixing code and HTML too much.


      Good answer; it neatly addresses the "get started quickly" feel which one gets from the OP's question.

      You'll get an error, though, with this line:

      print "<h1>Please enter your name</h1><form action=''> <input name="name" type="text"></form>";

      because of the embedded quotes.

      My favorite method for overcoming this problem (especially in CGI programming) has been to use the qq operator, eg.:

      print qq[<h1>Please enter your name</h1><form action=''> <input name="name" type="text"></form>];

      Stylistically, you'd also probably want to close the <body> tag too, with </body>, though of course it isn't a necessity.


      Wow, that seems like quite a lot of options. To someone who is new at this, which one would you recommend trying first? I do not need it to be similar to the PHP way of embedding in HTML. It does get pretty messy that way.

        Based on my own experience, I would agree with everything hangon said, and also recommend that you first get yourself oriented with a simpler script that uses just the CGI module, as demonstrated by Corion. As you get comfortable with the basics of how things work, start using HTML::Template. You'll appreciate how it improves things relative to using only CGI.

        And then when that's working for you -- and if you want your web app to manage a wider range of activity with a minimal amount of coding, get acquainted with CGI::Application. Getting started with it is pretty easy (once you understand CGI and HTML::Template), and it really helps for keeping the code simple and manageable as the app gets bigger.

        Spend some time skimming and probing the full length of the documentation that comes with each module, and then refer back to that as needed when writing code. Each manual has a lot of information (the size of the manuals might be a bit scary at first), and a lot of helpful and useful examples. When you understand the details provided in the manual about a particular function, it's a good bet that you really do know what you're doing.

        I do not need it to be similar to the PHP way of embedding in HTML. It does get pretty messy that way.

        In the Perl world, the mantra is There is more than one way to do it. This often leaves newbies in the position of having to make difficult decisions. To avoid embedding code in the PHP style, you may want to start out with CGI::Application and HTML::Template. There are tutorials on this site will help you: A Tutorial for CGI::Application, HTML::Template Tutorial and Using HTML::Template. As you gain experience, you may want to look at other options, but you can do a lot with these modules.

Re: How to use Perl in web pages?
by CountZero (Bishop) on Jun 06, 2009 at 21:55 UTC
    What do you know about Perl already? If this is your first foray into Perl-country, you will first have to learn Perl.

    But to answer your question, yes one can directly embed Perl in web-pages through the use of modules such as Apache2::ASP, although Perl knows a lot of other ways to build dynamic web-pages from CGI via CGI::Application and Catalyst or the use of templating systems such as Template::Toolkit.


    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      I have used Perl before, but only for writing simple scripts to execute on my own computer. How much experience in Perl is necessary to use Perl in web pages?

        Actually there is no diference: it is the same Perl and the beauty of Perl is that you can do a lot without having to know all the ins-and-outs of the language. As you get more experienced you will start writing more efficient code of course by using the more advanced (some would say "arcane") constructs and techniques of Perl.

        The basic structure of any Perl script that does "web"-things is easy:

        1. Your script is called by the web-server
        2. In your script you have access to the data of the request (preferably through a module such as CGI or CGI::Simple)
        3. You do something with this data and print the response (that could be as simple as some HTML-code to make a web-page or do some complex processing of form-data and update a database and then output the result as a web-page.
        4. Wash, Lather, Rinse, Repeat


        A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

        How much experience in Perl is necessary to use Perl in web pages?

        A minimum of 42 on the (open-ended) Camel scale ;-)

      Good thing there is plenty of help here. That one had me stumped, course I am just learning. Wanted to thank every one for replying.
Re: How to use Perl in web pages?
by TGI (Parson) on Jun 07, 2009 at 06:27 UTC

    The best way to get started is with a simple CGI script. IMO, the best way to get started writing CGI scripts is to read Ovid's CGI Course.

    Thanks to jdporter for hosting it and to Ovid for writing it in the first place.

    TGI says moo

Re: How to use Perl in web pages?
by halfcountplus (Hermit) on Jun 07, 2009 at 02:42 UTC
    I just took an interest in html embedded perl and started reading this:

    Embedding Perl in HTML with Mason

    which is free online and you should at least be aware of it.

    For sure: do some CGI stuff. You actually do not need to use *any* perl modules at all to do CGI (which is not to say they are not useful). Using the basic "CGI" one will spare you some simple parsing tasks also probably covered by PHP, and provide you with some helper functions as hinted at behind Corion's "curtain" -- but it is not (just to let you know) strictly necessary. CGI just works via <STDIN> and <STDOUT>.

    If you want to get your basic perl skills up to snuff I'd very strongly recommend "Intermediate Perl" (Schwartz, foy, Phoenix).

      Mason is a great tool. But it is complex and it is too easy to fall into the bad habits when learning it. PHP encourages those same bad habits.

      If kitsune looks at Mason, I would encourage her (him?) to look very closely at discussions of best practices, and think hard about MVC models of application design.

      Mason is a huge slice of awesome, but the helping is big enough that indigestion may ensue if it is not approached with caution.

      TGI says moo

Re: How to use Perl in web pages?
by systems (Pilgrim) on Jun 07, 2009 at 06:37 UTC
    Okay, I don't expect my opinion to be popular, but I really think you should stick with PHP and least for a while longer.
    Check advanced PHP frameworks like or

    Just moving to Perl, won't make web-develpoment easier for you. You need to use a Perl Framework, like Template-Toolkit , Mason, CGI-Application and Catalyst, to really gain an edge.
    I am learning how to use Perl for web-development, but this mainly because I like Perl and like learning Perl and I love its community, so I am biased.

    To conclude, I don't think PHP is your problem. And I do think you have a huge gap in your knowledge about web-framework, so learn about web-frameworks, before switching your language

      You have a valid point; Perl is not a silver bullet. Even those of us who believe that Perl is a better language than PHP in every way must reluctantly acknowledge that switching languages is not the solution to every problem. :)

      Whether this means someone "should" stick with PHP is more debatable, and depends on their personal learning style. Some people find gradual learning easier than rapid change, and if kitsune's that sort of person then sticking with PHP might be helpful. On the other hand, some people find a clean break helpful; it instantly gets them away from any existing bad habits, and it forces them to learn the new approach properly instead of falling back on their old tried-and-tested approaches when the going gets tough. If kitsune is that sort of person, then switching to Perl now would be best.

Re: How to use Perl in web pages?
by dj_goku (Novice) on Jun 08, 2009 at 05:54 UTC

    I have recently been trying out (and liking it so far) building web applications with catalyst. I have used the below module (Catalyst::Manual::Tutorial) which is very nice. I would try to learn the technologies used with Catalyst. Like Template::Toolkit, DBIx::Class. If you need help I would use, and check out #catalyst, and #dbix-class, and #tt.


Re: How to use Perl in web pages?
by pajout (Curate) on Jun 08, 2009 at 11:54 UTC
    I would like to share my point of view:

    Perl really provides many options how to support dynamic web. You should evaluate your motives to choose the proper one. For instance:

    If I need to script some simple dynamic page(s) from time to time and I really do not care, what is behind the scene, I try CGI. This is concept very similar to php. Access of the url causes launching of related script.

    If I need to code web project, controlling Apache behaviour relatively exactly, but I do not need prefabricated modules, I try pure mod_perl. Access of the url causes launching of related perl module subroutine.

    If I need a lot of work prefabricated, something like Catalyst or Mason would be proper choice.

    Other dimension is templating. My opinion is that templating (mixing form and content) varies from trivial (simple web service with text or xml output, web API) to complex solution (large webs working with different types of browsers). Trivial solutions can be easily supported by direct print from the code, complex solution needs some mature and complex templating system. I typically operate somewhere in the middle, liking Petal.

Re: How to use Perl in web pages?
by salazar (Scribe) on Jun 09, 2009 at 00:12 UTC
    Hey man,

    I'd say I'm in the same boat as you. I've done some web development in PHP, and decided to at least try Perl out. Soon enough, I liked it a whole lot better.

    As previously mentioned, your first step is to learn the basics of Perl. A lot of it is similar to PHP, but there's also a lot that just makes more sense. Head over to this free library to read up. It will stall whatever web projects you have going, but I think without taking time to learn, your code will essentially be PHP code written in Perl.

    Regardless, the biggest difference between PHP and Perl is that PHP was made for the web. And so, PHP will automatically handle a lot of things for you, which you need to manually do in Perl. For example, consider headers. At the end of the script, PHP will automatically send your header, unless you specified that a different header be sent. Also, any cookies set via setcookie will be sent with that header. In Perl, you have to do that yourself: It's not hard, but it tripped me up, especially before I realized that any and all cookies needed to be sent with the header.

    If you haven't already started to try to use a templating system, I'd strongly suggest that. It may not make much sense at first... but try using it for a bit, and then compare your results to what you had before. You will get much cleaner results, and even if you aren't hiring some HTML kiddie who doens't know Perl, this will help you out. It's much much easier to trouble shoot your HTML / CSS without your Perl getting in the way, and vice versa.

    So, as a direct answer to your question: It's possible, both using CGI and print'ing your HTML, and with something like HTML::Mason. However, try out the Template Toolkit. Using this tutorial, I literally learned the basics and made a simple dynamic page in about ninety seconds. Still, to each his own: Do what you're comfortable with, and if it's not for you, know that there are other options out there. Kind of like moving to Perl from PHP ;-).

    Best of luck!
Re: How to use Perl in web pages?
by John M. Dlugosz (Monsignor) on Jun 08, 2009 at 15:43 UTC
    I've used Microsoft's ASP pages, using Perl as the scripting language. So, just put the Perl code inside <% ... %> tags, like you are used to.

    Mason, as mentioned on another reply, is similar. But, it is better at allowing you to make reusable modules for a page. I think you will find Mason to be a friendly and gentle transition to make, expecially for porting your old pages. You probably still need to improve existing stuff without re-engineering the whole site, and you've reached the limit on PHP's programming.

    But... what's wrong with PHP? Are you bothered by everything being global and in the same namespace? Sure, Perl will be a change. Is the limitation the whole HTML file with embedded fragments? Mason may be a step up in allowing code to execute in more places during the process and affecting what gets done, and in breaking the page up into reusable modules. But it still has limits. I used Mason to make a web page for a store, and was able to design the reusable components (menus, header, footer, etc.) nicely, as it was a static site that just needed to customize the component for each page. I'm also using it on my personal site for a page that automatically picks up all the scans of pages and formats the page to organize and browse them (e.g. this one)

    Just printing the HTML you want, under full control of the program, is the ultimate in flexibility. But it gets tedious quickly. There are modules to help with this, in simple ways such as formatting tags as easy as printing text, all the way up to template systems. You will like templates: HTML code for the rough page, but processing is under your control. Your code is on the outside, not the inside.

    Finally, there are complete frameworks. Catalyst seems to be the top of the heap now. But you need to learn more than just Perl.

Re: How to use Perl in web pages?
by scorpio17 (Abbot) on Jun 08, 2009 at 15:55 UTC

    I think another really important point to consider is that a lot of the suggestions you've been given sort of imply/assume that you have root login to your own web server. If you're accustomed to using a shared host web provider that simply lets you upload html pages (or html pages containing php), then you may be in for a rude awakening! Most shared host web providers don't allow you to upload your own CGI scripts. Some providers may claim to offer "cgi scripts", but what they mean is that they have a few canned scripts (guest books, counters, email gateways) that you may access by using special links (not the same as allowing you to upload custom scripts).

    Even if you find a web host who will let you have your own custom CGI scripts, they most likely will not provide support for mod_perl, or Mason, etc.

    So choosing a web host that provides what you want will be more difficult. They're out there - but not to the same degree as the html/php guys. And it will probably cost more.

    Another option is to buy a "virtual server". This will look like you're logging in (as root) to your own server, but it's actually a virtual machine, being hosted on a machine running dozens of other virtual machines. This is great for playing around and doing experimental stuff, but probably not reliable enough for a real production site. But a dedicated server with root login will cost 10x more than your typical shared host plan.

    You'll also be forced to learn a great deal about server configuration, web site security, system administration, database administration, etc. Otherwise, your site will get hacked and turned into a spam bot in no time.

    But most of the information you'll need is freely available online, if you take the time to look for it. You have a lot of homework to do!

      ... a lot of the suggestions you've been given sort of imply/assume that you have root login to your own web server.

      Login access, for sure, but not necessarily root access. It's easy to install modules in paths owned by you (not owned by root), and to make sure that /usr/bin/perl finds the modules you installed -- at least, it's pretty trivial on *n*x servers, I don't know about the M$ variety.

Re: How to use Perl in web pages?
by tomfahle (Priest) on Jun 08, 2009 at 19:49 UTC
Re: How to use Perl in web pages?
by Anonymous Monk on Jul 01, 2013 at 01:00 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://769162]
Approved by Perlbotics
Front-paged by Arunbear
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2018-02-22 19:27 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (298 votes). Check out past polls.