Print this page

Perl



PERL Quick Reference

 

Example

#!/usr/bin/perl

print "Content-type: text/html \n\n";

print "Hello, World!<br>\n";

$r=10;

if ($r==10)

   { print "$r is 10<br>\n"; }

  elsif ($r==20)

   { print "$r is 20<br>\n"; }

  else

   { print "$r is neither 10 nor 20<br>\n"; }

For Loop

my $counter;

for($counter = 0; $counter < 10; $counter++)

print "$counter "; }

While Loop

$counter = 0;

while ($counter < 10

{

   print "$counter ";

   $counter++;

}

If…Then

my $test_var = 0;

 

if( $test_var < 1)

{

   print "test_var is less than one\n";

}

Array

@colours = ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet');

$colours[0]; # This will return 'red'.

$colours[2]; # This will return 'yellow'.

$colours[6]; # This will return 'violet'.

Struct

use Class::Struct;

struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]); ===========

use Class::Struct;

    struct(Employee => {

        GivenName => '$',

        FamilyName => '$',    });

 

Function Method

sub get_array

{

  @my_array = (23, 13, 43, 56, 72, 1, 10);

  @sorted = sort(@my_array);

  return @sorted;

}

 

Class

use Class::Struct;

    struct(Employee => {

        GivenName => '$',

        FamilyName => '$',  

});

Database

use DBI;

$dbh = DBI -> connect

('DBI:Local','user','Pwd',{PrintError=>1,RaiseError=>1})

Or die “connecting : $DBI::errstr \n”

$dbh->do(“CREATE TABLE users (uid INT,login CHAR(8))”)

$sql_fmt=”INSERT INTO users VALUE(%d , %s)”;

While ($user = getpwent){

$sql = sprintf($sql_fmt,$user->uid,$dbh->quote($user->name));

$dbh->do($sql);

}




Previous page: Java
Next page: Unix & Linux System