Translate Perl code to PHP!

arrays

hashes

data structures

array split/join

case conversion

string comparisons

functions

string matching operations

basename/dirname

environment variables

POST/GET parameters

HTML elements

URL encode

MySQL database access


Perl arrays Php arrays
@a = (); # empty
 
@a = ( 'xx', 11, 33.5, );
 
@a = 12..33;
 
$a[2] = 'something';
 
$len = scalar(@a);
# or
$len = @a;
 
@a3 = ('xx', @a1, @a2);
 
($x, $y) = @a;
 
push
pop
shift
unshift
splice
 
foreach $i (@a) { .. }
$a = array();  # empty
 
$a = array( 'xx', 11, 33.5, );
 
$a = range(12,33);
 
$a[2] = 'something';
 
$len = count($a);
 
 
 
$a3 = array_merge('xx', $a1, $a2);
 
list($x, $y) = @a;
 
array_push
array_pop
array_shift
array_unshift
array_splice
 
foreach ($a as $i) { .. }


Perl hashes Php hashes
%h = ();
 
%h = ( 'x' => 'y',
       'z' => 'w',
     );
 
$h{'x'} = 7;
 
while (($key,$value) = each(%h))
{ .. }
# %h is automatically "reset"
# for another iteration
 
$a = keys(%h);
$b = values(%h);
 
delete $h{'x'};
$h = array();
 
$h = array( 'x' => 'y',
            'z' => 'w',
          );
 
$h['x'] = 7;
 
while (list($key,$value) = each($h))
{ .. }
# must reset before reusing $h
reset($h);
 
$a = array_keys($h);
$b = array_values($h);
 
unset( $h['x'] );


Perl data structures Php data structures
%h = ('a'=>13, 'b'=>25);
@x = ('hi', 'there', 'all',);
 
@mix = ( \%h, \@x,
         [33..39],
	 { x=>15, yy=>23, },
       );
 
$mix[0]->{'b'}  # == 25
$mix[0]{'b'}    # == 25
$mix[1]->[2]    # == 35
$mix[1][2]      # == 35
$h = array('a'=>13, 'b'=>25);
$x = array('hi', 'there', 'all',);
 
$mix = array($h, $x,
	     range(33,39),
	     array('x'=>15, 'yy'=>23),
	    );
 
$mix[0]['b']  # == 25
 
$mix[1][2]    # == 35
 


Perl array split/join Php array split/join
@a = split( '\|', $s );
 
@a = split( '\s+', $s );
 
 
$s = join( '|', @a );
$a = preg_split( '/\|/', $s,
            -1, PREG_SPLIT_NO_EMPTY );
$a = preg_split( '/\s+/', $s,
            -1, PREG_SPLIT_NO_EMPTY );
 
$s = join( '|', $a );


Perl case conversion

Php case conversion

$s = lc($s);
$s = uc($s);
 
$s =~ tr/a-z/A-Z/;
$s = strtolower($s);
$s = strtoupper($s);
 
 


Perl string comparisons Php string comparisons
$s1 eq $s2
 
 
 
$s1 lt $s2
strcmp($s1,$s2) == 0
# or
$s1 === $s2
 
strcmp($s1,$s2) < 0


Perl functions Php functions
sub foo {
 my @args = @_;
}
 
sub foo {
 $x = 5;
}
 
 
 
 
 
foo2( \@a, \%h );
function foo() {
 $args = func_get_args();
}
 
function foo() {
 global $x;
 $x = 5;
}
 
function foo2($x, $y) {
}
 
foo2( $a, $h );


Perl string matching operations Php string matching operations
$s =~ m/(\w+)/;
$substr = $1;
 
@all = m/(\w+)/g;
 
 
$s =~ s/\s+/X/;
$s =~ s/\s+/X/g;
 
$s =~ s/^\s+|\s+$//g;
preg_match( "/(\w+)/", $s, $match );
$substr = $match[1];
 
preg_match_all( "/(\w+)/", $s, $match );
$all = $match[0];
 
$s = preg_replace( "/\s+/", 'X', $s, 1 );
$s = preg_replace( "/\s+/", 'X', $s );
 
$s = rtrim($s);


Perl basename/dirname

Php basename/dirname
use File::Basename;
 
$b = basename($path);
$d = dirname($path);

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


Perl environment variables

Php environment variables
%ENV
 
$ENV{REQUEST_METHOD}
 
$ARGV[$i]
 
$0

$_SERVER
 
$_SERVER[REQUEST_METHOD]
 
$argv[$i+1]
 
$argv[0]  # Php/CGI only


Perl POST/GET parameters Php POST/GET parameters
#form/hyperlink parameters:
# s : single-valued
# m : multi-valued
 
use CGI (:standard);
 
 
 
 
 
$s = param('s');
@m = param('m');
 
@param_names = param();
#form/hyperlink parameters:
# s   : single-valued
# m[] : multi-valued
#       (such as multi-selections
#        and checkbox groups)
 
$PARAM = array_merge(
   $HTTP_GET_VARS, $HTTP_POST_VARS
  );
 
$s = $PARAM[s];  # a scalar
$m = $PARAM[m];  # an array
 
$param_names = array_keys($PARAM);
 


Perl HTML elements

Php HTML elements

use CGI (:standard);
 
 
 
 
 
 
 
$ref = "x.cgi";
a({href=>$ref}, "yy")
 
textfield({name=>"yy", size=>5})
 
password({name=>"yy", size=>5})
 
textarea({name=>"yy",
	  cols=>5, rows=>2})
 
submit({value=>"yy"})
 
button( {name=>"xx",
	 value=>"yy",
         onclick=>"submit()",
        }
      )
 
%labels = (0=>'a',1=>'q',2=>'x');
popup_menu( { name=>"xx",
              values=>[0..2],
              labels=>\%labels,
              size=>4,
	    }
          )
 
 
@a = ('xx','yy','zz');
radio_group( { name=>'nn',
               values=> \@a,
               default=>'_',
               linebreak=>1,
	     }
           )
 
%labels = ('xx'=>'L1','yy'=>'L2');
@a = keys( %labels );
checkbox_group( { name=>'nn',
                  values=> \@a,
		  labels=> \%labels,
	        }
              )
 
table(
       Tr(
           [
	     td(['a','b']),
             td(['x','y']),
	   ]
         )
     )

# 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.php";
<a href="<?php echo $ref?>">yy</a>
 
<input type=text name=yy size=5>
 
<input type=password name=yy size=5>
 
<textarea name=yy cols=5 rows=2>

</textarea>
 
<input type=submit value=yy>
 
<input type=button
  name=xx value=yy
  onclick="submit()">
 
 
 
<select name=xx size=4>
<?php
$labels = array(0=>'a',1=>'q',2=>'x');
foreach (range(0,2) as $_)
  echo "<option value='$_'>",
       $labels[$_];
?>

</select>
 
$a = array('xx','yy','zz');
foreach ($a as $_)
  echo "<input type=radio
         name=nn value='$_'>$_<br>";
 
 
 
 
$labels = array('xx'=>'L1','yy'=>'L2');
foreach (array_keys($labels) as $_)
  echo "<input type=checkbox
         name=nn value='$_'>",
         $labels[$_];
 
 
 
<table>
<tr>
<td>a</td><td>b</td>

</tr>
<tr>
<td>x</td><td>y</td>
</tr>
</table>


Perl URL encode

Php URL encode

use URI::Escape;
 
uri_escape($val)
uri_unescape($val)
 
 
urlencode($val)
urldecode($val)


Perl MySQL database access

Php MySQL database access

use DBI;
$dbh = DBI->connect(
  'DBI:mysql:test:host',$usr,$pwd
);
 
 
$dbh->do( $sql_op )
 
$query = $dbh->prepare( $sql_op );
$query->execute();
 
while(@record = $query->fetchrow())
{ .. }
 
 
 
$dbh->quote($val);
 
 
 
$dbh = mysql_connect(
  'host', $usr, $pwd
);
mysql_select_db('test', $dbh)
 
mysql_query( $sql_op );
 
$results = mysql_query( $sql_op );
 
 
while($record =
        mysql_fetch_row($results))
{ .. }
 
 
mysql_quote($val)
#--------------------------- using:
function mysql_quote( $val )
{
  return
    "'" .
    preg_replace( "/'/", "'",
      preg_replace( '/\/', '',
		    $val
                  )
                )
    . "'";
}
 

One thought on “Translate Perl code to PHP!

Leave a Reply