Perl Script
Pingfei Chen
Introduction
-
Perl is an acronym that stands for Practical Extraction
and Report Language
-
It is an interpreted programming language known for its
power and flexibility
-
It combines the familiar syntax of C, C++, sed, awk, grep,
sh, and csh into a tool that is more powerful than the separate pieces
used together
-
It is an interpreted language optimized for scanning arbitrary
text files, extracting information from those text files, and printing
reports based on that information
-
It's also a good language for many system management tasks
What you can do with perl?
-
ADMINISTRATION scripts
-
TEXT handling and text processing
-
INFORMATION servers, clients, and tools
-
FILE handling, devices, and links with perl
-
NETWORK programming with perl
-
NEWS scripts and utilities
-
FTP scripts and library
-
DATE and TIME conversion/manipulation
-
DATABASE and archived file access with perl
Some topics about perl
That First Line
#!/usr/bin/perl
Data Types
three data types: scalars, array of scalars, and
associative arrays of scalars
Scalar Variables: Begin with a dollar sign followed
by a letter and then letters/numbers
Array of scalars: Begin with a @ sign
followed by a letter, and then letters/numbers
Associative array: Begin
with a % sign followed by a letter, and then letters/numbers
Examples :
$a = 1; $a = "Hi there";
@b = ("one","two","3");
%ages = ("Michael Caine", 39, "Dirty Den", 34,
"Angie", 27);
Special Variables
-
@ARGV holds the command line arguments.
-
$_ is used by perl for scratch space
-
< STDIN holds a newline terminated line from STDIN
-
< STDOUT is a pointer of STDOUT
-
< STDERR is a pointer of STDERR
Subroutines
A subroutine is like a command you define
yourself
Example:
#!/usr/bin/perl
$x = &getnumber;
$y = &getnumber;
$z = $x + $y;
print "$x + $y = $z\n";
sub getnumber {
print "Type in a number:
";
$number = <;
chop($number);
$number;
}
Control Structures
-
If/Then/Elsif/Else
-
Unless the opposite of if
-
For
-
While
-
Until the opposite of while
-
foreach
File Manipulation
Open function:
open(INFO, $file);
# Open for input
open(INFO, "$file");
# Open for output
open(INFO, "$file"); #
Open for appending
open(INFO, "<$file");
# Also open for input
Close function:
close(INFO);
Administration with perl
-
Add new user accounts
-
Generate random passwords for adduser
-
Change ownership of many files
-
Gripe about easy passwords
-
Making Backups
Experience with perl
-
hello.cgi hello.html
-
env.pl
-
inf.pl
-
machine.pl
-
push.pl