Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Embeding Perl in HTML the PHP way

by heatblazer (Scribe)
on Sep 11, 2012 at 19:02 UTC ( #993034=perlquestion: print w/replies, xml ) Need Help??
heatblazer has asked for the wisdom of the Perl Monks concerning the following question:

Hello, monks

I have a plain but yet not simple question - how can I embed Perl into HTML document the PHP way?

I know about mason but is there a more simple way to do it?

Let`s give an example of what I want to do for the file index.html:

<html><head></head> <body> <?perl printf("%s", $some_string); ?> </body> </html>

Replies are listed 'Best First'.
Re: Embeding Perl in HTML the PHP way
by Your Mother (Bishop) on Sep 11, 2012 at 19:41 UTC
    #!/usr/bin/env perl use Template; my $tt = Template->new({ EVAL_PERL => 1 }); $tt->process(\*DATA) or die $tt->error(), $/; __DATA__ [% PERL %] print "OHAI DER!"; [% END %]

    The Template code is no simpler than the Mojolicious example but still good to know about. Mason will do the same thing in a slightly different way as well.

    Update: nagged into adding links. I HAZ A LAZY. :P

Re: Embeding Perl in HTML the PHP way
by davido (Archbishop) on Sep 11, 2012 at 19:20 UTC

    I know of no simpler solution than what is provided by a Mojolicious::Lite framework (see the Mojolicious website).

    #!/usr/bin/env perl use Mojolicious::Lite; get '/index' => sub { my $self = shift; $self->render('index', some_string => "Hello world!!!" ); }; app->start; __DATA__ @@ index.html.ep <!DOCTYPE html> <html> <head> <title>Hello world</title> </head> <body> <%= $some_string %> </body> </html>

    Let's say you call that "". Run it like this: ./ daemon. Point your browser to http://localhost:3000/index.html.

    Deployment options are covered here: Mojolicious::Guides::Cookbook#DEPLOYMENT.

    This is a minimal example. In a real app you would want to reduce the redundancy somewhat between templates by using layouts. And you would define more routes, of course. ...and probably set index up as a default fallback route. For example:

    get '/goodbye' => sub { $_[0]->render( 'goodbye', some_string => "Goodbye world!" ); }; get '/*fallback' => { fallback => 'index' } => sub { $_[0]->render( 'index', some_string => "Hello world!\n" ); }; __DATA__ @@ index.html.ep ........ @@ goodbye.html.ep ...........

    The fallback is defined as your last route so that it doesn't try to take over unless no other routes matched. Also you would probably eventually inflate the app so that the templates can each live in their own files. Any pages that are truly static content will reside in public/.


      Thank, you, I`ll add it to my todo list for testing

Re: Embeding Perl in HTML the PHP way
by sundialsvc4 (Abbot) on Sep 11, 2012 at 19:46 UTC

    However ...

    Generally speaking, Perl does not pursue this objective in (what you call) “the PHP way,” and in my experience:   these days, neither does PHP(!).

    The Perl language clearly espouses the notion of “separation of concerns,” where the logic of the application is studiously separated from the presentation.   Typically, a Perl-driven (and a modern-day PHP-driven ...) web-site is viewed as being:   “a program that takes a URL-string and possibly POST-data as input, and which generates an HTML string as output ... using a template to do so.”

    If you are still “embedding programming_language into HTML,” then I cordially advise you that you should re-consider that approach.   Even though the PHP language started-out in this direction, it has since shifted away from it ... and, so should you.

    P.S.:   I speak as someone equally conversant and up-to-speed in both language systems, not-to-mention many others.   “This is not my first rodeo.”   (As, as you will find, is the case for most of us around here.)

      Separation of concerns (the Model, View, Controller) approach is, of course, the primary goal of all of the modern frameworks (including Catalyst, Dancer, and Mojolicious, as well as those popular in other languages). And I agree that the notion of embedding the bulk of an application in the HTML (ie, in the template) is the wrong way to go. But I think you're taking it a little far when you say:

      If you are still "embedding programming_language into HTML," then I cordially advise you that you should re-consider that approach.

      Surely you must mean that the application's business logic should reside in "model" code, the web application's minimal wiring should exist in "controller" code, and the view should reside in the templates, wherein embedded logic is kept to the minimum required, no more, and no less (which is different from reconsidering the concept of embedding altogether).

      Maybe it would help me to understand the line you're drawing if it were accompanied with an example.


        Sure, Dave.   What I am referring to is the original concept that a PHP file would consist of HTML code with <?..php code here..?> tags stuck all through it.   For instance, if you wanted to generate an HTML table, you literally enclosed the <tr> tags and so-forth inside of an inline PHP loop.   The idea was that the output would consist of the un-bracketed (HTML) content interspersed with the output that may be produced by any PHP code wherever it appeared.   There was (by design, actually), no separation between the two.

        That turned out to be a really bad idea, and the PHP community quickly moved away from it to adopt MVC strategies that are in many ways quite similar to what one now sees being done in Perl, et al.   The language itself also sprouted many new features, including many similarities to Perl and an openly-acknowledged copy of its regex technology.   I guess good word spreads fast... ;-)   Plus, the Zend folks include some really crackerjack coders.   PHP now does MVC along with the best of them, but the language emphatically didn’t start out that way.   (But hey, it sure seemed like a perfectly good idea at the time ...)

      these days, neither does PHP(!)

      I really wish that were true, but it isn't, at least in my limited experience. The worst offenders seem to be some of the big guns like Drupal and Joomla (I've not looked at WordPress in sufficient detail to know)!

      Those systems positively encourage template files that are a sea of PHP immersed in an ocean of HTML with the result that you can generally find neither the forest nor the trees.

      Having worked with PHP extensively over the last few months I can confirm all the rumours that suggest PHP took only those parts of Perl the author understood (not very much actually), reimplemented badly those bits that weren't understood, provided multiple inconsistent implementations where there were several alternatives, and then added functions for anything anyone ever asked for. The result is not good!

      True laziness is hard work

        That's the templates though. Intermingled code and HTML are par for the course when it comes to templates. (TT2 does this just as much. Example from the documentation. It's not Perl code intermingled - it's worse; its a whole other Turing-complete language.) The files that the browsers actually hit start with <?php and don't contain a ?>, so they're PHP all the way; not HTML with little chunks of PHP.

        There are plenty of awful things about the design of Drupal. This is not one of them though.

        Update: in case anyone doubts the Turing completeness of TT2...

        use Template; my $template = Template->new({ POST_CHOMP => 1, EVAL_PERL => 0, # note: false! }); $template->process(\*DATA, {}, \*STDOUT) or die $template->error; __DATA__ [% MACRO fib(n) BLOCK %] [% IF (n < 2) %] [% n %] [% ELSE %] [% fib(n - 1) + fib(n - 2) %] [% END %] [% END %] Fibonacci sequence... [% FOREACH i IN [ 1 2 3 4 5 6 7 8 9 10 ] %] [% fib(i) +%] [% END %]
        perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      I`ll most certainly reconsider what you`ve said. Thanks.

Re: Embeding Perl in HTML the PHP way
by aaron_baugher (Curate) on Sep 11, 2012 at 22:33 UTC

    Your example is how it's done in HTML::Mason, although the syntax would be slightly different. For one thing, you don't need the printf at all, since you're just printing a string. So you can do any of these:

    <body> <% $some_string %> </body> <body> % print $some_string; </body> <body> <%perl> print $some_string; </%perl>

    Like others here, I prefer frameworks these days. Mixing code with layout just doesn't scale well at all. Mason is better than PHP because it's Perl, but things still get ugly easily for some of the same reasons they do in PHP. Currently I'm using Dancer with Dancer::Template::Mason as my templating system, and liking that quite a bit. My templates are Mason, so they can use Perl code for things like loops, rather than requiring me to learn some new templating system's loop syntax. But since all my actual code that processes the data (Controller and Model, in MVC terms) is separate, the template files are still very clean.

    Aaron B.
    Available for small or large Perl jobs; see my home node.

      Yes, I think that everybody figured out pretty-quickly that the inline-code approach was an inferior approach ... particularly when I18N (internationalization) began to be a very big deal in this world-wide web of ours.   Really good templating systems, and then, really good web frameworks built on them, appeared in most language systems and all of them have matured along generally similar lines.   There is no reason to “go back,” and an abundance of reasons not to.

Re: Embeding Perl in HTML the PHP way
by tobyink (Abbot) on Sep 11, 2012 at 20:42 UTC

    Embperl allows something along those lines. However, take a look at the dates in the "News" section of the Embperl website.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: Embeding Perl in HTML the PHP way
by RichardK (Parson) on Sep 12, 2012 at 11:28 UTC

    Personally I still find CGI easier for simple cases like your example

    # example from the CGI docs use CGI; # load CGI routines $q = CGI->new; # create new CGI object print $q->header, # create the HTTP header $q->start_html('hello world'), # start the HTML $q->h1('hello world'), # level 1 header $q->end_html; # end the HTML
Re: Embeding Perl in HTML the PHP way
by greengaroo (Hermit) on Sep 13, 2012 at 13:36 UTC

    When I first started learning and programming Perl, back in 1999, I was doing exactly what you want to do!

    If you are using Apache Web Server, please take a look at ePerl, Apache::ePerl and OSSP eperl. I think you will need mod_perl too.

    Basically what you want to do is add something like this do your httpd.conf file:

    <Files ~ "/usr/local/apache/htdocs/.+\.iphtml$"> Options +ExecCGI SetHandler perl-script PerlHandler Apache::ePerl </Files>

    This will make Apache pre-parse the .iphtml files and interprets any embedded Perl scripts. Basically, your .iphtml files are HTML files with Perl script blocks. Note that the extension of the files could be anything you want, even .html but keep in mind this means all .html files would be pre-parsed, even if they don't contain embedded Perl.

    So this is what a Perl script blocks would look like:

    <html> <body> <? print 'Hello World!<br/>'; !> </body> </html>

    Pretty close to PHP, hey? I think you can even change the embedded block delimiters to whatever you want with Apache::ePerl module configuration.

    I remember, I even created websites using embedded Perl inside XML files back in the days! I was using AxKit! But it as been decommissioned in 2009.

    Good luck!

    There are no stupid questions, but there are a lot of inquisitive idiots.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2018-03-21 10:02 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (265 votes). Check out past polls.