Wednesday, January 23, 2008

The Subroutine Stack

Whenever Perl calls a subroutine, it pushes the details of the subroutine call onto an internal stack. This holds the context of each subroutine, including the parameters that were passed to it in the form of the @_ array, ready to be restored when the call to the next subroutine returns. The number of subroutine calls that the program is currently in is known as the 'depth' of the stack. Calling subroutines are higher in the stack, and called subroutines are lower.

This might seem academic, and to a large extent it is, but Perl allows us to access the calling stack ourselves with the caller function. At any given point we are at the 'bottom' of the stack, and can look 'up' to see the contexts stored on the stack by our caller, its caller, and so on, all the way back to the top of the program. This can be handy for all kinds of reasons, but most especially for debugging.

In a purely scalar context, caller returns the name of the package from which the subroutine was called, and undef if there was no caller. Note that this does not require that the call came from inside another subroutine – it could just as easily be from the main program. In a list context, caller returns the package name, the source file, the line number from which we were called, and the name of the subroutine that was called (i.e. us). This allows us to write error traps in subroutines like:

sub mysub
($pkg, $file, $line) = caller;
die "Called with no parameters at $file line $line" unless @_;
}

If we pass a numeric argument to caller, it looks back up the stack the requested number of levels, and returns a longer list of information. This level can of course be '0', so to get everything that Perl knows about the circumstances surrounding the call to our subroutine we can write:

@caller_info = caller 0;   # or caller(0), if we prefer

This returns a whole slew of items into the list, which may or may not be defined depending on the circumstances. They are, in order:

  • package: the package of the caller.
  • filename: the source file of the caller.
  • line: the line number in the source file.
  • subroutine: the subroutine that was called (that is, us). If we execute code inside an eval statement then this is set to eval.
  • hasargs: this is true if parameters were passed (@_ was defined).
  • wantarray: the value of wantarray inside the caller, see 'Returning Values' later in the chapter.
  • evaltext: the text inside the eval that caused the subroutine to be called, if the subroutine was called by eval.
  • is_require: true if a require or use caused the eval.
  • hints: compilation details, internal use only.
  • bitmask: compilation details, internal use only.

In practice, only the first four items: package, filename, line, and subroutine are of any use to us, which is why they are the only ones returned when we use caller with no arguments. Unfortunately we do not get the name of the calling subroutine this way, so we have to extract that from further up the stack:

# get the name of the calling subroutine, if there was one
$callingsub = (caller 1)[3];

Or, more legibly:

($pkg, $file, $line, $callingsub) = caller 1;

Armed with this information, we can create more informative error messages that report errors with respect to the caller. For example:

# die with a better error message

sub mysub {
($pkg, $file, $line) = caller;
die "Called from ", (caller(1)) [3], " with no parameters at $file line $line \n" unless @_;
...
}

If debugging is our primary interest, a better solution than all the above is to use the Carp module. The Carp module and other debugging aids are covered in Chapter 17.

One final point about the calling stack: if we try to access the stack above the immediate caller we may not always get the right information back. This is because Perl can optimize the stack under some circumstances, removing intermediate levels. The result of this is that caller is not always as consistent as we might expect, so a little caution should be applied to its use.

Monday, January 14, 2008

How to Use the Windiff.exe Utility

To compare two files by using Windiff.exe, follow these steps:
1.Start Windiff.exe.
2.On the File menu, click Compare Files.
3.In the Select First File dialog box, locate and then click a file name for the first file in the comparison, and then click Open.
4.In the Select Second File dialog box, locate and then click a file name for the second file in the comparison, and then click Open.

The information in the right pane indicates whether there is a file difference.
5.To view the actual file differences, click the first line in the Windiff.exe output results, and then on the Expand menu, click Left File Only, Right File Only, or Both Files.

The color-coded results indicate what the file differences are.
To compare two folders by using Windiff.exe, follow these steps:
1.Start Windiff.exe.
2.On the File menu, click Compare Directories.
3.In the Select Directories dialog box, type the two folder names that you want to compare in the Dir1 and Dir2 boxes. If you want to include subfolders, click to select the Include subdirectories check box.

The information in the right pane indicates the differences between the two folders.
4.To view the actual file differences, click the line that you want in the Windiff.exe output results, and then on the Expand menu, click Left File Only, Right File Only or Both Files.

The color-coded results indicate what the file differences are.

Friday, January 11, 2008

Row and Array Comparisons in postgresql

IN

expression IN (value[, ...])

The right-hand side is a parenthesized list of scalar expressions. The result is "true" if the left-hand expression's result is equal to any of the right-hand expressions. This is a shorthand notation for

expression = value1
OR
expression = value2
OR
...

Note that if the left-hand expression yields null, or if there are no equal right-hand values and at least one right-hand expression yields null, the result of the IN construct will be null, not false. This is in accordance with SQL's normal rules for Boolean combinations of null values.

NOT IN

expression NOT IN (value[, ...])

The right-hand side is a parenthesized list of scalar expressions. The result is "true" if the left-hand expression's result is unequal to all of the right-hand expressions. This is a shorthand notation for

expression <> value1
AND
expression <> value2
AND
...

Note that if the left-hand expression yields null, or if there are no equal right-hand values and at least one right-hand expression yields null, the result of the NOT IN construct will be null, not true as one might naively expect. This is in accordance with SQL's normal rules for Boolean combinations of null values.

Tip: x NOT IN y is equivalent to NOT (x IN y) in all cases. However, null values are much more likely to trip up the novice when working with NOT IN than when working with IN. It's best to express your condition positively if possible.

ANY/SOME (array)

expression operator ANY (array expression)
expression operator SOME (array expression)

The right-hand side is a parenthesized expression, which must yield an array value. The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ANY is "true" if any true result is obtained. The result is "false" if no true result is found (including the special case where the array has zero elements).

SOME is a synonym for ANY.

ALL (array)

expression operator ALL (array expression)

The right-hand side is a parenthesized expression, which must yield an array value. The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ALL is "true" if all comparisons yield true (including the special case where the array has zero elements). The result is "false" if any false result is found.

Row-wise Comparison

row_constructor operator row_constructor

The two row values must have the same number of fields. Each side is evaluated and they are compared row-wise. Presently, only = and <> operators are allowed in row-wise comparisons. The result is "true" if the two rows are equal or unequal, respectively.

As usual, null values in the rows are combined per the normal rules of SQL Boolean expressions. Two rows are considered equal if all their corresponding members are non-null and equal; the rows are unequal if any corresponding members are non-null and unequal; otherwise the result of the row comparison is unknown (null).

row_constructor IS DISTINCT FROM row_constructor

This construct is similar to a <> row comparison, but it does not yield null for null inputs. Instead, any null value is considered unequal to (distinct from) any non-null value, and any two nulls are considered equal (not distinct). Thus the result will always be either true or false, never null.

row_constructor IS NULL
row_constructor IS NOT NULL

These constructs test a row value for null or not null. A row value is considered not null if it has at least one field that is not null.

Wednesday, January 9, 2008

Array Functions

Here are the functions you can use with arrays:

* defined(VARIABLE) -- Returns true if VARIABLE has a real value and if the variable has not yet been assigned a value. This is not limited to arrays; any data type can be checked. Also see the exists function for information about associative array keys.
* delete(KEY) -- Removes the key-value pair from the given associative array. If you delete a value from the %ENV array, the environment of the current process is changed, not that of the parent.
* each(ASSOC_ARRAY) -- Returns a two-element list that contains a key and value pair from the given associative array. The function is mainly used so you can iterate over the associate array elements. A null list is returned when the last element has been read.
* exists(KEY) -- Returns true if the KEY is part of the specified associative array. For instance, exists($array{"Orange"}) returns true if the %array associative array has a key with the value of "Orange."
* join(STRING, ARRAY) -- Returns a string that consists of all of the elements of ARRAY joined together by STRING. For instance, join(">>", ("AA", "BB", "cc")) returns "AA>>BB>>cc".
* keys(ASSOC_ARRAY) -- Returns a list that holds all of the keys in a given associative array. The list is not in any particular order.
* map(EXPRESSION, ARRAY) -- Evaluates EXPRESSION for every element of ARRAY. The special variable $ is assigned each element of ARRAY immediately before EXPRESSION is evaluated.
* pack(STRING, ARRAY) -- Creates a binary structure, using STRING as a guide, of the elements of ARRAY. You can look in the next Chapter on References for more information.
* pop(ARRAY) -- Returns the last value of an array. It also reduces the size of the array by one.
* push(ARRAY1, ARRAY2) -- Appends the contents of ARRAY2 to ARRAY1. This increases the size of ARRAY1 as needed.
* reverse(ARRAY) -- Reverses the elements of a given array when used in an array context. When used in a scalar context, the array is converted to a string, and the string is reversed.
* scalar(ARRAY) -- Evaluates the array in a scalar context and returns the number of elements in the array.
* shift(ARRAY) -- Returns the first value of an array. It also reduces the size of the array by one.
* sort(ARRAY) -- Returns a list containing the elements of ARRAY in sorted order. See next Chapter 8on References for more information.
* splice(ARRAY1, OFFSET, -- Replaces elements of ARRAY1 with elements LENGTH, ARRAY2)in ARRAY2. It returns a list holding any elements that were removed. Remember that the $[ variable may change the base array subscript when determining the OFFSET value.
* split(PATTERN, STRING, LIMIT) -- Breaks up a string based on some delimiter. In an array context, it returns a list of the things that were found. In a scalar context, it returns the number of things found.
* undef(VARIABLE) -- Always returns the undefined value. In addition, it undefines VARIABLE, which must be a scalar, an entire array, or a subroutine name.
* unpack(STRING, ARRAY) -- Does the opposite of pack().
* unshift(ARRAY1, ARRAY2) -- Adds the elements of ARRAY2 to the front of ARRAY1. Note that the added elements retain their original order. The size of the new ARRAY1 is returned.
* values(ASSOC_ARRAY) -- Returns a list that holds all of the values in a given associative array. The list is not in any particular order.

Printing an Associative Array

The each() function returns key, value pairs of an associative array one-by-one in a list. This is called iterating over the elements of the array. Iteration is a synonym for looping. So, you also could say that the each() function starts at the beginning of an array and loops through each element until the end of the array is reached. This ability lets you work with key, value pairs in a quick easy manner.

The each() function does not loop by itself. It needs a little help from some Perl control statements. For this example, we'll use the while loop to print an associative array. The while (CONDITION) {} control statement continues to execute any program code surrounded by the curly braces until the CONDITION turns false, assoc.pl.

%array = ( "100", "Green", "200", "Orange");



while (($key, $value) = each(%array)) {

print("$key = $value\n");

}

This program prints:

100 = Green

200 = Orange

The each() function returns false when the end of the array is reached. Therefore, you can use it as the basis of the while's condition. When the end of the array is reached, the program continues execution after the closing curly brace. In this example, the program simply ends.

Checking the Existence of an Element

You can use the defined() function to check if an array element exists before you assign a value to it. This ability is very handy if you are reading values from a disk file and don't want to overlay values already in memory. For instance, suppose you have a disk file of Jazz Artist addresses and you would like to know if any of them are duplicates. You check for duplicates by reading the information one address at a time and assigning the address to an associative array using the Jazz Artist name as the key value. If the Jazz Artist name already exists as a key value, then that address should be flagged for follow up.

Because we haven't talked about disk files yet, we'll need to emulate a disk file with an associative array. And, instead of using Jazz Artist's address, we'll use Jazz Artist number and Jazz Artist name pairs. First, we see what happens when an associative array is created and two values have the same keys, element1.pl.

createPair("100",  "Miles Davis");

createPair("200", "Keith Jarrett");

createPair("100", "John Coltrane");



while (($key, $value) = each %array) {

print("$key, $value\n");

};



sub createPair{

my($key, $value) = @_ ;



$array{$key} = $value;

};

This program prints:

100, John Coltrane

200, Keith Jarrett

This example takes advantages of the global nature of variables. Even though the %array element is set in the createPair() function, the array is still accessible by the main program. Notice that the first key, value pair (100 and Miles Davis) are overwritten when the third key, value pair is encountered. You can see that it is a good idea to be able to determine when an associative array element is already defined so that duplicate entries can be handled. The next program does this, element2.pl.

createPair("100",  "Miles Davis");

createPair("200", "Keith Jarrett");

createPair("100", "John Coltrane");

while (($key, $value) = each %array) {

print("$key, $value\n");

};



sub createPair{

my($key, $value) = @_ ;



while (defined($array{$key})) {

$key++;

}



$array{$key} = $value;

};

This program prints:

100, Miles Davis

101, John Coltrane

200, Keith Jarrett

You can see that the number for John Coltrane has been changed to 101.

Monday, January 7, 2008

How to Create a Bullet List in Microsoft Excel

To Add a Bullet to an Existing Text Entry

1.Position the insertion point at the beginning of your text entry.
2.Type a symbol that you want to use as a bullet. To create the bullet character, press ALT+0149 (type 0149 on the numeric keypad).

You may want to include a space after the character so that the bullet will not be next to the text. Note that the bullet is an extended character and may not be available with all fonts.

Some other examples of characters you can use include: >, /, ~, !, and others.


To Create a Custom Text Format That Includes Bullets

1.Select the cell or range of cells that you want to apply bullets to.
2.On the Format menu, click Cells.
3.On the Number tab, click the Text category, and then click the Custom category.

Microsoft Excel places an at sign (@) in the Type box.
4.In the Type box, place the insertion point before the @, and type the symbol that you want to use as a bullet. To create the bullet character, press ALT+0149 (type 0149 on the numeric keypad).

You may want to include a space after the symbol so that the bullet will not be next to the text. Note that the bullet is an extended character and may not be available with all fonts.

Some other examples of characters you can use include: >, /, ~, !, and others.
5.Click OK.

Friday, January 4, 2008

installing module

> perl Makefile.PL
> make
> make test
> make install
perl -MCPAN -e 'install '

isArray() in Perl

foreach $item (@array){
if(ref($item) eq 'ARRAY'){
#It's an array reference...
#you can read it with $item->[1]
#or dereference it uisng @newarray = @{$item}
}else{
#not an array in any way...
}
}

ordering hash

use Tie::IxHash;
tie %HASH, "Tie::IxHash";
# manipulate %HASH
@keys = keys %HASH; # @keys is in insertion order

#Tie::InsertOrderHash does not allow you to change values in your hash and keep the original ordering. Thus, as mentioned above, updating the days in February will cause February to now appear after December when listing the keys.
#If you want to be able to change values without changing the ordering then Tie::IxHash may be a better option.

delete duplicate hash value's

my %seen;
for my $key (keys %students) {
my $value_key = "@{[values %{$students{$key}}]}";
if (exists $seen{$value_key}) {
delete $students{$key};
}
else {
$seen{$value_key}++;
}
}
undef %seen;

Finding oldest file in directory

my $xml_file = (reverse sort{(stat $a)[10] cmp (stat $b)[10]} glob "$dir_name/*.*")[0];

Monday, December 31, 2007

How to Format a Hard Drive in Windows XP

  1. Permanently erase all files with a disk sanitizer such as WipeDrive.
  2. Insert the Windows installation CD into the CD drive. Make sure that there are no other disks in the computer, and restart.
  3. At the "Welcome to Setup" screen, press the Enter key to set up Windows.
  4. Press the C key to continue setup.
  5. Press the F8 key to agree to the license.
  6. Press the C key to create a partition.
  7. Enter the size of the partition, or just press the Enter key to use maximum size.
  8. Select the "New (Unformatted)" option, and press the Enter key.
  9. Select NTFS or FAT file system (select NTFS if you are unsure).
  10. Simply follow the prompts format the hard drive in Windows XP continue the Windows installation.

Perl language gets a revamp

According to the foundation, this is the first new version in five years, and it has an emphasis on rough-and-ready practicality over syntactical formality.

Perl 5.0 has some features designed to make programming a little easier, according to the Perl Foundation. Among them is a "say" command that could ease some text-output chores, a "switch" operator to send a program in various directions depending on different situations, and improvements to the all-important "regular expression" methods for handling text. The Perl interpreter, which runs Perl programs, is also faster and requires less memory, the foundation said.

Perl programmers have been working already on two other future versions, 5.12 and Perl 6, but neither has a launch date yet, according to foundation spokesman Andy Lester. "Perl 5 and Perl 6 will stay in dual development. Perl 5 has such a huge installed base, it won't be going away any time soon after Perl," he said.

Perl founder Larry Wall initially announced Perl 6 in 2000, and development is still under way. Perl 6 attempts, among other things, to clean up some of the problems caused by the informality of Perl 5.

Closely related to Perl but separate is Parrot, an attempt to create a virtual machine that can execute programs written not just in Perl 6 but also in Ruby, Lua, Javascript, Python and PHP. (Virtual machine software provides an insulating layer that shields programs from the particulars of the computer and operating system they're running on.) Programmers released Parrot version 0.5.1 on 18 December.

Perl Offers Incremental Update; Version 6.0 Still Awaited

The first new version in five years of Perl, the popular Web scripting language, is now available, according to spokesmen from the Perl Foundation. The release is available for a free download as open source code from Perl.org or the Perl archive network.

Release 5.10 contains additions and enhancements to the language rather than the total revamp represented by a new version, Perl 6.0, announced by Perl's original author, Larry Wall, in 2000.

Perl -- like Tcl, Python, JavaScript, and PHP -- is a "dynamic" language that is interpreted, or run through an interpreter for each use of the program, instead of compiled once in advance. For that reason, changes to a phrase or line of Perl get picked up immediately in the next use of a Perl program in a runtime environment. Perl is often used to tie together dissimilar elements of a Web site, such as pieces of Java and Visual Basic code and other site resources.

But Perl has developed spontaneously, adding features and function before an overall design was in place. Wall, on the Perl.org Web site, said, "Perl 5 was my rewrite of Perl. I want version 6 to be the community's rewrite of Perl."

On the same site, the internals of the version 5 interpreter are described as "so tangled that they hinder maintenance, thwart some new feature efforts, and scare off potential internals hackers. The language as of version 5 has some mis-features that are a hassle to ongoing maintenance of the interpreter and of programs written in Perl."

Release 5.10 of Perl is meant to incorporate some additions to the language in lieu of the emergence of version 6.0. The interpreter has been sped up and given a smaller footprint in memory. "State variables" allow variables in a program to persist between calls to subroutines, so they don't have to be named again at a later point in the program.

A "say" command has been added to govern text output tasks. A "switch" operator sends a program's logic in various directions, depending on the conditions encountered. Changes have been made to how text is handled by the "regular expression" approach, according to information posted on the Perl.org Web site.

Release 5.10 was produced by Rafael Garcia-Suarez, a French software engineer who lives in Paris and is employed by Booking.com. He is a longtime contributor to Perl.

Version 6.0 seeks to establish a neutral mode of operation for the interpreter, allowing it to deal with different scripting languages. Interpreters often run pre-compiled code or byte code that has been moved beyond source code into a language that is more readily interpreted to the hardware. The version 6.0 interpreter may be able to run the byte code of other scripting languages, such as Python or Ruby, as well as Perl.

Fully compiled code, such as C or C++, runs faster but interpreted code is constantly picking up small changes to a program and incorporating them into its operation at runtime. Web site developers often resort to scripting languages for that purpose and for their ability to adapt to different languages and data types.

Thursday, December 20, 2007

submit forms to a new window, with window.open() features

you can just set up your form tag like this:

target=_blank
action=whatever.asp>

However, some would like to submit their forms to a new window that they have a little more control over.

This is not really an ASP issue, as the solution could be used in any web-based technology (including plain HTML). However, here is a way to submit a form to a new window, and have control over parameters like width, height, toolbar, etc.:

//
// method=post
// action=whatever.asp
//target=myNewWin>
/
//
/
// // value=' Submit '
// onClick='sendme();'>
//


CREATE VIEW in postgresql

Name
CREATE VIEW -- define a new view

Synopsis

CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW name [ ( column_name [, ...] ) ]
AS query

Description

CREATE VIEW defines a view of a query. The view is not physically materialized. Instead, the query is run every time the view is referenced in a query.

CREATE OR REPLACE VIEW is similar, but if a view of the same name already exists, it is replaced. You can only replace a view with a new query that generates the identical set of columns (i.e., same column names and data types).

If a schema name is given (for example, CREATE VIEW myschema.myview ...) then the view is created in the specified schema. Otherwise it is created in the current schema. Temporary views exist in a special schema, so a schema name cannot be given when creating a temporary view. The name of the view must be distinct from the name of any other view, table, sequence, or index in the same schema.
Parameters

TEMPORARY or TEMP

If specified, the view is created as a temporary view. Temporary views are automatically dropped at the end of the current session. Existing permanent relations with the same name are not visible to the current session while the temporary view exists, unless they are referenced with schema-qualified names.

If any of the tables referenced by the view are temporary, the view is created as a temporary view (whether TEMPORARY is specified or not).
name

The name (optionally schema-qualified) of a view to be created.
column_name

An optional list of names to be used for columns of the view. If not given, the column names are deduced from the query.
query

A SELECT or VALUES command which will provide the columns and rows of the view.

Notes

Currently, views are read only: the system will not allow an insert, update, or delete on a view. You can get the effect of an updatable view by creating rules that rewrite inserts, etc. on the view into appropriate actions on other tables. For more information see CREATE RULE.

Use the DROP VIEW statement to drop views.

Be careful that the names and types of the view's columns will be assigned the way you want. For example:

CREATE VIEW vista AS SELECT 'Hello World';

is bad form in two ways: the column name defaults to ?column?, and the column data type defaults to unknown. If you want a string literal in a view's result, use something like:

CREATE VIEW vista AS SELECT text 'Hello World' AS hello;

Access to tables referenced in the view is determined by permissions of the view owner. However, functions called in the view are treated the same as if they had been called directly from the query using the view. Therefore the user of a view must have permissions to call all functions used by the view.
Examples

Create a view consisting of all comedy films:

CREATE VIEW comedies AS
SELECT *
FROM films
WHERE kind = 'Comedy';

Compatibility

The SQL standard specifies some additional capabilities for the CREATE VIEW statement:

CREATE VIEW name [ ( column_name [, ...] ) ]
AS query
[ WITH [ CASCADED | LOCAL ] CHECK OPTION ]

The optional clauses for the full SQL command are:

CHECK OPTION

This option has to do with updatable views. All INSERT and UPDATE commands on the view will be checked to ensure data satisfy the view-defining condition (that is, the new data would be visible through the view). If they do not, the update will be rejected.
LOCAL

Check for integrity on this view.
CASCADED

Check for integrity on this view and on any dependent view. CASCADED is assumed if neither CASCADED nor LOCAL is specified.

CREATE OR REPLACE VIEW is a PostgreSQL language extension. So is the concept of a temporary view.

Why use stored procedures?

Stored procedures offer several distinct advantages over embedding queries in your Graphical User Interface (GUI). Your first thought may be: "Why tolerate the added development overhead?" After seeing the advantages, you may change your mind.

Advantage 1: Stored procedures are modular. This is a good thing from a maintenance standpoint. When query trouble arises in your application, you would likely agree that it is much easier to troubleshoot a stored procedure than an embedded query buried within many lines of GUI code.

Advantage 2: Stored procedures are tunable. By having procedures that handle the database work for your interface, you eliminate the need to modify the GUI source code to improve a query's performance. Changes can be made to the stored procedures--in terms of join methods, differing tables, etc.--that are transparent to the front-end interface.

Advantage 3: Stored procedures abstract or separate server-side functions from the client-side. It is much easier to code a GUI application to call a procedure than to build a query through the GUI code.

Advantage 4: Stored procedures are usually written by database developers/administrators. Persons holding these roles are usually more experienced in writing efficient queries and SQL statements. This frees the GUI application developers to utilize their skills on the functional and graphical presentation pieces of the application. If you have your people performing the tasks to which they are best suited, then you will ultimately produce a better overall application.

In short, queries are best handled via stored procedures. While the initial development overhead is greater, you will more than make up for the investment down the line.

Friday, December 7, 2007

PHP Vs Perl

1. The Language

If you are coming from a C, C++, Perl, Java or JavaScript background, learning PHP would probably be a piece of cake. In fact, you probably can get started writing your scripts almost immediately.

It uses typeless variables the way Perl does, prefixed with a "$" sign and holding any data type you wish. For example, $whatever can be a variable that you can use to contain strings, numbers, whatever. If $whatever contained a number, you can increment its value using

$whatever++ ;

or

$whatever += 1 ;

or

$whatever = $whatever + 1 ;

Doesn't it remind you of Perl, C, C++, Java, JavaScript? See what I mean?

2. Built-in Facilities

Unlike Perl, which is a general purpose scripting language that you can use for a wide variety of purposes (and not just generating web pages), PHP was designed from the ground up to be used for scripting web pages. As a result, it has lots of facilities built into that you may have to write yourself or use some pre-written module if you were using Perl.

For example, do you want to send email to yourself from a form on the web page? In Perl, one common way to do this is to use code like the following:

open ( MAIL,"|/usr/sbin/sendmail -t");
print MAIL "To: myself\@mydomain.com\n" ;
print MAIL "From: visitor\@hisdomain.com\n" ;
print MAIL "Subject: Comments from Web Form\n\n" ;
print MAIL $mainmessage ;
close ( MAIL ) ;

In PHP, the same thing would be coded as follows:

mail ( "myself@mydomain.com", "Comments from Web Form",
$mainmessage, "From: visitor@hisdomain.com" );

Nifty, huh? The same goes for other facilities like sending or retrieving a document via HTTP or FTP, etc. Since PHP was specially designed for a website, the facilities that web designers typically want in a scripting language are built into it.

Another convenience is its handling of form input. Take for example a form with a field like:

The data submitted for that field is made available to your script in the array variable $_REQUEST['dateofbirth']. You can assign its contents to any variable you like, or use it directly. There's no need to parse form inputs or the like. All fields in the form are automatically converted to variables that you can access.

Accessing databases is just as easy. There are built-in facilities in PHP to access MySQL, MSQL, Dbase, Oracle, InterBase, and so on (the list is very long). Need to MIME encode your message? There's a function to do it for you too.

There're many more features. I obviously can't run through the entire list - it would take a whole book to be exhaustive. This is just to whet your appetite.

3. Generating web pages

By default anything you type in your PHP document is given verbatim to the web browser. So a simple PHP script might look like the following:


My First PHP Script

My First PHP Script



Welcome, Internet user from IP address
. Hope you like my first
PHP page.


Notice that it looks exactly like a web page, except for the bit, which encloses the PHP script. In this case, all we want is for the script to output the visitor's IP address to the page, hence we use the "echo" function. The web server's environment variable REMOTE_ADDR is automatically made available to the PHP script via an array variable $_SERVER['REMOTE_ADDR']. In fact, all server environment variables are available to the PHP script in the $_SERVER array variable. So, for example, the name of your visitor's browser is available in $_SERVER['HTTP_USER_AGENT'].

There are many ways to embed your PHP script into your page, or to design your page itself. But you've probably already got the general idea. As I said, PHP was designed for web pages, so the idea of output to the server is built into its design. It makes writing such scripts a very pleasant task.

How to convert date to unixtime in perl (or vice versa)

  • time return number of seconds since 0 in your computer (1 jan 1970) on unix
  • localtime converts unixtime to normal dates
    To convert a specific date to its corresponding unixtime, you use Time::Local, the function looks like this:
      $time = timelocal($sec,$min,$hours,$mday,$mon,$year);
    so to convert 3rd of Sept 2000 to unixtime, (note that jan=0,feb=1,...):
      use Time::Local;
    $time = timelocal(0,0,0,'3','08','2000');
  •