MasterPage using HTML::Template

MasterPage using HTML::Template.

Advertisements

MasterPage using HTML::Template

Can we create single master page which includes header,footer and left-right panel ?  Absolutely yes yes !!! Since morning I was working on it and finally Eureka !!!

Note: It can be achieved by filter parameter of  HTML::Template, we are going to see in below example

Let me start with step by step

Create Masterpage: /html/masterpage.tmpl

<html>
<body>
<div style=”background:red;width:100%;height:100px”>
Header Section
</dvi>
<div style=”background:white;width:100%;margin-top:200px” id=”content”>
<tmpl_include name=”childpage”>
</div>
<div style=”background:green;width:100%;height:100px;margin-top:200px”>
Footer Section
</div>
</body>
</html>

Create Page Module: /cgi-bin/lib/Page.pm

package Page;
use CGI;
use HTML::Template;

BEGIN {
my $query = CGI->new();
print $query->header();
}

sub output  {
my $hash = pop @_;

my $childpage = $hash->{‘childpage’};
my $filter = sub {
my $text_ref = shift;
$$text_ref =~ s/childpage/$childpage/
};

my $template = HTML::Template->new(filename => $hash->{‘masterpage’},filter => $filter);
print $template->output();
}
1;

Create Child Pages: /html/ index.tmpl, /html/login.tmpl

index.tmpl

This is the home page or index page of website

login.tmpl

<form>
<table>
<tr><td>Username:</td><td><input type=’text’ /></td></tr>
<tr><td>Password:</td><td><input type=’text’ /></td></tr>
<tr><td colspan=”2″><input type=’submit’ /></td></tr>
</table>
</form>

Create CGI pages:  /cgi-bin/cgi/index.cgi,  /cgi-bin/cgi/login.cgi

1)  index.cgi

#!c:\perl\bin\perl.exe -w
use CGI::Carp qw(fatalsToBrowser);
use lib “./../lib/”;
use Page;

Page->output({
‘masterpage’ => ‘../../html/masterpage.tmpl’,
‘childpage’ => “index.tmpl”,
});

2)  login.cgi

#!c:\perl\bin\perl.exe -w
use CGI::Carp qw(fatalsToBrowser);
use lib “./../lib/”;
use Page;

Page->output({
‘masterpage’ => ‘../../html/masterpage.tmpl’,
‘childpage’ => “login.tmpl”,
});

Call CGI page:

http://localhost/cgi-bin/index.cgi

http://localhost/cgi-bin/login.cgi

Please contact me you want any query or want .rar file of this example.

 

Subroutine

what is subroutine?
Subroutines are the basic computer science methodology to divide tasks into subtasks.

Example:

sub version {
print “version of pl file.”;
}

It can be call by name without braces, but make sure subroutine defined before we use them

Example:

mysub;

sub mysub {
print “mysub is called”;
}

# Following error comes if sub routine is called without braces

# Unquoted string “mysub” may clash with future reserved word at t.pl line 4.
# Useless use of a constant (mysub) in void context at t.pl line 4.

Parameters & Arguments

@_ is the list of incoming parameters to a sub.
$_ is known as the “default input and pattern matching space

sub mysub {
foreach(@_) {
print $_;
}
}
myspace(1,2,3);

Return

By default (implicitly) last statement of sub routine returns
Programmer must write return statement to return explicitly from sub routine.

Sub routine prototype 

Prototypes let you declare subroutines to take arguments just like many of the built-ins, that is, with certain constraints on the number and types of arguments. We call them “prototypes”, but they work more like automatic templates for the calling context than like what C or Java programmers would think of as prototypes. With these templates, Perl will automatically add implicit backslashes, or calls to scalar, or whatever else it takes to get things to show up in a way that matches the template

Example:

sub sum_of_two_squares($$)  {

my ($a, $b) = (shift, shift);

return $a**2 + $b**2;

}

sum_of_two_squares(1,2);      # No run-time error

sum_of_two_squares(1,2,3);  # ERROR

 

Declared as Called as
sub mylink ($$) mylink $old, $new
sub myreverse (@) myreverse $a,$b,$c
sub myjoin ($@) myjoin ":",$a,$b,$c
sub mypop (\@) mypop @array
sub mysplice (\@$$@) mysplice @array,@array,0,@pushme

 

Binary, Octal, and Hexidecimal Numbers in Perl

Perl understands numbers specified in binary (base-2), octal (base-8), and hexadecimal (base-16) notation only when they occur as literals in your programs. See below example

#!/usr/bin/perl -w
use strict;
use warnings;

my $hexadecimal = 0x2e;
my $octal = 057;
my $binary = 0b101110;

print “Hexadecimal: “,$hexadecimal ,”, Octal: “,$octal,” Binary: “,$binary;

#Hexadecimal: 46, Octal: 47 Binary: 46

If they come in as data—such as by reading from files or environment variables, or when supplied as command-line arguments—no automatic conversion takes place.

If you want to convert a string (e.g., “0b10110”, “0x55”, or “0755”) containing a binary, octal, or hexadecimal number to the correct number, use Perl’s hex function if you have a hexadecimal string like “2e” or “0x2e”:

$number = hex($hexadecimal);         # hexadecimal only ("2e" becomes 47)

Use the oct function if you have a hexadecimal string like “0x2e”, an octal string like “057”, or a binary string like “0b101110”:

$number = oct($hexadecimal);         # "0x2e" becomes 46
$number = oct($octal);               # "057" becomes 47 
$number = oct($binary);              # "0b101110" becomes 46

The oct function converts octal numbers with or without the leading “0”; for example, “0350” or “350”. Despite its name, oct does more than convert octal numbers: it also converts hexadecimal (“0x350”) numbers if they have a leading “0x” and binary (“0b101010”) numbers if they have a leading “0b”. The hexfunction converts only hexadecimal numbers, with or without a leading “0x”: “0x255”, “3A”, “ff”, or “deadbeef”. (Letters may be in upper- or lowercase.)

How swap values of two variables

PERL is magical language, I have no doubt about it. See the following simple example to swap the value of two variables

#!/usr/bin/perl -w
use strict;
use warnings;

my $a = 11;
my $b = 22;
print “a = “, $a,”b = “,$b,”\n”;

($a,$b)= ($b,$a); # here is the magic
print “a = “, $a,”b = “,$b;

No temporary variable and complex logic as compare to other languages like c#, vb and java

It is piece of cake !!! Really

 

 

Best Practice For PERL

#!c:\>perl\bin\perl.exe
use strict;
use warnings;
use diagnostics;

use strict

  • Generates an error if you use symbolic references ( Exp: $x=10; $var = “x”; $$var = “30”; print $x; )
  • It generates an error if you use a variable without declaring it. ( Exp: $a = 10; )
  • It also generates an error if you leave barewords hanging around in the script ( Exp:  foo()  #correct; foo #incorrect; )

use warnings

Generates a warning message based on many criteria, which are described in the POD ‘perllexwarn’. These warnings have nothing to do with strictures, but rather, watch for the most common “gotchas” one is likely to encounter in their programming. It is a best practice to use warnings while writing scripts too. In some cases where the message might be undesirable a certain warning category may be locally disabled within a scope. Additional info is described in ‘warnings’.

Example: Give warning message if uninitialized variable is used in script.

use diagnostics

makes the warnings more verbose, and in a development or learning environment, particularly among newcomers, that’s highly desirable.

Further more errors will be trapped by eval {} and Try::Tiny…

( Exp: $a = 10; )

Two sides of EVAL !!!

Do you know EVAL has two sides ? Even I did not know till I read EVAL line by line !!!

EVAL function works in two somewhat distinct ways depending on the type of its argument.

USE-1 (The String Form: Expression Evaluation)

If given a string, eval treats the string as a little program and compiles and execute it which is called dynamic expression evaluation. The contents of the string may or may not be known at compile time.

Example:

#!/usr/bin/perl -w
use strict;
use warnings;

my $a = 10; my $b = 20;my $c =0;
my $str = ‘$c = $a + $b’;
eval $str;                                                   # execute string as a little program
print $c;                                                    # It prints 30

Danger: Things get interesting if $str comes from elsewhere, we will see in next blog and also preventing measures to create secure PERL and CGI scripts

USE-2  (The Block Form: Exception Handling)

In this form, eval is followed by a block of code, not a scalar containing a string. It is used for handling run-time errors, or exceptions . Errors can be internal built-in ones (out-of-memory, divide-by-zero) or user-defined ones produced by die .

The following example shows how you can use the block form eval to trap a run-time divide-by-zero error:

eval {
$a = 10; $b = 0;
$c = $a / $b;     # Causes a run-time error,
# which is trapped by eval
};
print $@;   # Prints  “Illegal division by 0 at try.pl line 3

When the script is compiled, Perl syntax-checks the block of code and generates code. If it encounters a run-time error, Perl skips the rest of the eval block and sets $@ to the corresponding error text.

To signal your own errors, you use die . Perl knows whether a piece of code is currently executing inside an eval , and so, when die is called, Perl simply gives the error string – die ‘s argument – to the global $@ , and jumps to the statement following the eval block.

Java/C++ programmers would of course recognize the parallel to the throw, try , and catch statements, where try corresponds to the eval block, catch to the checking of $@ , and throw to die . (Essentially, the caller says to the run-time environment, “Here, try this code, and catch whatever errors are thrown by the callee.”)

 

[Curtsey: Advanced Perl Programming By Sriram Srinivasan]

Read carefully to find new things “God is in the small details”