Java

Java is a programming language originally developed by Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.

The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun made available most of their Java technologies as free software under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java and GNU Classpath.

History

Duke, the Java mascot
Main articles: Java (Sun)#History and Java version history

The Java language was created by James Gosling in June 1991 for use in one of his many set-top box projects.[5] The language was initially called Oak, after an oak tree that stood outside Gosling's office—and also went by the name Green—and ended up later being renamed to Java, from a list of random words.[6] Gosling's goals were to implement a virtual machine and a language that had a familiar C/C++ style of notation.[7] The first public implementation was Java 1.0 in 1995. It promised "Write Once, Run Anywhere" (WORA), providing no-cost runtimes on popular platforms. It was fairly secure and its security was configurable, allowing network and file access to be restricted. Major web browsers soon incorporated the ability to run secure Java applets within web pages. Java quickly became popular. With the advent of Java 2, new versions had multiple configurations built for different types of platforms. For example, J2EE was for enterprise applications and the greatly stripped down version J2ME was for mobile applications. J2SE was the designation for the Standard Edition. In 2006, for marketing purposes, new J2 versions were renamed Java EE, Java ME, and Java SE, respectively.

In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and later the Ecma International to formalize Java, but it soon withdrew from the process.[8][9][10] Java remains a de facto standard that is controlled through the Java Community Process.[11] At one time, Sun made most of its Java implementations available without charge although they were proprietary software. Sun's revenue from Java was generated by the selling of licenses for specialized products such as the Java Enterprise System. Sun distinguishes between its Software Development Kit (SDK) and Runtime Environment (JRE) that is a subset of the SDK, the primary distinction being that in the JRE, the compiler, utility programs, and many necessary header files are not present.

On 13 November 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL). On 8 May 2007 Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.[12]

[edit]
Philosophy

[edit]
Primary goals

There were five primary goals in the creation of the Java language:[13]
It should use the object-oriented programming methodology.
It should allow the same program to be executed on multiple operating systems.
It should contain built-in support for using computer networks.
It should be designed to execute code from remote sources securely.
It should be easy to use by selecting what were considered the good parts of other object-oriented languages.

[edit]
Platform independence
Main article: Java Platform

One characteristic, platform independence, means that programs written in the Java language must run similarly on any supported hardware/operating-system platform. One should be able to write a program once, compile it once, and run it anywhere.

This is achieved by most Java compilers by compiling the Java language code halfway (to Java bytecode) – simplified machine instructions specific to the Java platform. The code is then run on a virtual machine (VM), a program written in native code on the host hardware that interprets and executes generic Java bytecode. (In some JVM versions, bytecode can also be compiled to native code, either before or during program execution, resulting in faster execution.) Further, standardized libraries are provided to allow access to features of the host machines (such as graphics, threading and networking) in unified ways. Note that, although there is an explicit compiling stage, at some point, the Java bytecode is interpreted or converted to native machine code by the JIT compiler.

The first implementations of the language used an interpreted virtual machine to achieve portability. These implementations produced programs that ran slower than programs compiled to native executables, for instance written in C or C++, so the language suffered a reputation for poor performance. More recent JVM implementations produce programs that run significantly faster than before, using multiple techniques.

One technique, known as just-in-time compilation (JIT), translates the Java bytecode into native code at the time that the program is run, which results in a program that executes faster than interpreted code but also incurs compilation overhead during execution. More sophisticated VMs use dynamic recompilation, in which the VM can analyze the behavior of the running program and selectively recompile and optimize critical parts of the program. Dynamic recompilation can achieve optimizations superior to static compilation because the dynamic compiler can base optimizations on knowledge about the runtime environment and the set of loaded classes, and can identify the hot spots (parts of the program, often inner loops, that take up the most execution time). JIT compilation and dynamic recompilation allow Java programs to take advantage of the speed of native code without losing portability.

Another technique, commonly known as static compilation, is to compile directly into native code like a more traditional compiler. Static Java compilers, such as GCJ, translate the Java language code to native object code, removing the intermediate bytecode stage. This achieves good performance compared to interpretation, but at the expense of portability; the output of these compilers can only be run on a single architecture. Some see avoiding the VM in this manner as defeating the point of developing in Java; however it can be useful to provide both a generic bytecode version, as well as an optimized native code version of an application.

[edit]
Implementations

Sun Microsystems officially licenses the Java Standard Edition platform for Microsoft Windows, Linux, and Solaris. Through a network of third-party vendors and licensees[14], alternative Java environments are available for these and other platforms.

Sun's trademark license for usage of the Java brand insists that all implementations be "compatible". This resulted in a legal dispute with Microsoft after Sun claimed that the Microsoft implementation did not support the RMI and JNI interfaces and had added platform-specific features of their own. Sun sued in 1997, and in 2001 won a settlement of $20 million as well as a court order enforcing the terms of the license from Sun.[15] As a result, Microsoft no longer ships Java with Windows, and in recent versions of Windows, Internet Explorer cannot support Java applets without a third-party plugin. However, Sun and others have made available Java run-time systems at no cost for those and other versions of Windows.

Platform-independent Java is essential to the Java Enterprise Edition strategy, and an even more rigorous validation is required to certify an implementation. This environment enables portable server-side applications, such as Web services, servlets, and Enterprise JavaBeans, as well as with Embedded systems based on OSGi, using Embedded Java environments. Through the new GlassFish project, Sun is working to create a fully functional, unified open-source implementation of the Java EE technologies.

[edit]
Automatic memory management
See also: Garbage collection (computer science)

One of the ideas behind Java's automatic memory management model is that programmers be spared the burden of having to perform manual memory management. In some languages the programmer allocates memory for the creation of objects stored on the heap and the responsibility of later deallocating that memory also resides with the programmer. If the programmer forgets to deallocate memory or writes code that fails to do so, a memory leak occurs and the program can consume an arbitrarily large amount of memory. Additionally, if the program attempts to deallocate the region of memory more than once, the result is undefined and the program may become unstable and may crash. Finally, in non garbage collected environments, there is a certain degree of overhead and complexity of user-code to track and finalize allocations. Often developers may box themselves into certain designs to provide reasonable assurances that memory leaks will not occur.[16]

In Java, this potential problem is avoided by automatic garbage collection. The programmer determines when objects are created, and the Java runtime is responsible for managing the object's lifecycle. The program or other objects can reference an object by holding a reference to it (which, from a low-level point of view, is its address on the heap). When no references to an object remain, the unreachable object is eligible for release by the Java garbage collector - it may be freed automatically by the garbage collector at any time. Memory leaks may still occur if a programmer's code holds a reference to an object that is no longer needed—in other words, they can still occur but at higher conceptual levels.

The use of garbage collection in a language can also affect programming paradigms. If, for example, the developer assumes that the cost of memory allocation/recollection is low, they may choose to more freely construct objects instead of pre-initializing, holding and reusing them. With the small cost of potential performance penalties (inner-loop construction of large/complex objects), this facilitates thread-isolation (no need to synchronize as different threads work on different object instances) and data-hiding. The use of transient immutable value-objects minimizes side-effect programming.

Comparing Java and C++, it is possible in C++ to implement similar functionality (for example, a memory management model for specific classes can be designed in C++ to improve speed and lower memory fragmentation considerably), with the possible cost of adding comparable runtime overhead to that of Java's garbage collector, and of added development time and application complexity if one favors manual implementation over using an existing third-party library. In Java, garbage collection is built-in and virtually invisible to the developer. That is, developers may have no notion of when garbage collection will take place as it may not necessarily correlate with any actions being explicitly performed by the code they write. Depending on intended application, this can be beneficial or disadvantageous: the programmer is freed from performing low-level tasks, but at the same time loses the option of writing lower level code. Additionally, the garbage collection capability demands some attention to tuning the JVM, as large heaps will cause apparently random stalls in performance.

Java does not support pointer arithmetic as is supported in, for example, C++. This is because the garbage collector may relocate referenced objects, invalidating such pointers. Another reason that Java forbids this is that type safety and security can no longer be guaranteed if arbitrary manipulation of pointers is allowed.

Java Server Pages(JSP)

JavaServer Pages (JSP) is a Java technology that allows software developers to dynamically generate HTML, XML or other types of documents in response to a Web client request. The technology allows Java code and certain pre-defined actions to be embedded into static content.

The JSP syntax adds additional XML-like tags, called JSP actions, to be used to invoke built-in functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as extensions to the standard HTML or XML tags. Tag libraries provide a platform independent way of extending the capabilities of a Web server.

JSPs are compiled into Java Servlets by a JSP compiler. A JSP compiler may generate a servlet in Java code that is then compiled by the Java compiler, or it may generate byte code for the servlet directly. JSPs can also be interpreted on-the-fly reducing the time taken to reload changes.

JSP and Servlets

Architecturally, JSP may be viewed as a high-level abstraction of servlets that is implemented as an extension of the Servlet 2.1 API. Both servlets and JSPs were originally developed at Sun Microsystems. Starting with version 1.2 of the JSP specification, JavaServer Pages have been developed under the Java Community Process. JSR 53 defines both the JSP 1.2 and Servlet 2.3 specifications and JSR 152 defines the JSP 2.0 specification. As of May 2006 the JSP 2.1 specification has been released under JSR 245 as part of Java EE 5.

[edit]
JSP syntax

A JavaServer Page may be broken down into the following pieces:
static data such as HTML
JSP directives such as the include directive
JSP scripting elements and variables
JSP actions
custom tags with correct library

JSP directives control how the JSP compiler generates the servlet. The following directives are available:
include
The include directive informs the JSP compiler to include a complete file into the current file. It is as if the contents of the included file were pasted directly into the original file. This functionality is similar to the one provided by the C preprocessor. Included files generally have the extension "jspf" (for JSP Fragment):
<%@ include file="somefile.jspf" %>
page
There are several options to the page directive.
import
Results in a Java import statement being inserted into the resulting file.
contentType
specifies the content that is generated. This should be used if HTML is not used or if the character set is not the default character set.
errorPage
Indicates the page that will be shown if an exception occurs while processing the HTTP request.
isErrorPage
If set to true, it indicates that this is the error page. Default value is false.
isThreadSafe
Indicates if the resulting servlet is thread safe.
autoFlush
To autoflush the contents.A value of true, the default, indicates that the buffer should be flushed when it is full. A value of false, rarely used, indicates that an exception should be thrown when the buffer overflows. A value of false is illegal when also using buffer="none".
session
To maintain session. A value of true (the default) indicates that the predefined variable session (of type HttpSession) should be bound to the existing session if one exists, otherwise a new session should be created and bound to it. A value of false indicates that no sessions will be used, and attempts to access the variable session will result in errors at the time the JSP page is translated into a servlet.
buffer
To set Buffer Size. The default is 8k and it is advisable that you increase it.
isELIgnored
Defines whether EL expressions are ignored when the JSP is translated.
language
Defines the scripting language used in scriptlets, expressions and declarations. Right now, the only possible value is "java".
extends
Defines the superclass of the class this JSP will become. You won't use this unless you REALLY know what you're doing - it overrides the class hierarchy provided by the Container.
info
Defines a String that gets put into the translated page, just so that you can get it using the generated servlet's inherited getServletInfo() method.
pageEncoding
Defines the character encoding for the JSP. The default is "ISO-8859-1"(unless the contentType attribute already defines a character encoding, or the page uses XML document syntax).
<%@ page import="java.util.*" %> <%-- example import --%>
<%@ page contentType="text/html" %> <%-- example contentType --%>
<%@ page isErrorPage="false" %> <%-- example for non error page --%>
<%@ page isThreadSafe="true" %> <%-- example for a thread safe JSP --%>
<%@ page session="true" %> <%-- example for using session binding --%>
<%@ page autoFlush="true" %> <%-- example for setting autoFlush --%>
<%@ page buffer="20kb" %> <%-- example for setting Buffer Size --%>
Note: Only the "import" page directive can be used multiple times in the same JSP.
taglib
The taglib directive indicates that a JSP tag library is to be used. The directive requires that a prefix be specified (much like a namespace in C++) and the URI for the tag library description.
<%@ taglib prefix="myprefix" uri="taglib/mytag.tld" %>

[edit]
JSP scripting elements and objects

[edit]
JSP implicit objects

The following JSP implicit objects are exposed by the JSP container and can be referenced by the programmer:
out
The JspWriter used to write the data to the response stream(output page).
page
The servlet itself.
pageContext
A PageContext instance that contains data associated with the whole page. A given HTML page may be passed among multiple JSPs.
request
The HttpServletRequest object that provides HTTP request information.
response
The HttpServletResponse object that can be used to send data back to the client.
session
The HttpSession object that can be used to track information about a user from one request to another.
config
Provides servlet configuration data.
application
Data shared by all JSPs and servlets in the application.
exception
Exceptions not caught by application code .

[edit]
Scripting elements

There are three basic kinds of scripting elements that allow java code to be inserted directly into the servlet.
A declaration tag places a variable definition inside the body of the java servlet class. Static data members may be defined as well. Also inner classes should be defined here.
<%! int serverInstanceVariable = 1; %>

Java Servlets

The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as PHP, CGI and ASP.NET. Servlets can maintain state across many server transactions by using HTTP cookies, session variables or URL rewriting.

The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of a Web container and a servlet. A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

A Servlet is an object that receives a request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the Web server and a client. Servlets may be packaged in a WAR file as a Web application.

Servlets can be generated automatically by JavaServer Pages (JSP) compiler, or alternately by template engines such as WebMacro. Often servlets are used in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model-view-controller pattern.


Lifecycle of a Servlet

The Servlet lifecycle consists of the following steps:
The Servlet class is loaded by the container during start-up.
The container calls the init() method. This method initializes the servlet and must be called before the servlet can service any requests. In the entire life of a servlet, the init() method is called only once.
After initialization, the servlet can service client-requests. Each request is serviced in its own separate thread. The container calls the service() method of the servlet for every request. The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester.
Finally, the container calls the destroy() method which takes the servlet out of service. The destroy() method like init() is called only once in the lifecycle of a Servlet.

[edit]
ServletConfig and ServletContext

There is only one ServletContext in every application. This object can be used by all the servlets to obtain application level information or container details. Every servlet, on the other hand, gets its own ServletConfig object. This object provides initialization parameters for a servlet. A developer can obtain the reference to ServletContext using either the ServletConfig object or ServletRequest object...

[edit]
Servlet containers
See also: List of Servlet containers

A Servlet container is a specialized web server that supports Servlet execution. It combines the basic functionality of a web server with certain Java/Servlet specific optimizations and extensions – such as an integrated Java runtime environment, and the ability to automatically translate specific URLs into Servlet requests. Individual Servlets are registered with a Servlet container, providing the container with information about what functionality they provide, and what URL or other resource locator they will use to identify themselves. The Servlet container is then able to initialize the Servlet as necessary and deliver requests to the Servlet as they arrive. Many containers have the ability to dynamically add and remove Servlets from the system, allowing new Servlets to quickly be deployed or removed without affecting other Servlets running from the same container. Servlet containers are also referred to as web containers or web engines.

Like the other Java APIs, different vendors provide their own implementation of the Servlet container standard. For a list of some of the free and commercial web containers, see the list of Servlet containers. (Note that 'free' means that non-commercial use is free. Some of the commercial containers, e.g. Resin and Orion, are free to use in a server environment for non-profit organizations).

PHP

PHP is a computer scripting language originally designed for producing dynamic web pages. It is for server-side scripting, but can be used from a command line interface or in standalone graphical applications.[2]

While PHP was originally created by Rasmus Lerdorf in 1995, the main implementation of PHP is now produced by The PHP Group and serves as the de facto standard for PHP as there is no formal specification.[3] Released under the PHP License, the Free Software Foundation considers it to be free software.[4]

PHP is a widely used general-purpose scripting language that is especially suited for web development and can be embedded into HTML. It generally runs on a web server, taking PHP code as its input and creating web pages as output. It can be deployed on most web servers and on almost every operating system and platform free of charge.[5] PHP is installed on more than 20 million websites and 1 million web servers.[6] It is also the most popular Apache module among computers using Apache as a web server.[7] The most recent major release of PHP was version 5.2.6 on May 1, 2008.[8]

PHP originally stood for Personal Home Page.[9] It began in 1994 as a set of Common Gateway Interface binaries written in the C programming language by the Danish/Greenlandic programmer Rasmus Lerdorf. Lerdorf initially created these Personal Home Page Tools to replace a small set of Perl scripts he had been using to maintain his personal homepage. The tools were used to perform tasks such as displaying his résumé and recording how much traffic his page was receiving.[3] He combined these binaries with his Form Interpreter to create PHP/FI, which had more functionality. PHP/FI included a larger implementation for the C programming language and could communicate with databases, enabling the building of simple, dynamic web applications. Lerdorf released PHP publicly on June 8, 1995 to accelerate bug location and improving the code.[10] This release was named PHP version 2 and already had the basic functionality that PHP has today. This included Perl-like variables, form handling, and the ability to embed HTML. The syntax was similar to Perl but was more limited, simpler, and less consistent.[3]

Zeev Suraski and Andi Gutmans, two Israeli developers at the Technion IIT, rewrote the parser in 1997 and formed the base of PHP 3, changing the language's name to the recursive initialism PHP: Hypertext Preprocessor.[3] The development team officially released PHP/FI 2 in November 1997 after months of beta testing. Afterwards, public testing of PHP 3 began, and the official launch came in June 1998. Suraski and Gutmans then started a new rewrite of PHP's core, producing the Zend Engine in 1999.[11] They also founded Zend Technologies in Ramat Gan, Israel, which manages the development of PHP.[3]

On May 22, 2000, PHP 4, powered by the Zend Engine 1.0, was released.[3] On July 13, 2004, PHP 5 was released, powered by the new Zend Engine II.[3] PHP 5 included new features such as improved support for object-oriented programming, the PHP Data Objects extension (which defines a lightweight and consistent interface for accessing databases), and numerous performance enhancements.[12] The most recent update released by The PHP Group is for the older PHP version 4 code branch. As of August 2008, this branch is up to version 4.4.9. PHP 4 is no longer under active development but will be supported by security updates until August 8, 2008.[13][14]

In 2008, PHP 5 became the only stable version under development. Late static binding has been missing from PHP and will be added in version 5.3.[15][16] Alongside PHP 5, PHP 6 is also under active development. Major changes include the removal of register_globals,[17] magic quotes, and safe mode.[13][18]

PHP does not have complete native support for Unicode or multibyte strings;[19] unicode support will be included in PHP 6.[20] Many high profile open source projects ceased to support PHP 4 in new code as of February 5, 2008, due to the GoPHP5 initiative, provided by a consortium of PHP developers promoting the transition from PHP 4 to PHP 5.[21][22]

It runs in both 32-bit and 64-bit environments, but on Windows the only official distribution is 32-bit, requiring Windows 32-bit compatibility mode to be enabled while using IIS in a 64-bit Windows environment. There is a third-party distribution[23] available for 64-bit Windows.

Syntax
Main article: PHP syntax and semantics

Syntax-highlighted PHP code

Variables are prefixed with a dollar symbol and a type does not need to be specified in advance. Unlike function and class names, variable names are case sensitive. Both double-quoted ("") and heredoc strings allow the ability to embed a variable's value into the string.[47] PHP treats newlines as whitespace in the manner of a free-form language (except when inside string quotes), and statements are terminated by a semicolon.[48] PHP has three types of comment syntax: /* */ serves as block comments, and // as well as # are used for inline comments.[49] The echo statement is one of several facilities PHP provides to output text (e.g. to a web browser).


Data types

PHP stores whole numbers in a platform-dependent range. This range is typically that of 32-bit signed integers. Unsigned integers are converted to signed values in certain situations; this behavior is different from other programming languages.[50] Integer variables can be assigned using decimal (positive and negative), octal, and hexadecimal notations. Real numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation.[51] PHP has a native Boolean type that is similar to the native Boolean types in Java and C++. Using the Boolean type conversion rules, non-zero values are interpreted as true and zero as false, as in Perl and C++.[51] The null data type represents a variable that has no value. The only value in the null data type is NULL.[51] Variables of the "resource" type represent references to resources from external sources. These are typically created by functions from a particular extension, and can only be processed by functions from the same extension; examples include file, image, and database resources.[51] Arrays can contain elements of any type that PHP can handle, including resources, objects, and even other arrays. Order is preserved in lists of values and in hashes with both keys and values, and the two can be intermingled.[51] PHP also supports strings, which can be used with single quotes, double quotes, or heredoc syntax.[52]

Perl

In computer programming, Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall, a linguist working as a systems administrator for NASA, in 1987, as a general purpose Unix scripting language to make report processing easier.[1][2] Since then, it has undergone many changes and revisions and became widely popular among programmers. Larry Wall continues to oversee development of the core language, and its newest version, Perl 6.

Perl borrows features from other programming languages including C, shell scripting (sh), AWK, sed and Lisp.[3] The language provides powerful text processing facilities without arbitrary data length limits, like the many Unix tools present at the time, [4] making it the ideal language for manipulating text files. It is also used for graphics programming, system administration, network programming, applications that require database access and CGI programming on the Web. Perl is nicknamed as the Swiss Army chainsaw of the programming languages because of its flexibility and adaptability.[5]

Overview

Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more.

The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal).[16] Its major features include support for multiple programming paradigms (procedural, object-oriented, and functional styles), reference counting memory management (without a cycle-detecting garbage collector), built-in support for text processing, and a large collection of third-party modules.

According to Larry Wall, Perl has two slogans. The first is "There's more than one way to do it", commonly known as TMTOWTDI and the second is "Easy things should be easy and hard things should be possible".[17]

[edit]
Features

The overall structure of Perl derives broadly from C. Perl is procedural in nature, with variables, expressions, assignment statements, brace-delimited code blocks, control structures, and subroutines.

Perl also takes features from shell programming. All variables are marked with leading sigils, which unambiguously identify the data type (scalar, array, hash, etc.) of the variable in context. Importantly, sigils allow variables to be interpolated directly into strings. Perl has many built-in functions which provide tools often used in shell programming (though many of these tools are implemented by programs external to the shell) like sorting, and calling on system facilities.

Perl takes lists from Lisp, associative arrays (hashes) from AWK, and regular expressions from sed. These simplify and facilitate many parsing, text handling, and data management tasks.

In Perl 5, features were added that support complex data structures, first-class functions (i.e., closures as values), and an object-oriented programming model. These include references, packages, class-based method dispatch, and lexically scoped variables, along with compiler directives (for example, the strict pragma). A major additional feature introduced with Perl 5 was the ability to package code as reusable modules. Larry Wall later stated that "The whole intent of Perl 5's module system was to encourage the growth of Perl culture rather than the Perl core."[18]

All versions of Perl do automatic data typing and memory management. The interpreter knows the type and storage requirements of every data object in the program; it allocates and frees storage for them as necessary using reference counting (so it cannot deallocate circular data structures without manual intervention). Legal type conversions—for example, conversions from number to string—are done automatically at run time; illegal type conversions are fatal errors.

Language structure

In Perl, the minimal Hello world program may be written as follows:
print "Hello, world!\n"

This prints the string Hello, world! and a newline, symbolically expressed by an n character whose interpretation is altered by the preceding escape character (a backslash).

The canonical form of the program is slightly more verbose:
#!/usr/bin/perl
print "Hello, world!\n";

The hash mark character introduces a comment in Perl, which runs up to the end of the line of code and is ignored by the compiler. The comment used here is of a special kind: it’s called the shebang line. This tells Unix-like operating systems where to find the Perl interpreter, making it possible to invoke the program without explicitly mentioning perl. (Note that on Microsoft Windows systems, Perl programs are typically invoked by associating the .pl extension with the Perl interpreter. In order to deal with such circumstances, perl detects the shebang line and parses it for switches,[24] so it is not strictly true that the shebang line is ignored by the compiler.)

The second line in the canonical form includes a semicolon, which is used to separate statements in Perl. With only a single statement in a block or file, a separator is unnecessary, so it can be omitted from the minimal form of the program—or more generally from the final statement in any block or file. The canonical form includes it because it is common to terminate every statement even when it is unnecessary to do so, as this makes editing easier: code can be added to or moved away from the end of a block or file without having to adjust semicolons.

Version 5.10 of Perl introduces a say function that implicitly appends a newline character to its output, making the minimal "Hello world" program even shorter:
say 'Hello, world!'

[edit]
Data types

Perl has a number of fundamental data types, the most commonly used and discussed being: scalars, arrays, hashes, filehandles and subroutines:
A scalar is a single value; it may be a number, a string or a reference
An array is an ordered collection of scalars
A hash, or associative array, is a map from strings to scalars; the strings are called keys and the scalars are called values.
A file handle is a map to a file, device, or pipe which is open for reading, writing, or both.
A subroutine is a piece of code that may be passed arguments, be executed, and return data

Most variables are marked by a leading sigil, which identifies the data type being accessed (not the type of the variable itself), except filehandles, which don't have a sigil. The same name may be used for variables of different data types, without conflict.
$foo # a scalar
@foo # an array
%foo # a hash
FOO # a file handle
&FOO # a constant (but the & is optional)
&foo # a subroutine (but the & is optional)

File handles and constants need not be uppercase, but it is a common convention owing to the fact that there is no sigil to denote them. Both are global in scope, but file handles are interchangeable with references to file handles, which can be stored in scalars, which in turn permit lexical scoping. Doing so is encouraged in Damian Conway's Perl Best Practices. As a convenience, the open function in Perl 5.6 and newer will autovivify undefined scalars to file handle references.

Numbers are written in the bare form; strings are enclosed by quotes of various kinds.
$name = "joe";
$color = 'red';

$number1 = 42;
$number2 = '42';

# This evaluates to true
if ($number1 == $number2) { print "Numbers and strings of numbers are the same!"; }

$answer = "The answer is $number1"; # Variable interpolation: The answer is 42
$price = 'This device costs $42'; # No interpolation in single quotes

$album = "It's David Bowie's \"Heroes\""; # literal quotes inside a string;
$album = 'It\'s David Bowie\'s "Heroes"'; # same as above with single quotes;
$album = q(It's David Bowie's "Heroes"); # the quote-like operators q() and qq() allow
# almost any delimiter instead of quotes, to
# avoid excessive backslashing

$multilined_string =<This is my multilined string
note that I am terminating it with the "EOF" word.
EOF

Perl will convert strings into numbers and vice versa depending on the context in which they are used. In the following example the strings $n and $m are treated as numbers when they are the arguments to the addition operator. This code prints the number '5', discarding non numeric information for the operation, although the variable values remain the same. (The string concatenation operator is the period, not the + symbol.)
$n = '3 apples';
$m = '2 oranges';
print $n + $m;

Perl also has a boolean context that it uses in evaluating conditional statements. The following values all evaluate as false in Perl:
$false = 0; # the number zero
$false = 0.0; # the number zero as a float
$false = 0b0; # the number zero in binary
$false = 0x0; # the number zero in hexadecimal
$false = '0'; # the string zero
$false = ""; # the empty string
$false = undef; # the return value from undef

All other values are evaluated to true. This includes the odd self-describing literal string of "0 but true", which in fact is 0 as a number, but true when used as a boolean. (Any non-numeric string would also have this property, but this particular string is ignored by Perl with respect to numeric warnings.) A less explicit but more conceptually portable version of this string is '0E0' or '0e0', which does not rely on characters being evaluated as 0, as '0E0' is literally "zero times ten to the zeroth power."

Evaluated boolean expressions also return scalar values. Although the documentation does not promise which particular true or false is returned (and thus cannot be relied on), many boolean operators return 1 for true and the empty-string for false (which evaluates to zero in a numeric context). The defined() function tells if the variable has any value set. In the above examples defined($false) is true for every value except undef.

If a specifically 1 or 0 result (as in C) is needed, an explicit conversion is thought by some authors to be required:
my $real_result = $boolean_result ? 1 : 0;

However, if it's known that the value is either 1 or undef, an implicit conversion can be used instead:
my $real_result = $boolean_result + 0;

A list is written by listing its elements, separated by commas, and enclosed by parentheses where required by operator precedence.
@scores = (32, 45, 16, 5);

It can be written many other ways as well, some straightforward and some less so:
# An explicit and straightforward way
@scores = ('32', '45', '16', '5');

# Equivalent to the above, but the qw() quote-like operator saves typing of
# quotes and commas and reduces visual clutter; almost any delimiter can be
# used instead of parentheses
@scores = qw(32 45 16 5);

# The split function returns a list of strings, which are extracted
# from the expression using a regex template.
# This may be useful for reading from a file of comma-separated values (CSV)
@scores = split /,/, '32,45,16,5';

# It's also possible to use a postfix for operator and aliasing of
# the $_ magic variable to the next value of the list during each
# iteration; this is pointless here, but similar idioms are widely used
# in some circumstances.
push @scores, $_ foreach 32, 45, 16, 5;

A hash may be initialized from a list of key/value pairs:
%favorite = (
joe => 'red',
sam => 'blue'
);

The => operator is equivalent to a comma, except that it assumes quotes around the preceding token if it is a bare identifier: (joe => 'red') is the same as ('joe' => 'red'). It can therefore be used to elide quote marks, improving readability.

Individual elements of a list are accessed by providing a numerical index, in square brackets. Individual values in a hash are accessed by providing the corresponding key, in curly braces. The $ sigil identifies the accessed element as a scalar.
$scores[2] # an element of @scores
$favorite{joe} # a value in %favorite

Thus, a hash can also be specified by setting its keys individually:
$favorite{joe} = 'red';
$favorite{sam} = 'blue';

Multiple elements may be accessed by using the @ sigil instead (identifying the result as a list).
@scores[2, 3, 1] # three elements of @scores
@favorite{'joe', 'sam'} # two values in %favorite
@favorite{qw(joe sam)} # same as above

The number of elements in an array can be obtained by evaluating the array in scalar context or with the help of the $# sigil. The latter gives the index of the last element in the array, not the number of elements. Note: the syntax highlighting in Wikipedia's software mistakenly considers some of the following code to be part of the comments.
$count = @friends; # Assigning to a scalar forces scalar context

$#friends; # The index of the last element in @friends
$#friends+1; # Usually the number of elements in @friends is one more
# than $#friends because the first element is at index 0,
# not 1, unless the programmer reset this to a different
# value, which most Perl manuals discourage.

There are a few functions that operate on entire hashes.
@names = keys %addressbook;
@addresses = values %addressbook;

# Every call to each returns the next key/value pair.
# All values will be eventually returned, but their order
# cannot be predicted.
while (($name, $address) = each %addressbook) {
print "$name lives at $address\n";
}

# Similar to the above, but sorted alphabetically
foreach my $next_name (sort keys %addressbook) {
print "$next_name lives at $addressbook{$next_name}\n";
}

ServerSide Scripting Languages

Server-side scripting is a web server technology in which a user's request is fulfilled by running a script directly on the web server to generate dynamic HTML pages. It is usually used to provide interactive web sites, that interface to databases or other data stores. This is different from client-side scripting where scripts are run by the viewing web browser, usually in JavaScript. The primary advantage to server-side scripting is the ability to highly customize the response based on the user's requirements, access rights, or queries into data stores.

When the server serves data in a commonly used manner, for example according to the HTTP or FTP protocols, users may have their choice of a number of client programs (most modern web browsers can request and receive data using both of those protocols). In the case of more specialized applications, programmers may write their own server, client, and communications protocol, that can only be used with one another.

Programs that run on a user's local computer without ever sending or receiving data over a network are not considered clients, and so the operations of such programs would not be considered client-side operations.

Explanation

In the "old" days of the web, server-side scripting was almost exclusively performed by using a combination of C programs, Perl scripts and shell scripts using the Common Gateway Interface (CGI). Those scripts were executed by the operating system, mnemonic coding and the results simply served back by the web server. Nowadays, these and other on-line scripting languages such as ASP and PHP can often be executed directly by the web server itself or by extension modules (e.g. mod perl or mod php) to the web server. Either form of scripting (i.e., CGI or direct execution) can be used to build up complex multi-page sites, but direct execution usually results in lower overhead due to the lack of calls to external interpreters.

Dynamic websites are also sometimes powered by custom web application servers, for example the Python "Base HTTP Server" library, although some may not consider this to be server-side scripting.


Dynamic web page production

The production of server-side dynamic web pages is one of the main applications of server-side scripting languages.

One important alternative to use them, on a MVC framework, is using web template systems. Any "not web specific" programming language can be used to manage template engines and web templates.

VBScript

VBScript (short for Visual Basic Scripting Edition) is an Active Scripting language developed by Microsoft. The language's syntax reflects its history as a limited variation of Microsoft's Visual Basic programming language. VBScript is installed by default in every desktop release of the Windows Operating System (OS) since Windows 98[1] and may or may not be included with Windows CE depending on the configuration and purpose of the device it is running on. It initially gained support from Windows administrators seeking an automation tool more powerful than the batch language first developed in the late 1970s. A VBScript script must be executed within a host environment, of which there are several provided on a standard install of Microsoft Windows (Windows Script Host, Windows Internet Explorer). Additionally, The VBScript hosting environment is embeddable in other programs, through technologies such as the Microsoft Script control (msscript.ocx).


History

VBScript began as part of the Microsoft Windows Script Technologies, which were targeted at web developers initially and were launched in 1996. During a period of just over two years, the VBScript and JScript languages advanced from version 1.0 to 2.0 (the latter was later renamed 5.0) and over that time system administrators noticed it and began using it. In version 5.0, the functionality of VBScript was increased with new features such as regular expressions, classes, the With statement,[2] Eval/Execute/ExecuteGlobal functions to evaluate and execute script commands built during the execution of another script, a function-pointer system via GetRef(), and Distributed COM (DCOM) support.

In 5.5, "Submatches"[3] were added to the regular expression class in VBScript to finally allow VBScript script authors to capture the text within the expression's groups. That capability before was only possible through the JScript member of the Microsoft ActiveX Scripting family.

As of 2007, no new functionality will be added to the VBScript language, which has been superseded by Windows Powershell. However, it will continue to be shipped with future releases of Microsoft Windows, as will other components of the ActiveX Scripting Family (such as JScript). Additionally, support will continue due to the amount of code written in it and because it is still considered a useful tool for some tasks.

The language engine is currently being maintained by Microsoft's Sustaining Engineering Team, which is responsible for bug fixes and security enhancements.





Functionality

As-is, VBScript provides functions and sub-routines, basic date/time, string manipulation, math, user interaction, error handling, and regular expressions. Additional functionality can be added through the use of ActiveX technologies. File system management, file modification, and streaming text operations can be achieved with the Scripting Runtime Library scrrun.dll. Binary file and memory I/O is provided by the "ADODB.Stream" class, which can also be used as a string builder (since a high amount of VBScript string concatenation is costly due to constant memory re-allocation), and can be used to convert an array of bytes to a string and vice versa. Database access is made possible through ActiveX Data Objects (ADO), and the IIS Metabase can be manipulated using the GetObject() function with sufficient permissions (useful for creating and destroying sites and virtual directories). Additionally, XML files and schemas can be manipulated with the Microsoft XML Library Application Programming Interfaces (msxml6.dll, msxml3.dll), which also can be used to retrieve content from the World Wide Web via the XMLHTTP and ServerXMLHTTP objects (class strings "MSXML2.XMLHTTP.6.0" and "MSXML2.ServerXMLHTTP.6.0").

JavaScript

JavaScript is a scripting language most often used for client-side web development. It was the originating dialect of the ECMAScript standard. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript was influenced by many languages and was designed to look like Java, but be easier for non-programmers to work with.[1][2]

Although best known for its use in websites (as client-side JavaScript), JavaScript is also used to enable scripting access to objects embedded in other applications (see below).

JavaScript, despite the name, is essentially unrelated to the Java programming language, although both have the common C syntax, and JavaScript copies many Java names and naming conventions. The language was originally named "LiveScript" but was renamed in a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. The key design principles within JavaScript are inherited from the Self programming language.

"JavaScript" is a trademark of Sun Microsystems. It was used under license for technology invented and implemented by Netscape Communications and current entities such as the Mozilla Foundation.[3]






History and naming

Some JavaScript source code

JavaScript was originally developed by Brendan Eich of Netscape under the name Mocha, which was later renamed to LiveScript, and finally to JavaScript. The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. JavaScript was first introduced and deployed in the Netscape browser version 2.0B3 in December 1995. The naming has caused confusion, giving the impression that the language is a spin-off of Java, and it has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language.[4][5]

Microsoft named its dialect of the language JScript to avoid trademark issues. JScript was first supported in Internet Explorer version 3.0, released in August 1996, and it included Y2K compliant date functions, unlike those based on java.util.Date in JavaScript at the time. The dialects are perceived to be so similar that the terms "JavaScript" and "JScript" are often used interchangeably (including in this article). Microsoft, however, notes dozens of ways in which JScript is not ECMA compliant.

Netscape submitted JavaScript to Ecma International for standardization resulting in the standardized version named ECMAScript.[6]



Features

[edit]
Structured programming

JavaScript supports all the structured programming syntax in C (e.g., if statements, while loops, switch statements, etc.). One partial exception is scoping: C-style block-level scoping is not supported. However, JavaScript 1.7 supports block-level scoping with the let keyword. Like C, JavaScript makes a distinction between expressions and statements.

[edit]
Dynamic programming
dynamic typing
As in most scripting languages, types are associated with values, not variables. For example, a variable x could be bound to a number, then later rebound to a string. JavaScript supports various ways to test the type of an object, including duck typing.[7]
objects as associative arrays
JavaScript is heavily object-based. Objects are associative arrays, augmented with prototypes (see below). Object property names are associative array keys: obj.x = 10 and obj["x"] = 10 are equivalent, the dot notation being merely syntactic sugar. Properties and their values can be added, changed, or deleted at run-time. The properties of an object can also be enumerated via a for...in loop.
run-time evaluation
JavaScript includes an eval function that can execute statements provided as strings at run-time.

[edit]
Function-level programming
first-class functions
Functions are first-class; they are objects themselves. As such, they have properties and can be passed around and interacted with like any other object.
inner functions and closures
Inner functions (functions defined within other functions) are created each time the outer function is invoked, and variables of the outer functions for that invocation continue to exist as long as the inner functions still exist, even after that invocation is finished (e.g. if the inner function was returned, it still has access to the outer function's variables) — this is the mechanism behind closures within JavaScript.

[edit]
Prototype-based
prototypes
JavaScript uses prototypes instead of classes for defining object properties, including methods, and inheritance. It is possible to simulate many class-based features with prototypes in JavaScript.
functions as object constructors
Functions double as object constructors along with their typical role. Prefixing a function call with new creates a new object and calls that function with its local this keyword bound to that object for that invocation. The function's prototype property determines the new object's prototype.
functions as methods
Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; a function can be called as a method. When a function is invoked as a method of an object, the function's local this keyword is bound to that object for that invocation.

[edit]
Others
run-time environment
JavaScript typically relies on a run-time environment (e.g. in a web browser) to provide objects and methods by which scripts can interact with "the outside world". (This is not a language feature per se, but it is common in most JavaScript implementations.)
variadic functions
An indefinite number of parameters can be passed to a function. The function can both access them through formal parameters and the local arguments object.
array and object literals
Like many scripting languages, arrays and objects (associative arrays in other languages) can be created with a succinct shortcut syntax. The object literal in particular is the basis of the JSON data format.
regular expressions
JavaScript also supports regular expressions in a manner similar to Perl, which provide a concise and powerful syntax for text manipulation that is more sophisticated than the built-in string functions.


Syntax
Main article: JavaScript syntax

As of 2008, the latest version of the language is JavaScript 1.8. It is a superset of ECMAScript (ECMA-262) Edition 3. Extensions to the language, including partial E4X (ECMA-357) support and experimental features considered for inclusion into ECMAScript Edition 4, are documented here.

client side scripting languages

Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side (on the web server). This type of computer programming is an important part of the Dynamic HTML (DHTML) concept, enabling web pages to be scripted; that is, to have different and changing content depending on user input, environmental conditions (such as the time of day), or other variables.

Web authors write client-side scripts in languages such as JavaScript (Client-side JavaScript) and VBScript.

Client-side scripts are often embedded within an HTML document, but they may also be contained in a separate file, which is referenced by the document (or documents) that use it. Upon request, the necessary files are sent to the user's computer by the web server (or servers) on which they reside. The user's web browser executes the script, then displays the document, including any visible output from the script. Client-side scripts may also contain instructions for the browser to follow if the user interacts with the document in a certain way, e.g., clicks a certain button. These instructions can be followed without further communication with the server, though they may require such communication.

By viewing the file that contains the script, users may be able to see its source code. Many web authors learn how to write client-side scripts partly by examining the source code for other authors' scripts.