Implicit Evaluation with PHP

2 October 2006

PHP and Perl Comparison

Today’s post is more practical than usual. A few weeks ago, I discovered a functional comparison between PHP and Perl authored by Professor Alva Couch of Tufts University. It struck me as a very useful resource, so I updated the PHP column to PHP5 (it was PHP3) and added all the function documentation I could find. So here it is. Enjoy!

Action PHP Perl Notes
File extension .php, .php3, .php4, .php5, .inc .pl, .cgi, pm The extension is only important to the web server when determining the document’s MIME type, and to aid developers in discovering files. Included files can have arbitrary extensions.
Code Code is contained in blocks within a file. Included files must create their own blocks. Whole file is script An included file is not considered within the block that included it.
HTML All the file’s content which is not in a block is considered HTML. Using PHP’s output functions, HTML can also be programactially generated. All HTML must be printed in code.  
First line requirements No special requirements The first line of the file being accessed must be a shebang A shebang is a line declaring the location of the interpretter, eg, #!/usr/bin/perl
Execution A PHP script can be executed at the command line if it has proper permissions (755) and a shebang. The only requirement when accessed through a web server is read (644) The file being accessed must have a shebang and be marked executable (755) In both languages, included files can lack a shebang and execute privelages.
Output echo, print, or content not held within a block print “stuff\n”; Both languages support print “\n”; calls.
Variables All variables reguardless of type are prefaced by a “$” (eg $foo) All variables are prefaced by a symbol which implies it’s meaning: $foo is a scalar variable, @foo is an array, %foo is a hash. foo with no identifier is a handle.  
Arrays $var = array(1,2,3); @var = (1,2,3); Note that perl does not require the word array, because the @ already prepared perl for the data type to expect.
Accessing index $var[1] is second element of $var $var[1] is second element of @var Perl uses a $ because the element being accessed in the array is a scalar
Determining array size count($var) is how many indices exist within an array scalar(@var) is how many indices exist  
Transversing array with for for ($i=0; $i < count($var); $i++) { print $var[$i]; } for ($i=0; $i < scalar(@var); $i++) { print $var[1]; }  
Transversing array with foreach foreach ($arrayname as $value) { print $value; } foreach $value (@arrayname) { print $value; }  
Imploding (joining) array join(”:”, array(1,2,3)) join(”:”, (1,2,3))  
Array data structure Associative arrays and conventional arrays are the same data type Associative arrays (hashes) are their own type Hash is a term used primarily in Perl
Creating associative array $var = array(1=>”ho”,”hi”=>4); %var = (1=>"ho","hi"=>4); The initialization code is very similar to standard array’s code
Accessing associative index $var['hi'] is 4 $var{'hi'} is 4 Note that Perl’s hash uses curly braces instead of straight braces
Looping over associative array foreach ($array as $key => $value) { … } while (($key,$value) = each %array) {…} A closer alternative to Perl’s iteration exists, but is rarely used
Default variable scope Local Global  
Explicitally specifying alternative scope global $variablename; // brings in variable from global scope my $var; # declares a local variable local to a procedure Global variables are those which aren’t inside a function/sub.
Static variables static $foo; // within a function Doesn’t exist Static variables are those which retain their value acros multiple calls to that function.
Dynamically scoped variables Doesn’t exist local $var; A nested function call retains access to the caller’s scope.
Non-evaluated string 'stuff' 'stuff' The only characters evaluated in this string type are escapes
Evaluated string "stuff $var" "stuff $var" Replaces variable with variable’s value
String concatenation $a . $b $a . $b  
String splitting $array = split("[ \t]+",$thing) @array = split(/[ \t]+/,$thing)  
File variable types Resource type File handle Perl and PHP’s file variable type is essentially the same, only Perl’s variable lacks a delimiter and PHP uses the same $ which all variables use.
Function reference C file functions Shell scripting functions PHP’s file I/O functions are based in name on C’s, whereas Perl’s are based on shell’s functions
Open a file $fd=fopen
(”file.txt”,”MODE”);
$success=open
(FD,”MODEfile.txt”);
$fd holds the resource in PHP, FD holds it in Perl. Errors are explicit in Perl through the success variable and implicit in PHP by $fd’s value. PHP uses the second fopen parameter to control use, PERL uses arrows like shell scripts do
Open modes
PHP Perl Description
r < Open for reading only; place the file pointer at the beginning of the file.
r+ <+ Open for reading and writing; place the file pointer at the beginning of the file.
w > Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
w+ >+ Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
a >> Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
a+ >>+ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
Write to a file fwrite($fd,$stuff); print FD $stuff;
Read line from file $stuff=fgets($fd); $stuff = <FD>; Perl populates the implicit variable $_ (which is an assumed argument) with the current line when looping through a file handle
Close file fclose($fd); close(FD);
Read file’s lines into array $filelines = file(”junk.txt”); open(FD,"<junk.txt"); $stuff=(<FD>);
Regular expressions if (ereg(’[ \t]’,$thing)) { … } if ($thing =~ /[\t]/) { ... } PHP’s regular expressions are based on Perl’s
Replacing by regular expressions $thing=ereg_replace
(”[\t]+”,’:',$thing);
$thing =~ s/[\t]+/:/g;
Creating function function foo() { print “hi\n”; } sub foo { print “hi\n”; }
Explicit Arguments function foo ($bar) { … } Doesn’t exist
Variable Arguments function foo () {
$bar = func_get_arg(0);
$baz = func_get_arg(1);
// …
}
sub foo {
my $bar = shift;
my $baz = shift;
# …
}
An implicit variable @_ gets populated with function parameters in Perl.
Function sample function foo($thing) {
print $thing;
}
sub foo {
my $thing = shift @_;
print $thing; }
Reference arguments function foo (&$bar) Perl arguments are references by default & in PHP makes a variable a reference
Refence argument sample function bar(&$thing) { $thing=1; } sub bar { $_[0]=1; }
Object data type Objects are discrete datatypes which can behave similarily to arrays Objects have a type called reference
Instanciating object $t = new stdClass;
$t->foo = 1;
$t->bar = “hello”;
$t = { foo => 1, bar = "hello" };
Accessing object $t->foo; $t->{foo};
CGI Built-in. PHP was designed as a web language. Special module. Perl was transformed into a web language.
CGI Variable $_POST[”thing”], $_GET[”thing”], $_COOKIE[”thing”], $_REQUEST[”thing”] $cgi=new CGI; $thing=$cgi->param(’thing’); $_REQUEST is a special combination of POST, GET and COOKIE
Self-aware $_SERVER[”PHP_SELF”] $ENV{'SCRIPT_NAME'}; These terms are the indices and need not be replaced with anything
HTTP Header Automatic, can be overriden Explicit in code PHP sends headers for a HTML response. New headers can be sent to send images, CSS, JavaScript or any other file type
Styles Many similar functions Many shorthands
Parameters Only a few built-in functions are scope-aware Anything that can be inferred can be left out
Function calls Any call functions the same way in any context many function calls change what they do depending upon context
Reading code Easily readable Implicit actions make reading difficult

Derived from Professor Alva Couch of Tufts University’s Comparison

One Comment currently posted.

Anonymous says:

Hi! Very nice site! Thanks you very much!

Post a comment on this entry: