Perl

From Leo's Notes
Last edited on 23 September 2019, at 05:05.

Perl is a scripting language.

Basics[edit | edit source]

Since I know PHP, here's the PHP equivalent for some of Perl's constructs.

PHP Arrays Perl Arrays
$a = [];
$a = [ 'x', 'y', 'z' ];
$a = range(1, 100);
$a[] = 'push';
$a = arary_merge('x', $array1, $array2)
$len = count($a)

foreach ($x as $k) {..}
@a = ();
@a = ( 'x', 'y', 'z' );
@a = 1..100;
$a[@a] = 'push';
@a = ('x', @array1, @array2);
$len = scalar(@a);   # or  $len = @a

foreach $k (@a) {..}
PHP Hashes Perl Hashes
$h = [];
$h = array[
  'foo' => 'bar',
  'abc' => 'xyz',
];
$h['x'] = 42;
 
foreach ($h as $key => $value) {..}
 
$a = array_keys($h);
$b = array_values($h);

$x = isset($h['foo']); 

unset($h['x']);
%h = ();
%h = (
  'x' => 'y',
  'z' => 'w',
);
$h{'x'} = 42;

while (($key,$value) = each(%h)) {..}
 
$a = keys(%h);
$b = values(%h);

exists $h{'foo'};
 
delete $h{'x'};
PHP Strings Perl Strings
$s = strtoupper($s);

$s = strtolower($s);


if ($s1 == $s2) {..}

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 = trim($s);


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

if $sq eq $s2

$s =~ m/(\w+)/;
$substr = $1;

@all = ($s =~ m/(\w+)/g);
 
 
$s =~ s/\s+/X/;
$s =~ s/\s+/X/g;
 
$s =~ s/^\s+
PHP Environment Variables Perl Environment Variables
$_SERVER
$_SERVER['REQUEST_METHOD']
$argv[$i+1]
$argv[0]
%ENV
$ENV{REQUEST_METHOD}
$ARGV[$i]
$0


PHP Functions Perl Subroutines
function foo() {
}

function foo2($x, $y) {
  return $x + y;
}


foo2(10, 20);
sub foo {
}

sub foo2 {
  my ($a, $b) = @_;
  return $a + b;
}
 
foo2(10, 20);



See Also[edit | edit source]