ralijani has asked for the wisdom of the Perl Monks concerning the following question:

Hi dear friends I want to use javascipt code in my perl(CGI) program. how can i do it if it is possible give me an example thanks for your help

Replies are listed 'Best First'.
Re: using javascript in perl
by Corion (Patriarch) on Mar 15, 2004 at 14:32 UTC

    If by "using javascript code" you mean "output Javascript code", then it's easy - you output Javascript code the same as you output any text:

    #!/usr/bin/perl -w use strict; use CGI qw(standard); print header; print <<'END_OF_JS' <script> alert("Hello World"); </script> <p>And here comes some text of the rest of the page</p> END

    If you mean that you want to run Javascript on your webserver, like for example Domino does (OK, Domino uses LotusScript, but LotusScript is not completely unlike Javascript), then you will have to look for a Javascript machine, for example Javascript::SpiderMonkey. But I doubt that this is the solution you want.

Re: using javascript in perl
by kutsu (Priest) on Mar 15, 2004 at 14:53 UTC

    Since Corion has already given an answer I will just give two pointers: consider reading Ovid's Tutorial and you might want to look at Html::Template or some other Templating system.

    #!/usr/bin/perl -w use HTML::Template; my $template = HTML::Template->new(filename => 'test.tmpl'); $template->param(TEXT => "Hello World"); print "Content-Type: text/html\n\n", $template->output;
    <html> <body> <script = "javascript"> alert("<TMPL_VAR NAME=TEXT>"); </script> <p>There you go a modified version of Corion's script using HTML::Temp +late.</p> </body> </html>

    "Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce

Re: using javascript in perl
by UnderMine (Friar) on Mar 15, 2004 at 15:03 UTC
    Without more context it is hard to give an answer. The last couple of posts gave a very good explaination for outputting JavaScript from perl.

    If you want to go further you may well need to look a Javascripts document.write that allows you to change the contents of a page based upon runtime parameters. This can be used to embed a dynamic call to include a Javascript library. Normally this is done when you need a browser specific version of the library and wish do decrease the download time by only downloading the correct code. However this could be to include any javascript library and before now I have had libraries for menus that are writen in perl based of database results.

    Hope it helps
    UnderMine