Simple Perl Tutorial

 

 

1.      Scaler:

string1.string2 : catenate  string1 & string2
string x n : repeat string n times.

Example:  strRepeat

print "String: "; $a = <STDIN>;
print "Number of times: "; chomp($b = <STDIN>);
$c = $a x $b; print "The result is:\n$c";

 

Example Usage:

% strRepeat

String: Hussein

Number of times: 2

The result is:

Hussein

Hussein

 

2.     Arrays:

@array = (1,2,"three");
$array[0] is 1
$array[2] is three

Example: randArray

 

srand;
print "List of strings: "; @b = <STDIN>;
print "Answer: $b[rand(@b)]";

 

Example Usage:

% randArray

List of strings:

a

b

c

d

Answer: b

 

3.    Flow control:

 

·      if elseif else

·      while (1) {}

·      until (0) {}

·      for (i=0, i<n, i++) {}

·      foreach $i (list) {}

 

Example: squareForeach

foreach $number (0..32) {
    $square = $number * $number;
    printf "%5g %8g\n", $number, $square;
}

 

4.    Associative Arrays:


Example: wordcountAssocaitive

chomp(@words = <STDIN>);   
foreach $word (@words) {
    $count{$word}++
}
foreach $word (keys %count) {
    print "$word was seen $count{$word} times\n";
}

 

Example usage:

% wordcountsAssociative

Hussein

Omar

Hussein

Hussein was seen 2 times

Omar was seen 1 times

 

 

5.                 Basic I/O:

Input from STDIN
@strings = <STDIN>

 

Input from the Diamond Operator
@strings = <>
if @ARGV is empty it uses STDIN
otherwise it uses the files specified by:

$ARGV[0], $ARGV[1], etc.


Example: basicIO

 

print "List of strings:\n";
#chomp(@strings = <STDIN>);
chomp(@strings = <>);
foreach (@strings) {
    printf "%s\n", $_;
}

Example Usage:
% basicIO

aaa

bbb

^D

List of strings:

aaa

bbb

                                    

% basicIO basicIO

List of strings:

print "List of strings:\n";

#chomp(@strings = <STDIN>);

chomp(@strings = <>);

foreach (@strings) {

    printf "%s\n", $_;

}

 

 

                       

 

6.    Regular Expressions:

 

Example: vowelsAnyOrder

/i : ignore case.
To find all words that have all 5 vowels (a,e,i,o,u) in any order:

while (<>) {
    if (/a/i && /e/i && /i/i && /o/i && /u/i) {
        print;
    }
}

Example Usage:
% vowelsAnyOrder /usr/dict/words

adventitious

aeronautic

ambidextrous

argillaceous

argumentation

auctioneer

audiotape

......

Example: vowelsInOrder

To find all words that have all 5 vowels (a,e,i,o,u) in order:

while (<>) {
    if (/a.*e.*i.*o.*u/i) {
        print;
    }
}

Example Usage:
% vowelsInOrder /usr/dict/words
     adventitious
     facetious
     sacrilegious


Example: passwdMatch

open(PW,"ypcat passwd | ") ;
while (<PW>) {
    chomp;
    ($user, $gcos) = (split /:/)[0,4];
    ($real) = split /,/, $gcos;
    ($first) = split /\s+/, $real;
    $names{$first} .= " $user;";
}
foreach (keys %names) {
    $this = $names{$_};
    if ($this =~ /;/) {
        print "$_ is used by:$this\n";
    }
}

 

NOTES:

/s : space
=~ : match
.= : append

 

Example Usage:

% passwdMatch | grep virginia

virginia is used by: vkinsey; vmyers;

 

% passwdMatch | grep mohammad

mohammad is used by: malmalag; malyami;

 

Example: backqoute

system ("date");
if (`date` =~ /^S/) {
    print "Go play!\n";
} else {
    print "Get to work!\n";
}

Example Usage:

% backqoute

Sunday, July 24, 2011  8:34:11 PM EDT

Go play!

 

 

7.      Functions:

Example: subHello

&say("hello", "world");
&say("goodbye", "cruel world");
sub say {
        print "$_[0], $_[1]!\n";
}

 

Example Usage:

% subHello

hello, world!

goodbye, cruel world!

Example: subAdd

 

@_ : function arguments

print &add(@ARGV) , "\n";
print &add(1..5) ,"\n" ;
print &add(1,3,5), "\n";

sub add {
        local ($sum);
        $sum = 0;
        foreach $_ (@_) {
                $sum += $_;
        }
        return $sum;
}

Example Usage:

% subAdd 2 4 6 8

20

15

9

 

8.      File IO:

Example: fileIO

print "Input file name: ";
chomp($infilename = <STDIN>);


print "Output file name: ";
chomp($outfilename = <STDIN>);


print "Search string: ";
chomp($search = <STDIN>);


print "Replacement string: ";
chomp($replace = <STDIN>);

 

open(IN,$infilename) ||
    die "cannot open $infilename for reading: $!";
die "will not overwrite $outfilename" if -e $outfilename;


open(OUT,">$outfilename") ||
    die "cannot create $outfilename: $!";

 

while (<IN>) {    # read a line from file IN into $_
    s/$search/$replace/g; # change the lines
    print OUT $_; # print that line to file OUT
}
close(IN);
close(OUT);

 

Example usage:

% more testfile

Hussein Abdel-Wahab

% fileIO

Input file name: testfile

Output file name: testfile2

Search string: Hussein

Replacement string: Omar

% more testfile2

Omar Abdel-Wahab

 

 

9.    Format STDOUT:

 

Example: formatSTDOUT

open(PW,"ypcat passwd|") || die "How did you get logged in?";
while (<PW>) {
    ($user,$gid,$gcos) = (split /:/)[0,3,4];
    if ($gid == $ARGV[0]) {
        ($real) = split /,/,$gcos;
        write;
    }
}
format STDOUT =
@<<<<<<<  @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$user,  $real
.

format STDOUT_TOP =
Page @<<<
$%
Username  Real Name
========  =========
.

Usage examples:
% formatSTDOUT 13
  ...list of faculty

Page 1

Username  Real Name

========  =========

zeil      Steven J. Zeil

nadeem    Tamer Nadeem

wahab     Hussein Abdel-Wahab


% formatSTDOUT 22
  ...list of grad students.