277

Chapter 20:

Reserved Words

"When Iuse a word," Humpty Dumpty said in a rather scornful tone,
"it means just what I choose it to mean - neither more nor less."

- Lewis Carroll, Through the Looking Glass

This chapter provides a "Quick Reference" to Perl's "reserved words" or
commands. These include the built-in functions and things that can be
thought of as functions (the "named operators") as well as the control flow
modifiers. The non-word symbolic operators, escape characters, and such
can be found in the preceding chapter.

The chapter is organized into the following sections:

  • An alphabetical list of all reserved words. The list includes all of the
    functions, named operators, and control flow modifiers which are
    available without your specifically
    useing or requireing a module or
    library. The list also includes the "backquoted commands" which have
    been specifically implemented for MacPerl. Look here if you know the
    name of command you want to find.
  • A table of all reserved words, organized by category. Look here if you
    know what you want to do, but aren't sure of the command's name.
  • Detailed synopses for a chosen subset of these reserved words, organ-
    ized alphabetically by name. The synopses include brief information on
    usage as well as occasional Mac OS-specific notes. Synopses are pro-
    vided only for a subset of the commands listed in the first two sections.

Space considerations (and the desire not to reproduce what may be better
found elsewhere) prevent us from including detailed information on every
available Perl function! We hope this reference will serve as a memory aid
for functions you already know about, and a sufficient hint for those which
are new to you.


IMAGE imgs/410.Functions01.gif

In particular cases, we have provided more detailed information. We have
chosen to detail those functions which exist onlyin MacPerl, as well as
those which exhibit different behaviorunder MacPerl.

In addition, we have provided synopses for those Perl functions which we
feel are most useful and relevant to a wide range of Perl programming tasks.
In particular, we have included many of the functions which were used in
the examples in Part II of this book.

For explanations of the rest of the built-in functions and more information
(including code examples) on those covered here, please see the online docu-
mentation ("Built-in functions" aka
perlfunc.pod) and/or a good Perl refer-
ence book (e.g., Programming Perl). We also refer you to Parts II and III of
this book.

For more information on the Mac OS Interface functions module, as well as
details on the Macintosh Toolbox modules (which are not built in), see
Chapters 12 and 13 and the online documentation (
Macintosh specific
features
and Macintosh Toolbox Modules).

In each section, all names are given in Courierfont; in addition, we have
used the following typographical conventions to convey additional
information:

  • Boldindicates that we have included usage notes, etc. in the synopses.
  • Bold-Italicindicates that this function is not supported by
    MacPerl or is only partially supported in MacPerl (as compared to Unix
    Perl); we have included information on differences, workarounds, etc.,
    in the synopses.
  • Italicindicates that the function is not available in MacPerl.
  • Plain Couriertext indicates that there are no noticeable differences
    between the way this command works under MacPerl as compared to
    Unix Perl. We refer you to the online documentation for specific details
    on usage, etc.

IMAGE imgs/410.Functions02.gif

Alphabetical List
abs, accept, alarm, Answer, Ask, atan2
bind
, binmode, bless
caller
, chdir, chmod, chomp, Choose, chop, chown, chr, chroot,
close, closedir, connect, continue, cos, crypt
dbmclose
, dbmopen, defined, delete, die, Directory, do,
DoAppleScript, dump
each
, else, elsif, endgrent, endhostent, endnetent,
endprotoent, endpwent, eof, eval, exec, exists, exit, exp
FAccess
, fcntl, fileno, find, flock, for, foreach, fork, format,
formline
getc
, GetFileInfo, getgrent, getgrgid, getgrnam,
gethostbyaddr, gethostbyname, gethostent, getlogin,
getnetbyaddr, getnetbyname, getnetent, getpeername, getpgrp,
getppid, getpriority, getprotobyname, getprotobynumber,
getprotoent, getpwent, getpwnam, getpwuid, getservbyaddr,
getservbyname, getservbyport, getservent, getsockname,
getsockopt, glob, gmtime, goto, grep
hex
, hostname
if
, import, index, int, ioctl
join
keys
, kill
last
, lc, lcfirst, length, link, listen, LoadExternals, local,
localtime, log, lstat
m//
, MakeFSSpec, MakePath, map, mkdir, msgctl, msgget, msgrcv,
msgsnd, my
next
, no
oct
, open, opendir, ord
pack
, package, Pick, pipe, pop, pos, print, printf, push, pwd
q//
, qq//, Quit, quotemeta, qw//, qx//
rand
, read, readdir, readlink, recv, redo, ref, rename, Reply,
require, reset, return, reverse, rewinddir, rindex, rmdir


IMAGE imgs/410.Functions03.gif

s///, scalar, seek, seekdir, select, semctl, semget, semop, send,
SetFileInfo, setgrent, sethostent, setnetent, setpgrp,
setpriority, setprotoent, setpwent, setservent, setsockopt,
shift, shmctl, shmget, shmread, shmwrite, shutdown, sin, sleep,
socket, socketpair, sort, splice, split, sprintf, sqrt, srand,
stat, stty, study, sub, substr, symlink, syscall, sysopen,
sysread, system, syswrite
tell
, telldir, tie, tied, time, times, tr///, truncate
uc
, ucfirst, umask, undef, unless, unlink, until, unpack,
unshift, untie, use, utime
values
, vec, Volumes
wait
, waitpid, wantarray, warn, while, write
y///

Categories

The built-in functions are categorized below by type (e.g., Data Manipu-
lation, Input/Output, Networking, etc.) and subtype (e.g. Numeric, Lists,
etc.). Some functions may be listed in more than one category.

Data Manipulation - Numeric
absexp
atan2int
coslog

rand
sin
sqrt

srand

Data Manipulation - Conversion
chroct
hexord

pack
unpack

vec

Data Manipulation - Lists (any)
grepmap
joinreverse

scalar
sort

split
unpack

Data Manipulation - Lists (@array)
popshift
pushsplice

unshift


IMAGE imgs/410.Functions04.gif

Data Manipulation - Lists (%hash)
deleteexists
each
keys

values

Data Manipulation - Time
gmtimelocaltime

time

times

Data Manipulation - Strings and Patterns
chomplengthquotemeta
chopm//reverse
cryptposrindex
evalq//s///
indexqq//split
lcqw//sprintf
lcfirstqx//substr

tr///
uc
ucfirst
y///

Functions, Modules, and Classes
blessmy
callerno
importpackage
localref

require
return
sub
tie

tied
untie
use
wantarray

Group/User data
endgrent
endpwent
getgrent

getgrgid
getgrnam
getpwent

getpwnam
getpwuid
setgrent

setpwent

Input/Output - File System
chmodlstat
chownmkdir
globreadlink
linkrename

rmdir
stat
symlink
truncate

unlink
utime

Input/Output - File
binmodefileno
closeflock
dbmcloseformat
dbmopenformline
eofgetc
fcntlioctl

open
pipe
print
printf
read
seek

select
sysopen
sysread
syswrite
tell
write


IMAGE imgs/410.Functions05.gif

Input/Output - Directory
closedirreaddir
opendirrewinddir

seekdir
telldir

Mac OS Interface
Answer
Ask
Choose
DoAppleScript
FAccess

GetFileInfo
LoadExternals
MakeFSSpec
MakePath
Pick

Quit
Reply
SetFileInfo
Volumes

Miscellaneous
defined
do
dump

eval
find
formline

ref
reset
scalar

sort
study
undef

Network Protocols
endprotoent
getprotobyname

getprotobynumber
getprotoent

setprotoent

Networking - Sockets
accept
bind
Choose
connect
endhostent
endnetent
gethostbyaddr
gethostbyname
gethostent
getnetbyaddr

getnetbyname
getnetent
getpeername
getservbyaddr
getservbyname
getservbyport
getservent
getsockname
getsockopt
listen

recv
send
sethostent
setnetent
setservent
setsockopt
shutdown
socket
socketpair

Networking - System V
msgctlmsgsnd
msggetsemctl
msgrcvsemget

semop
shmctl
shmget

shmread
shmwrite

Process management
alarmfork
chdirgetlogin
chrootgetpgrp

setpgrp
setpriority
sleep

wait
waitpid
warn


IMAGE imgs/410.Functions06.gif

die
exec
exit

getppid
getpriority
kill

syscall
system
umask

Control Flow Modifiers

The control flow modifiers include commands for selection (conditional
evaluation), repetition (looping), and movement within a block.
1

continue
else
elsif
for

foreach
goto
if
last

next
redo
unless
until

while

Inline execution (`backquoted commands`)

MacPerl has a limited capability to handle constructs like `command`,
if you have
ToolServer(and MPW). Additionally, whether you have
ToolServeror not, a few commands are specifically implemented (emu-
lated, really) by MacPerl. Each is described below as if it were a func-
tion. Remember that these commands use backquotes, not parentheses!

These commands may not be portable to platforms other than Mac OS.
`pwd`and `hostname`should be available under Unix Perl. Unix sys-
tems have the
sttycommand, but its options vary; read the manual.
`Directory`and `glob`should be assumed to be non-portable.

`Directory`
`glob`

`hostname`
`pwd`

`stty raw`
`stty sane`

Synopses

Answer

MacPerl::Answer(PROMPT)
MacPerl::Answer(PROMPT, BUTTON1, BUTTON2, BUTTON3)

Puts up a dialog box with a message (PROMPT) and a choice of 1, 2, or 3
buttons for the user to click.

IMAGE imgs/410.Functions07.gif

1gotois an "actual" function.


IMAGE imgs/410.Functions08.gif

Ask

MacPerl::Ask(PROMPT, DEFAULT)
MacPerl::Ask(PROMPT)

Asks the user for a string. Returns undefif the dialog is cancelled.

chdir

chdir(EXPR)

Changes the working directory to EXPR, if possible.

chmod

chmod(EXPR, FILE)
chmod(EXPR, LIST)

This function has limited meaning under MacPerl. Disabling write per-
mission is mapped to locking a file (or a list of files). For example:

chmod(0444, 'foo');
chmod(0666, 'foo');

#lock the file
# unlock the file

chomp

chomp(VARIABLE)
chomp(LIST)
chomp

Removes the line ending character (corresponding to the current value
of
$/; the default is \n). Returns the number of characters removed. If
VARIABLEis omitted, it chomps $_. If you chompa list, each element is
chomped.

Choose

MacPerl::Choose(DOMAIN, TYPE, PROMPT, CONSTRAINT,
FLAGS, DEFAULT)
MacPerl::Choose(DOMAIN, TYPE, PROMPT, CONSTRAINT,
FLAGS)
MacPerl::Choose(DOMAIN, TYPE, PROMPT, CONSTRAINT)
MacPerl::Choose(DOMAIN, TYPE, PROMPT)

Puts up a modal dialog, prompting the user to choose a network address.
DOMAINspecifies the communication domain, as in socket(). TYPEis
ignored by current domains.
PROMPTis a message that will appear in


IMAGE imgs/410.Functions09.gif

the dialog. CONSTRAINTmay be set to a packed value to restrict the
types of acceptable addresses.

Choosewas used primarily for networking and GUI purposes. How-
ever, the
Socketmodule and various Mac Toolbox modules are now
recommended for these uses.

close

close(FILEHANDLE)

Closes the file associated with FILEHANDLE.

closedir

closedir(DIRHANDLE)

Closes the directory (folder) associated with DIRHANDLE.

continue

continue

Repetition control flow modifier. See: while.

dbmclose

dbmclose(HASH)

Breaks the binding between a DBM file and HASH.

dbmopen

dbmopen(HASH, DBNAME, MODE)

Binds one of various types of database (DB) file to HASH. DBNAMEis the
name of the database. On Unix systems, if the database does not exist,
it is created with permissions as specified by
MODE(modified by the
umask). File permissions are unsupported in MacPerl. If you don't plan
to port your script to Unix, just pick a reasonable value (e.g.,
0666).

defined

defined(EXPR)
defined

Returns a Boolean value telling whether EXPRhas a value other than
the undefined value undef. If
EXPRis omitted, $_is checked.


IMAGE imgs/410.Functions10.gif

die

die(LIST)
die()

Prints the value of LISTto STDERRand exits with the current value of
$! (errno). See also:
warn.

Directory

`Directory`

Returns the current directory, followed by a newline. Same as `pwd`.

DoAppleScript

MacPerl::DoAppleScript(SCRIPT)

Executes an AppleScript script, SCRIPT. The AppleScript script code is
usually presented as a string, if short, or within a here document.

each

each(HASH)

In list context, returns a two element array consisting of the key and value
for the next element of
HASH.In scalar context, returns only the key. See
also:
keys, values.

elsif

elsif (EXPR2) { ... }

Conditional control flow modifier. See: iffor details.

else

else { ... }

Conditional control flow modifier. See: if, unlessfor details.

eof

eof(FILEHANDLE)
eof()
eof

The eoffunction returns true if the next read on FILEHANDLEwill return
end of file (or if
FILEHANDLEis not open). Without an argument, eof
returns the end of file status for the last file read.


IMAGE imgs/410.Functions11.gif

Unlike many Perl functions, eofbehaves differently if it is given an
empty list as an argument, that is,
eofand eof()may not produce the
same result! Within a
while (<>)loop, iterating across the files in
@ARGV, eofwithout parentheses will test the status of eachfile. In
contrast,
eof()will only test the status of the lastfile in the list. In
this case,
eofwithout parentheses is equivalent to eof(ARGV).

FAccess

MacPerl::FAccess(FILE, CMD, ARGS)

This function is only available when using the MacPerl MPW tool; it is
not supported by the standalone application.
FAccessmanipulates
various file information. To get the command constants, it is convenient
to
require"FAccess.ph".

for

for (EXPR; CONDITION; EXPR2) { ... }

Repetition control flow modifier. Upon startup of a forloop, the
initial state is set by
EXPRand the truth of CONDITIONis checked. If
the condition is true, the block is executed. On the next and all
subsequent iterations,
EXPR2is evaluated and CONDITIONis checked
again. If
CONDITIONis still true, the block is evaluated again. The
loop will continue, evaluating
EXPR2each time, for as long as
CONDITIONramains true. See also: foreach.

foreach

foreach SCALAR (LIST) { ... }

Repetition control flow modifier. A foreachloop is used to evaluate a
block of code for each of a known list of scalars, typically the elements
of an array or hash. Note that the loop variable,
SCALAR, becomes a
reference to the actual list element under consideration; modifying this
variable will modify the original array or hash! See also:
for.

Note:forand foreachare actually synonyms for the same command,
and can be used interchangeably with the same syntax. Conventionally,
however, they are most commonly used as we have shown.


IMAGE imgs/410.Functions12.gif

getc

getc(FILEHANDLE)
getc()

Returns a string containing the next character (byte) read from FILE
HANDLE
. If no filehandle is specified, reads from STDIN. Returns a null
string at end of file. See also:
stty.

GetFileInfo

MacPerl::GetFileInfo(FILE)

In scalar context, returns the file type. In array context, returns (creator,
type).

glob

glob(PATTERN)
<PATTERN>
`glob PATTERN`

Expands the glob PATTERNand returns a list of expanded file names.
Only the
"*"and "?"metacharacters are supported; Option-x is an
(MPW-style) alternative to
"*". For example, the glob pattern <*.pl>
will match all files in the current directory whose names end in .pl.

goto

goto LABEL
goto EXPR
goto &SUB

A gotostatement jumps to the specified location in a program and
resumes execution at that point. Typically, the first form is used;
goto
jumps to the statement labeled LABEL. If an expression, EXPR, is given,
this provides a label name whose scope is resolved dynamically.

The last form, goto &SUB, substitutes a call to subroutine SUBfor the
currently running subroutine. This is typically used by
AUTOLOADand
not by mere mortal Perl programs.

hostname

`hostname`

Returns the name of the current Macintosh (if TCP/IP is running).


IMAGE imgs/410.Functions13.gif

if

if (EXPR){ ... }
elsif (EXPR2) { ... }
else{ ... }

Conditional control flow modifier. An ifstatement evaluates an
expression,
EXPR. If true, the following block of code is executed. If
false, an
elsifstatement, if present, will be evaluated, testing EXPR2
expression for truth, and so on.

Any number of elsifstatements may be included; each is evaluated
only if all preceding conditionswere false. When any condition is true,
that block is executed; any succeeding conditions are ignored.

An elsestatement may occur at the very end, to "catch" a condition
that evaluated false through all preceding tests. See also:
unless.

index

index(STRING, SUBSTRING, POSITION)
index(STRING, SUBSTRING)

Returns the position of the first occurrence of SUBSTRINGin STRINGat
or after
POSITION. If POSITIONis omitted, starts searching from the
beginning of the string.

keys

keys(HASH)

Returns an array consisting of all the keys of the named hash. See also:
each, values.

last

last

Control flow modifier, repetition. The laststatement forces a loop to
end prematurely, skipping to the end of the execution block as if this
were the last iteration (e.g., as if the test condition had returned false).
If present, a
continueblock will notbe evaluated. See also:
continue, for, next, redo, while.


IMAGE imgs/410.Functions14.gif

length

length(EXPR)
length()

Returns the length in characters of EXPR, or of $_if EXPRis omitted.

LoadExternals

MacPerl::LoadExternals(LIBFILE)

Loads XCMD and XFCN extensions contained in file LIBFILE, which is
searched along the same path as it would be for a
require. The exten-
sions are made accessible in the current package, unless they contain an
explicit package name.

localtime

localtime(EXPR)
localtime()

Converts a time as returned by time()into a 9-element array with the
time adjusted for the local time zone. If
EXPRis omitted, uses the
current time. The array returned is typically used as:

($sec, $min, $hour, $mday, $mon, $year, $wday,
$yday, $isdst) = localtime(time);

All array elements are returned are numeric; $monhas the range 0..11;
$wday