Porting from Perl to PHP or vice versa

This is a side by side translation of Perl and PHP. There may well be better ways to do it, this is one way.

There other pages similar to this, all the pages I could find were somewhat out of date.

-=Comments=-
# Perl only has comments to the end of the line
my $i; #index counter
// PHP can use // or # for single line comments
Where you can put // you can swap it for a single #
PHP also has block comments like C or C++
/* This starts a multi-line comment as
in C , C++. This is still a comment.
This is the end of the comment
blcock => */
-= Testing variables =-
defined $var; isset($var);
isset($var, $a)
exists $var;
-= Arrays Manipulation =-
@a = (); $a = array();
@a = ( ‘xx’, 11, 33.5,) $a = array( ‘xx’, 11, 33.5, );
@a = 12..33; $a = range(12,33)
$a[2] = ‘something’; $a[2] = ‘something’;
$len = scalar(@a);
$len = @a;
$len = count($a);
@a3 = (‘xx’, @a1, @a2); $a3 = array_merge((array)’xx’, $a1, $a2);
($x, $y) = @a; list($x, $y) = $a;
$a[@a] = ‘new’; # push $a[] = ‘new’; # push
push
pop
shift
unshift
splice
array_push
array_pop
array_shift
array_unshift
array_splice
foreach $value (@a) { .. }
map { .. } @a;
foreach ($a as $value) { .. }
-= Hashes =-
%h = (); $h = array();
%h = ( ‘x’ => ‘y’,
‘z’ => ‘w’,
);
$h = array( ‘x’ => ‘y’,
‘z’ => ‘w’,
);
$h{‘x’} = 7; $h[‘x’] = 7;
while (($key,$value) = each(%h)){…} foreach ($h as $key => $value){…}
foreach my $key (sort keys %h){…} ksort($h)
foreach ($h as $key => $value){…}
# When %h is keyed numerically
foreach my $key (sort { $a <=> $b} keys %h){…}
ksort($h, SORT_NUMERIC)
foreach ($h as $key => $value){…}
$a = keys(%h); $a = array_keys($h);
$b = values(%h); $b = array_values($h);
-= Data Structures =-
%h = (‘a’=>13, ‘b’=>25); $h = array(‘a’=>13, ‘b’=>25);
@x = (‘hi’, ‘there’, ‘all’,); $x = array(‘hi’, ‘there’, ‘all’,);
@mix = ( \%h, \@x,
[33..39],
{ x=>15, yy=>23, },
);
$mix = array($h, $x,
range(33,39),
array(‘x’=>15, ‘yy’=>23),
);
$mix[0]->{‘b’} # == 25
$mix[0]{‘b’} # == 25
$mix[2]->[2] # == 35
$mix[2][2] # == 35
$mix[0][‘b’] # == 25

$mix[2][2] # == 35

-= Arrays split/join =-
@a = split( ‘\s*,\s*’, $s ); $a = preg_split(‘/\s*,\s*/’, $s,-1, PREG_SPLIT_NO_EMPTY );
@a = split( ‘\s+’, $s ); $a = preg_split( ‘/\s+/’, $s,-1, PREG_SPLIT_NO_EMPTY );
# split on a string not regexp
$a = explode(‘, ‘, $s);
$s = join( ‘|’, @a ); $s = join( ‘|’, $a );
-= String Case Conversion =-
$s = lc($s);
$s = uc($s);
$s = ucfirst( lc( $s ));
$s = strtolower($s);
$s = strtoupper($s);
$s = ucfirst($s);
$s =~ tr/a-z/A-Z/; $s = strtr($s, join(”,range(‘a’, ‘z’)), join(”,range(‘A’, ‘Z’)));
-=String Comparisons=-
$s1 eq $s2 strcmp($s1,$s2) == 0
$s1 === $s2
$s1 lt $s2 strcmp($s1,$s2) < 0
-= Calling Functions =-
sub foo {
my @args = @_;
}
function foo() {
$args = func_get_args();
}
my $x;
sub foo {
$x = 5;
}
function foo() {
global $x;
$x = 5;
}
sub foo2 {
my ($x, $y) = @;

}
function foo2($x, $y) {…}
foo2( \@a, \%h ); foo2( & $a, &$h );
-= String Comparison Operations =-
$s =~ m/(\w+)/;
$substr = $1;
preg_match( “/(\w+)/”, $s, $match );
$substr = $match[1];
@all = ($s =~ m/(\w+)/g); preg_match_all( “/(\w+)/”, $s, $match );
$all = $match[0];
$s =~ s/\s+/X/;
$s =~ s/\s+/X/g;
$s = preg_replace( “/\s+/”, ‘X’, $s, 1 );
$s = preg_replace( “/\s+/”, ‘X’, $s );
// PHP defaults to global replace ‘g’
// or to be explicit
$s = preg_replace( “/\s+/”, ‘X’, $s, -1);
$s =~ s/^\s+|\s+$//g; $s = trim($s);
-= Conditions =-
if (condition) {
..
} elsif (condition) {
..
} else {
..
}
if (condition) {

} elseif (condition) {

} else {
}
// Without curley brackets
if (condition)

endif
next if condition;
-= File basename/dirname =-
use File::Basename;

$b = basename($path);
$d = dirname($path);

$b = basename($path);
$d = dirname($path);
-= Environment Variables =-
%ENV $_SERVER
$ENV{REQUEST_METHOD} $_SERVER[REQUEST_METHOD]
$ARGV[$i] $argv[$i+1]
$0 $argv[0] # Php/CGI only
# In /etc/php.ini if the value for
//variables_order includes ‘E’
//You can also use the global hash
// $_ENV
// e.g. $_ENV[‘USER’]
-= Command Line Options – GetOpt =-
PHP getopt is pretty much USELESS!
use Getopt::Long;
GetOptions (\%options,
‘v’,
‘h=s’,
‘o:s’,
$shortopts = array(
‘v’, // No Value
‘h:’, // Required value
‘o::’, // Optional value
GetOptions (\%options,
‘verbose’,
‘host=s’,
‘host_opt:s’,
);
$longopts = array(
‘verbose’, // No Value
‘host:’, // Required value
‘host_opt::’, // Optional value
);
$options = getopt(”, $longopts);
# Perl can also have options set to
# Integer or real numbers =i or =f
# Assign an aliases to an option
# ‘verbose|v’ (-verbose or -v)
# ‘noopt|dry-run’ (-noopt or -dry-run)
// PHP cannot
-= POST/GET parameters =-
#form/hyperlink parameters:
# s : single-valued
# m : multi-valued

use CGI (:standard);

#form/hyperlink parameters:
# s : single-valued
# m[] : multi-valued
# (such as multi-selections
# and checkbox groups)
$s = param(‘s’); $PARAM = array_merge($_GET, $_POST);
@m = param(‘m’); $s = $PARAM[‘s’]; # a scalar
$m = $PARAM[‘m’]; # an array
$param_names = array_keys($PARAM);
$num_params = count($PARAM);
-= HTML elements =-
use CGI (:standard); # The Perl/CGI functions have the
# additional property of “stability”
# when used in reentrant forms.
# The values of the HTML elements are
# set according to the incoming
# parameter values for those elements.
# The versions below are not stable.
$ref = “x.cgi”;
a({href=>$ref}, “yy”)
$ref = “x.php”;
<a href=”<?php echo $ref?>”>yy
textfield({name=>”yy”, size=>5}) <input type=text name=yy size=5>
password({name=>”yy”, size=>5}) <input type=password name=yy size=5>
textarea({name=>”yy”,cols=>5, rows=>2}) <textarea name=yy cols=5 rows=2>
submit({value=>”yy”}) <input type=”submit” value=yy>
button( {name=>”xx”,
value=>”yy”,
onclick=>”submit()”,
}
)
<input type=”button” name=”xx” value=”yy” onclick=”submit()”>
%labels = (0=>’a’,1=>’q’,2=>’x’); <select name=”xx” size=”4″>
popup_menu( { name=>”xx”,
values=>[0..2],
labels=>\%labels,
size=>4,
}
)
<?php
$labels = array(0=>’a’,1=>’q’,2=>’x’);
foreach (range(0,2) as $_) {
echo “<option value=’$_’>”,$labels[$_];
}
?></select>
@a = (‘xx’,’yy’,’zz’);
radio_group( { name=>’nn’,
values=> \@a,
default=>’_’,
linebreak=>1,
}
)
$a = array(‘xx’,’yy’,’zz’);
foreach ($a as $_) {
echo “<input type=radio name=nn value=’$_’>$_
“;
}
%labels = (‘xx’=>’L1′,’yy’=>’L2′);
@a = keys( %labels );
checkbox_group( { name=>’nn’,
values=> \@a,
labels=> \%labels,
}
)
$labels = array(‘xx’=>’L1′,’yy’=>’L2’);
foreach (array_keys($labels) as $_) {
echo “<input type=checkbox name=nn value=’$_’>”, $labels[$_];
}
table(
Tr(
[td([‘a’,’b’]),
td([‘x’,’y’]),]
)
)
<table>
<tr>
<td>a</td><td>b</td>
</tr>
<tr>
<td>x</td><td>y</td>
</tr>
</table>
-= URL encode =-
use URI::Escape;

uri_escape($val)
uri_unescape($val)

urlencode($val);
urldecode($val);
-= MySQL Database Access =-
use DBI;
$dbh = DBI->connect(‘DBI:mysql:test:localhost’,$usr,$pwd);
$dbh = mysqli_connect(‘localhost’, $usr, $pwd);
mysqli_query($dbh, ‘USE test’)
$dbh->do( $sql_op ); mysqli_query($dbh, $sql_op );
$query = $dbh->prepare( $sql_op );
$query->execute();
$stmt = mysqli_prepare($dbh, $sql_op );
execute($stmt);
while( @record = $query->fetchrow() ) { .. } while ($row = mysqli_fetch_row($result)) {…}
while ($row = $result->fetch_array(MYSQLI_NUM)){…}
while ($result = $sth->fetchrow_hashref()) { .. } while(
$row = mysqli_fetch_assoc($result)){ .. }
while ($row = $result->fetch_array(MYSQLI_ASSOC)) { .. }
$dbh->quote($val) $val = “‘”.mysqli_real_escape_string($dbh, $val).”‘”;

Leave a Reply

Your email address will not be published. Required fields are marked *