a2p
accept
access
acct
addftinfo
addr2line
adjtime
afmtodit
after
aio_cancel
aio_error
aio_read
aio_return
aio_suspend
aio_waitcomplete
aio_write
alias
aliases
alloc
anvil
append
apply
apropos
ar
array
as
asa
asn1parse
at
atq
atrm
attemptckalloc
attemptckrealloc
authlib
authtest
autopoint
awk
b64decode
b64encode
basename
batch
bc
bdes
bell
bg
bgerror
biff
big5
binary
bind
bindkey
bindtags
bindtextdomain
bio
bitmap
blowfish
bn
bootparams
bootptab
bounce
brandelf
break
breaksw
brk
bsdiff
bsdtar
bsnmpd
bspatch
bthost
btsockstat
buffer
builtin
builtins
bunzip2
button
byacc
bzcat
bzegrep
bzfgrep
bzgrep
bzip2
c2ph
c89
c99
ca
cal
calendar
canvas
cap_mkdb
case
cat
catch
catman
cc
cd
cdcontrol
chdir
checkbutton
checknr
chflags
chfn
chgrp
chio
chkey
chmod
chown
chpass
chroot
chsh
ci
ciphers
ckalloc
ckdist
ckfree
ckrealloc
cksum
cleanup
clear
clipboard
clock
clock_getres
clock_gettime
clock_settime
close
cmp
co
col
colcrt
colldef
colors
colrm
column
comm
command
compile_et
complete
compress
concat
config
connect
console
continue
core
courierlogger
couriertcpd
cp
cpan
cpio
cpp
creat
crl
crontab
crunchgen
crunchide
crypt
crypto
csh
csplit
ctags
ctm
ctm_dequeue
ctm_rmail
ctm_smail
cu
cursor
cursors
cut
cvs
date
dbiprof
dbiproxy
dc
dcgettext
dcngettext
dd
dde
default
defer
deliverquota
des
destroy
devfs
df
dgettext
dgst
dh
dhparam
dialog
diff
diff3
dig
dir
dirent
dirname
dirs
discard
disktab
dngettext
do
domainname
done
dprofpp
dsa
dsaparam
dtmfdecode
du
dup
dup2
eaccess
ec
ecdsa
echo
echotc
ecparam
ed
edit
editrc
ee
egrep
elf
elfdump
elif
else
enc
enc2xs
encoding
end
endif
endsw
engine
enigma
entry
env
envsubst
eof
eqn
err
errno
error
errstr
esac
ethers
euc
eui64
eval
event
evp
ex
exec
execve
exit
expand
export
exports
expr
extattr
extattr_delete_fd
extattr_delete_file
extattr_get_fd
extattr_get_file
extattr_set_fd
extattr_set_file
f77
false
famm
famx
fblocked
fbtab
fc
fchdir
fchflags
fchmod
fchown
fcntl
fconfigure
fcopy
fdescfs
fdformat
fdread
fdwrite
fetch
fg
fgrep
fhopen
fhstat
fhstatfs
fi
file
file2c
fileevent
filename
filetest
find
find2perl
finger
flex
flock
flush
fmt
focus
fold
font
fontedit
for
foreach
fork
format
forward
fpathconf
frame
from
fs
fstab
fstat
fstatfs
fsync
ftp
ftpchroot
ftpusers
ftruncate
futimes
g711conv
gb2312
gb18030
gbk
gcc
gcore
gcov
gdb
gencat
gendsa
genrsa
gensnmptree
getconf
getdents
getdirentries
getdtablesize
getegid
geteuid
getfacl
getfh
getfsstat
getgid
getgroups
getitimer
getlogin
getopt
getopts
getpeername
getpgid
getpgrp
getpid
getppid
getpriority
getresgid
getresuid
getrlimit
getrusage
gets
getsid
getsockname
getsockopt
gettext
gettextize
gettimeofday
gettytab
getuid
glob
global
gmake
goto
gperf
gprof
grab
grep
grid
grn
grodvi
groff
groff_font
groff_out
groff_tmac
grog
grolbp
grolj4
grops
grotty
group
groups
gunzip
gzcat
gzexe
gzip
h2ph
h2xs
hash
hashstat
hd
head
help2man
hesinfo
hexdump
history
host
hostname
hosts
hosts_access
hosts_options
hpftodit
http
hup
i386_get_ioperm
i386_get_ldt
i386_set_ioperm
i386_set_ldt
i386_vm86
iconv
id
ident
idprio
if
ifnames253
ifnames259
image
imapd
incr
indent
indxbib
info
infokey
inode
install
instmodsh
interp
intro
introduction
ioctl
ipcrm
ipcs
ipf
ipftest
ipnat
ippool
ipresend
issetugid
jail
jail_attach
jobid
jobs
join
jot
kbdcontrol
kbdmap
kcon
kdestroy
kdump
kenv
kevent
keycap
keylogin
keylogout
keymap
keysyms
kgdb
kill
killall
killpg
kinit
kldfind
kldfirstmod
kldload
kldnext
kldstat
kldsym
kldunload
klist
kpasswd
kqueue
kse
kse_create
kse_exit
kse_release
kse_switchin
kse_thr_interrupt
kse_wakeup
ktrace
label
labelframe
lam
lappend
last
lastcomm
lastlog
lchflags
lchmod
lchown
ld
ldap
ldapadd
ldapcompare
ldapdelete
ldapmodify
ldapmodrdn
ldappasswd
ldapsearch
ldapwhoami
ldd
leave
less
lesskey
lex
lgetfh
lhash
libnetcfg
library
limit
limits
lindex
link
linprocfs
linsert
lint
lio_listio
list
listbox
listen
lj4_font
lkbib
llength
lmtp
ln
load
loadfont
local
locale
locate
lock
lockf
log
logger
login
logins
logname
logout
look
lookbib
lorder
lower
lp
lpq
lpr
lprm
lptest
lrange
lreplace
ls
lsearch
lseek
lset
lsort
lstat
lsvfs
lutimes
lynx
m4
madvise
magic
mail
maildiracl
maildirkw
maildirmake
mailq
mailx
make
makeinfo
makewhatis
man
manpath
master
mc
mcedit
mcview
md2
md4
md5
mdc2
memory
menu
menubar
menubutton
merge
mesg
message
mincore
minherit
minigzip
mkdep
mkdir
mkfifo
mkimapdcert
mklocale
mknod
mkpop3dcert
mkstr
mktemp
mlock
mlockall
mmap
mmroff
modfind
modfnext
modnext
modstat
moduli
more
motd
mount
mprotect
mptable
msdos
msdosfs
msgattrib
msgcat
msgcmp
msgcomm
msgconv
msgen
msgexec
msgfilter
msgfmt
msggrep
msginit
msgmerge
msgs
msgunfmt
msguniq
mskanji
msql2mysql
msync
mt
munlock
munlockall
munmap
mv
myisamchk
myisamlog
myisampack
mysql
mysqlaccess
mysqladmin
mysqlbinlog
mysqlcheck
mysqld
mysqldump
mysqld_multi
mysqld_safe
mysqlhotcopy
mysqlimport
mysqlshow
mysql_config
mysql_fix_privilege_tables
mysql_zap
namespace
nanosleep
nawk
nc
ncal
ncplist
ncplogin
ncplogout
neqn
netconfig
netgroup
netid
netstat
networks
newaliases
newgrp
nex
nfsstat
nfssvc
ngettext
nice
nl
nm
nmount
nohup
nologin
notify
nroff
nseq
nslookup
ntp_adjtime
ntp_gettime
nvi
nview
objcopy
objdump
objformat
ocsp
od
onintr
open
openssl
opieaccess
opieinfo
opiekey
opiekeys
opiepasswd
option
options
oqmgr
pack
package
packagens
pagesize
palette
pam_auth
panedwindow
parray
passwd
paste
patch
pathchk
pathconf
pawd
pax
pbm
pcre
pcreapi
pcrebuild
pcrecallout
pcrecompat
pcrecpp
pcregrep
pcrematching
pcrepartial
pcrepattern
pcreperform
pcreposix
pcreprecompile
pcresample
pcretest
perl
perl56delta
perl58delta
perl561delta
perl570delta
perl571delta
perl572delta
perl573delta
perl581delta
perl582delta
perl583delta
perl584delta
perl585delta
perl586delta
perl587delta
perl588delta
perl5004delta
perl5005delta
perlaix
perlamiga
perlapi
perlapio
perlapollo
perlartistic
perlbeos
perlbook
perlboot
perlbot
perlbs2000
perlbug
perlcall
perlcc
perlce
perlcheat
perlclib
perlcn
perlcompile
perlcygwin
perldata
perldbmfilter
perldebguts
perldebtut
perldebug
perldelta
perldgux
perldiag
perldoc
perldos
perldsc
perlebcdic
perlembed
perlepoc
perlfaq
perlfaq1
perlfaq2
perlfaq3
perlfaq4
perlfaq5
perlfaq6
perlfaq7
perlfaq8
perlfaq9
perlfilter
perlfork
perlform
perlfreebsd
perlfunc
perlglossary
perlgpl
perlguts
perlhack
perlhist
perlhpux
perlhurd
perlintern
perlintro
perliol
perlipc
perlirix
perlivp
perljp
perlko
perllexwarn
perllinux
perllocale
perllol
perlmachten
perlmacos
perlmacosx
perlmint
perlmod
perlmodinstall
perlmodlib
perlmodstyle
perlmpeix
perlnetware
perlnewmod
perlnumber
perlobj
perlop
perlopenbsd
perlopentut
perlos2
perlos390
perlos400
perlothrtut
perlpacktut
perlplan9
perlpod
perlpodspec
perlport
perlqnx
perlre
perlref
perlreftut
perlrequick
perlreref
perlretut
perlrun
perlsec
perlsolaris
perlstyle
perlsub
perlsyn
perlthrtut
perltie
perltoc
perltodo
perltooc
perltoot
perltrap
perltru64
perltw
perlunicode
perluniintro
perlutil
perluts
perlvar
perlvmesa
perlvms
perlvos
perlwin32
perlxs
perlxstut
perror
pfbtops
pftp
pgrep
phones
photo
pic
pickup
piconv
pid
pipe
pkcs7
pkcs8
pkcs12
pkg_add
pkg_check
pkg_create
pkg_delete
pkg_info
pkg_sign
pkg_version
pkill
pl2pm
place
pod2html
pod2latex
pod2man
pod2text
pod2usage
podchecker
podselect
poll
popd
popup
posix_madvise
postalias
postcat
postconf
postdrop
postfix
postkick
postlock
postlog
postmap
postqueue
postsuper
pr
pread
preadv
printcap
printenv
printf
proc
procfs
profil
protocols
prove
proxymap
ps
psed
psroff
pstruct
ptrace
publickey
pushd
puts
pwd
pwrite
pwritev
qmgr
qmqpd
quota
quotactl
radiobutton
raise
rand
ranlib
rcp
rcs
rcsclean
rcsdiff
rcsfile
rcsfreeze
rcsintro
rcsmerge
read
readelf
readlink
readonly
readv
realpath
reboot
recv
recvfrom
recvmsg
red
ree
refer
regexp
registry
regsub
rehash
remote
rename
repeat
replace
req
reset
resolver
resource
return
rev
revoke
rfcomm_sppd
rfork
rhosts
ripemd
ripemd160
rlog
rlogin
rm
rmd160
rmdir
rpc
rpcgen
rs
rsa
rsautl
rsh
rtld
rtprio
rup
ruptime
rusers
rwall
rwho
s2p
safe
sasl
sasldblistusers2
saslpasswd2
sbrk
scache
scale
scan
sched
sched_getparam
sched_getscheduler
sched_get_priority_max
sched_get_priority_min
sched_rr_get_interval
sched_setparam
sched_setscheduler
sched_yield
scon
scp
script
scrollbar
sdiff
sed
seek
select
selection
semctl
semget
semop
send
sendbug
sendfile
sendmail
sendmsg
sendto
services
sess_id
set
setegid
setenv
seteuid
setfacl
setgid
setgroups
setitimer
setlogin
setpgid
setpgrp
setpriority
setregid
setresgid
setresuid
setreuid
setrlimit
setsid
setsockopt
settc
settimeofday
setty
setuid
setvar
sftp
sh
sha
sha1
sha256
shar
shells
shift
shmat
shmctl
shmdt
shmget
showq
shutdown
sigaction
sigaltstack
sigblock
sigmask
sigpause
sigpending
sigprocmask
sigreturn
sigsetmask
sigstack
sigsuspend
sigvec
sigwait
size
slapadd
slapcat
slapd
slapdn
slapindex
slappasswd
slaptest
sleep
slogin
slurpd
smbutil
smime
smtp
smtpd
socket
socketpair
sockstat
soelim
sort
source
spawn
speed
spinbox
spkac
splain
split
squid
squid_ldap_auth
squid_ldap_group
squid_unix_group
sscop
ssh
sshd_config
ssh_config
stab
startslip
stat
statfs
stop
string
strings
strip
stty
su
subst
sum
suspend
swapoff
swapon
switch
symlink
sync
sysarch
syscall
sysconftool
sysconftoolcheck
systat
s_client
s_server
s_time
tabs
tail
talk
tar
tbl
tclsh
tcltest
tclvars
tcopy
tcpdump
tcpslice
tcsh
tee
tell
telltc
telnet
term
termcap
terminfo
test
texindex
texinfo
text
textdomain
tfmtodit
tftp
then
threads
time
tip
tk
tkerror
tkvars
tkwait
tlsmgr
tmac
top
toplevel
touch
tput
tr
trace
trafshow
trap
troff
true
truncate
truss
tset
tsort
tty
ttys
type
tzfile
ui
ul
ulimit
umask
unalias
uname
uncomplete
uncompress
undelete
unexpand
unhash
unifdef
unifdefall
uniq
units
unknown
unlimit
unlink
unmount
unset
unsetenv
until
unvis
update
uplevel
uptime
upvar
usbhidaction
usbhidctl
users
utf8
utimes
utmp
utrace
uudecode
uuencode
uuidgen
vacation
variable
verify
version
vfork
vgrind
vgrindefs
vi
vidcontrol
vidfont
view
virtual
vis
vt220keys
vwait
w
wait
wait3
wait4
waitpid
wall
wc
wget
what
whatis
where
whereis
which
while
who
whoami
whois
window
winfo
wish
wm
write
writev
wtmp
x509
xargs
xgettext
xmlwf
xstr
xsubpp
yacc
yes
ypcat
ypchfn
ypchpass
ypchsh
ypmatch
yppasswd
ypwhich
yyfix
zcat
zcmp
zdiff
zegrep
zfgrep
zforce
zgrep
zmore
znew
_exit
__syscall
 
FreeBSD/Linux/UNIX General Commands Manual
Hypertext Man Pages
perlintro
 
PERLINTRO(1)	       Perl Programmers Reference Guide 	  PERLINTRO(1)



NAME
       perlintro -- a brief introduction and overview of Perl

DESCRIPTION
       This document is intended to give you a quick overview of the Perl pro-
       gramming language, along with pointers to further documentation.  It is
       intended as a "bootstrap" guide for those who are new to the language,
       and provides just enough information for you to be able to read other
       peoples' Perl and understand roughly what it's doing, or write your own
       simple scripts.

       This introductory document does not aim to be complete.	It does not
       even aim to be entirely accurate.  In some cases perfection has been
       sacrificed in the goal of getting the general idea across.  You are
       strongly advised to follow this introduction with more information from
       the full Perl manual, the table of contents to which can be found in
       perltoc.

       Throughout this document you'll see references to other parts of the
       Perl documentation.  You can read that documentation using the "perl-
       doc" command or whatever method you're using to read this document.

       What is Perl?

       Perl is a general-purpose programming language originally developed for
       text manipulation and now used for a wide range of tasks including sys-
       tem administration, web development, network programming, GUI develop-
       ment, and more.

       The language is intended to be practical (easy to use, efficient, com-
       plete) rather than beautiful (tiny, elegant, minimal).  Its major fea-
       tures are that it's easy to use, supports both procedural and object-
       oriented (OO) programming, has powerful built-in support for text pro-
       cessing, and has one of the world's most impressive collections of
       third-party modules.

       Different definitions of Perl are given in perl, perlfaq1 and no doubt
       other places.  From this we can determine that Perl is different things
       to different people, but that lots of people think it's at least worth
       writing about.

       Running Perl programs

       To run a Perl program from the Unix command line:

	   perl progname.pl

       Alternatively, put this as the first line of your script:

	   #!/usr/bin/env perl

       ... and run the script as "/path/to/script.pl".	Of course, it'll need
       to be executable first, so "chmod 755 script.pl" (under Unix).

       For more information, including instructions for other platforms such
       as Windows and Mac OS, read perlrun.

       Basic syntax overview

       A Perl script or program consists of one or more statements.  These
       statements are simply written in the script in a straightforward fash-
       ion.  There is no need to have a "main()" function or anything of that
       kind.

       Perl statements end in a semi-colon:

	   print "Hello, world";

       Comments start with a hash symbol and run to the end of the line

	   # This is a comment

       Whitespace is irrelevant:

	   print
	       "Hello, world"
	       ;

       ... except inside quoted strings:

	   # this would print with a linebreak in the middle
	   print "Hello
	   world";

       Double quotes or single quotes may be used around literal strings:

	   print "Hello, world";
	   print 'Hello, world';

       However, only double quotes "interpolate" variables and special charac-
       ters such as newlines ("\n"):

	   print "Hello, $name\n";     # works fine
	   print 'Hello, $name\n';     # prints $name\n literally

       Numbers don't need quotes around them:

	   print 42;

       You can use parentheses for functions' arguments or omit them according
       to your personal taste.	They are only required occasionally to clarify
       issues of precedence.

	   print("Hello, world\n");
	   print "Hello, world\n";

       More detailed information about Perl syntax can be found in perlsyn.

       Perl variable types

       Perl has three main variable types: scalars, arrays, and hashes.

       Scalars
	   A scalar represents a single value:

	       my $animal = "camel";
	       my $answer = 42;

	   Scalar values can be strings, integers or floating point numbers,
	   and Perl will automatically convert between them as required.
	   There is no need to pre-declare your variable types.

	   Scalar values can be used in various ways:

	       print $animal;
	       print "The animal is $animal\n";
	       print "The square of $answer is ", $answer * $answer, "\n";

	   There are a number of "magic" scalars with names that look like
	   punctuation or line noise.  These special variables are used for
	   all kinds of purposes, and are documented in perlvar.  The only one
	   you need to know about for now is $_ which is the "default vari-
	   able".  It's used as the default argument to a number of functions
	   in Perl, and it's set implicitly by certain looping constructs.

	       print;	       # prints contents of $_ by default

       Arrays
	   An array represents a list of values:

	       my @animals = ("camel", "llama", "owl");
	       my @numbers = (23, 42, 69);
	       my @mixed   = ("camel", 42, 1.23);

	   Arrays are zero-indexed.  Here's how you get at elements in an
	   array:

	       print $animals[0];	       # prints "camel"
	       print $animals[1];	       # prints "llama"

	   The special variable $#array tells you the index of the last ele-
	   ment of an array:

	       print $mixed[$#mixed];	    # last element, prints 1.23

	   You might be tempted to use "$#array + 1" to tell you how many
	   items there are in an array.  Don't bother.	As it happens, using
	   @array where Perl expects to find a scalar value ("in scalar con-
	   text") will give you the number of elements in the array:

	       if (@animals < 5) { ... }

	   The elements we're getting from the array start with a "$" because
	   we're getting just a single value out of the array -- you ask for a
	   scalar, you get a scalar.

	   To get multiple values from an array:

	       @animals[0,1];		       # gives ("camel", "llama");
	       @animals[0..2];		       # gives ("camel", "llama", "owl");
	       @animals[1..$#animals];	       # gives all except the first element

	   This is called an "array slice".

	   You can do various useful things to lists:

	       my @sorted    = sort @animals;
	       my @backwards = reverse @numbers;

	   There are a couple of special arrays too, such as @ARGV (the com-
	   mand line arguments to your script) and @_ (the arguments passed to
	   a subroutine).  These are documented in perlvar.

       Hashes
	   A hash represents a set of key/value pairs:

	       my %fruit_color = ("apple", "red", "banana", "yellow");

	   You can use whitespace and the "=>" operator to lay them out more
	   nicely:

	       my %fruit_color = (
		   apple  => "red",
		   banana => "yellow",
	       );

	   To get at hash elements:

	       $fruit_color{"apple"};		# gives "red"

	   You can get at lists of keys and values with "keys()" and "val-
	   ues()".

	       my @fruits = keys %fruit_colors;
	       my @colors = values %fruit_colors;

	   Hashes have no particular internal order, though you can sort the
	   keys and loop through them.

	   Just like special scalars and arrays, there are also special
	   hashes.  The most well known of these is %ENV which contains envi-
	   ronment variables.  Read all about it (and other special variables)
	   in perlvar.

       Scalars, arrays and hashes are documented more fully in perldata.

       More complex data types can be constructed using references, which
       allow you to build lists and hashes within lists and hashes.

       A reference is a scalar value and can refer to any other Perl data
       type. So by storing a reference as the value of an array or hash ele-
       ment, you can easily create lists and hashes within lists and hashes.
       The following example shows a 2 level hash of hash structure using
       anonymous hash references.

	   my $variables = {
	       scalar  =>  {
			    description => "single item",
			    sigil => '$',
			   },
	       array   =>  {
			    description => "ordered list of items",
			    sigil => '@',
			   },
	       hash    =>  {
			    description => "key/value pairs",
			    sigil => '%',
			   },
	   };

	   print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";

       Exhaustive information on the topic of references can be found in perl-
       reftut, perllol, perlref and perldsc.

       Variable scoping

       Throughout the previous section all the examples have used the syntax:

	   my $var = "value";

       The "my" is actually not required; you could just use:

	   $var = "value";

       However, the above usage will create global variables throughout your
       program, which is bad programming practice.  "my" creates lexically
       scoped variables instead.  The variables are scoped to the block (i.e.
       a bunch of statements surrounded by curly-braces) in which they are
       defined.

	   my $a = "foo";
	   if ($some_condition) {
	       my $b = "bar";
	       print $a;	   # prints "foo"
	       print $b;	   # prints "bar"
	   }
	   print $a;		   # prints "foo"
	   print $b;		   # prints nothing; $b has fallen out of scope

       Using "my" in combination with a "use strict;" at the top of your Perl
       scripts means that the interpreter will pick up certain common program-
       ming errors.  For instance, in the example above, the final "print $b"
       would cause a compile-time error and prevent you from running the pro-
       gram.  Using "strict" is highly recommended.

       Conditional and looping constructs

       Perl has most of the usual conditional and looping constructs except
       for case/switch (but if you really want it, there is a Switch module in
       Perl 5.8 and newer, and on CPAN. See the section on modules, below, for
       more information about modules and CPAN).

       The conditions can be any Perl expression.  See the list of operators
       in the next section for information on comparison and boolean logic
       operators, which are commonly used in conditional statements.

       if
	       if ( condition ) {
		   ...
	       } elsif ( other condition ) {
		   ...
	       } else {
		   ...
	       }

	   There's also a negated version of it:

	       unless ( condition ) {
		   ...
	       }

	   This is provided as a more readable version of "if (!condition)".

	   Note that the braces are required in Perl, even if you've only got
	   one line in the block.  However, there is a clever way of making
	   your one-line conditional blocks more English like:

	       # the traditional way
	       if ($zippy) {
		   print "Yow!";
	       }

	       # the Perlish post-condition way
	       print "Yow!" if $zippy;
	       print "We have no bananas" unless $bananas;

       while
	       while ( condition ) {
		   ...
	       }

	   There's also a negated version, for the same reason we have
	   "unless":

	       until ( condition ) {
		   ...
	       }

	   You can also use "while" in a post-condition:

	       print "LA LA LA\n" while 1;	    # loops forever

       for Exactly like C:

	       for ($i=0; $i <= $max; $i++) {
		   ...
	       }

	   The C style for loop is rarely needed in Perl since Perl provides
	   the more friendly list scanning "foreach" loop.

       foreach
	       foreach (@array) {
		   print "This element is $_\n";
	       }

	       # you don't have to use the default $_ either...
	       foreach my $key (keys %hash) {
		   print "The value of $key is $hash{$key}\n";
	       }

       For more detail on looping constructs (and some that weren't mentioned
       in this overview) see perlsyn.

       Builtin operators and functions

       Perl comes with a wide selection of builtin functions.  Some of the
       ones we've already seen include "print", "sort" and "reverse".  A list
       of them is given at the start of perlfunc and you can easily read about
       any given function by using "perldoc -f functionname".

       Perl operators are documented in full in perlop, but here are a few of
       the most common ones:

       Arithmetic
	       +   addition
	       -   subtraction
	       *   multiplication
	       /   division

       Numeric comparison
	       ==  equality
	       !=  inequality
	       <   less than
	       >   greater than
	       <=  less than or equal
	       >=  greater than or equal

       String comparison
	       eq  equality
	       ne  inequality
	       lt  less than
	       gt  greater than
	       le  less than or equal
	       ge  greater than or equal

	   (Why do we have separate numeric and string comparisons?  Because
	   we don't have special variable types, and Perl needs to know
	   whether to sort numerically (where 99 is less than 100) or alpha-
	   betically (where 100 comes before 99).

       Boolean logic
	       &&  and
	       ||  or
	       !   not

	   ("and", "or" and "not" aren't just in the above table as descrip-
	   tions of the operators -- they're also supported as operators in
	   their own right.  They're more readable than the C-style operators,
	   but have different precedence to "&&" and friends.  Check perlop
	   for more detail.)

       Miscellaneous
	       =   assignment
	       .   string concatenation
	       x   string multiplication
	       ..  range operator (creates a list of numbers)

       Many operators can be combined with a "=" as follows:

	   $a += 1;	   # same as $a = $a + 1
	   $a -= 1;	   # same as $a = $a - 1
	   $a .= "\n";	   # same as $a = $a . "\n";

       Files and I/O

       You can open a file for input or output using the "open()" function.
       It's documented in extravagant detail in perlfunc and perlopentut, but
       in short:

	   open(INFILE,  "input.txt")	or die "Can't open input.txt: $!";
	   open(OUTFILE, ">output.txt") or die "Can't open output.txt: $!";
	   open(LOGFILE, ">>my.log")	or die "Can't open logfile: $!";

       You can read from an open filehandle using the "<>" operator.  In
       scalar context it reads a single line from the filehandle, and in list
       context it reads the whole file in, assigning each line to an element
       of the list:

	   my $line  = ;
	   my @lines = ;

       Reading in the whole file at one time is called slurping. It can be
       useful but it may be a memory hog. Most text file processing can be
       done a line at a time with Perl's looping constructs.

       The "<>" operator is most often seen in a "while" loop:

	   while () {	  # assigns each line in turn to $_
	       print "Just read in this line: $_";
	   }

       We've already seen how to print to standard output using "print()".
       However, "print()" can also take an optional first argument specifying
       which filehandle to print to:

	   print STDERR "This is your final warning.\n";
	   print OUTFILE $record;
	   print LOGFILE $logmessage;

       When you're done with your filehandles, you should "close()" them
       (though to be honest, Perl will clean up after you if you forget):

	   close INFILE;

       Regular expressions

       Perl's regular expression support is both broad and deep, and is the
       subject of lengthy documentation in perlrequick, perlretut, and else-
       where.  However, in short:

       Simple matching
	       if (/foo/)	{ ... }  # true if $_ contains "foo"
	       if ($a =~ /foo/) { ... }  # true if $a contains "foo"

	   The "//" matching operator is documented in perlop.	It operates on
	   $_ by default, or can be bound to another variable using the "=~"
	   binding operator (also documented in perlop).

       Simple substitution
	       s/foo/bar/;		 # replaces foo with bar in $_
	       $a =~ s/foo/bar/;	 # replaces foo with bar in $a
	       $a =~ s/foo/bar/g;	 # replaces ALL INSTANCES of foo with bar in $a

	   The "s///" substitution operator is documented in perlop.

       More complex regular expressions
	   You don't just have to match on fixed strings.  In fact, you can
	   match on just about anything you could dream of by using more com-
	   plex regular expressions.  These are documented at great length in
	   perlre, but for the meantime, here's a quick cheat sheet:

	       .		   a single character
	       \s		   a whitespace character (space, tab, newline)
	       \S		   non-whitespace character
	       \d		   a digit (0-9)
	       \D		   a non-digit
	       \w		   a word character (a-z, A-Z, 0-9, _)
	       \W		   a non-word character
	       [aeiou]		   matches a single character in the given set
	       [^aeiou] 	   matches a single character outside the given set
	       (foo|bar|baz)	   matches any of the alternatives specified

	       ^		   start of string
	       $		   end of string

	   Quantifiers can be used to specify how many of the previous thing
	   you want to match on, where "thing" means either a literal charac-
	   ter, one of the metacharacters listed above, or a group of charac-
	   ters or metacharacters in parentheses.

	       *		   zero or more of the previous thing
	       +		   one or more of the previous thing
	       ?		   zero or one of the previous thing
	       {3}		   matches exactly 3 of the previous thing
	       {3,6}		   matches between 3 and 6 of the previous thing
	       {3,}		   matches 3 or more of the previous thing

	   Some brief examples:

	       /^\d+/		   string starts with one or more digits
	       /^$/		   nothing in the string (start and end are adjacent)
	       /(\d\s){3}/	   a three digits, each followed by a whitespace
				   character (eg "3 4 5 ")
	       /(a.)+/		   matches a string in which every odd-numbered letter
				   is a (eg "abacadaf")

	       # This loop reads from STDIN, and prints non-blank lines:
	       while (<>) {
		   next if /^$/;
		   print;
	       }

       Parentheses for capturing
	   As well as grouping, parentheses serve a second purpose.  They can
	   be used to capture the results of parts of the regexp match for
	   later use.  The results end up in $1, $2 and so on.

	       # a cheap and nasty way to break an email address up into parts

	       if ($email =~ /([^@]+)@(.+)/) {
		   print "Username is $1\n";
		   print "Hostname is $2\n";
	       }

       Other regexp features
	   Perl regexps also support backreferences, lookaheads, and all kinds
	   of other complex details.  Read all about them in perlrequick,
	   perlretut, and perlre.

       Writing subroutines

       Writing subroutines is easy:

	   sub log {
	       my $logmessage = shift;
	       print LOGFILE $logmessage;
	   }

       What's that "shift"?  Well, the arguments to a subroutine are available
       to us as a special array called @_ (see perlvar for more on that).  The
       default argument to the "shift" function just happens to be @_.	So "my
       $logmessage = shift;" shifts the first item off the list of arguments
       and assigns it to $logmessage.

       We can manipulate @_ in other ways too:

	   my ($logmessage, $priority) = @_;	   # common
	   my $logmessage = $_[0];		   # uncommon, and ugly

       Subroutines can also return values:

	   sub square {
	       my $num = shift;
	       my $result = $num * $num;
	       return $result;
	   }

       For more information on writing subroutines, see perlsub.

       OO Perl

       OO Perl is relatively simple and is implemented using references which
       know what sort of object they are based on Perl's concept of packages.
       However, OO Perl is largely beyond the scope of this document.  Read
       perlboot, perltoot, perltooc and perlobj.

       As a beginning Perl programmer, your most common use of OO Perl will be
       in using third-party modules, which are documented below.

       Using Perl modules

       Perl modules provide a range of features to help you avoid reinventing
       the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ).  A
       number of popular modules are included with the Perl distribution
       itself.

       Categories of modules range from text manipulation to network protocols
       to database integration to graphics.  A categorized list of modules is
       also available from CPAN.

       To learn how to install modules you download from CPAN, read perlmodin-
       stall

       To learn how to use a particular module, use "perldoc Module::Name".
       Typically you will want to "use Module::Name", which will then give you
       access to exported functions or an OO interface to the module.

       perlfaq contains questions and answers related to many common tasks,
       and often provides suggestions for good CPAN modules to use.

       perlmod describes Perl modules in general.  perlmodlib lists the mod-
       ules which came with your Perl installation.

       If you feel the urge to write Perl modules, perlnewmod will give you
       good advice.

AUTHOR
       Kirrily "Skud" Robert 



perl v5.8.8			  2006-01-07			  PERLINTRO(1)
=1917
+90
(61)