perl 5 pocket reference

Upload: roshni-chopra

Post on 03-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 Perl 5 Pocket Reference

    1/74

    Programming Tools

    Pocket Reference

    O'REILLY Johan Vromans

  • 7/28/2019 Perl 5 Pocket Reference

    2/74

    X

    Perl 5Pocket ReferenceSecond EditionJohan Vromans

    O'REILLY"Cambridge Koln Paris Sebastopol Tokyo

  • 7/28/2019 Perl 5 Pocket Reference

    3/74

    Per l 5 Po cket Re ference , Sec ond Ed it ionbyjohan VromansCopyright 1998, 1996Johan Vrom ans. All rights reserved. Printedin the United States of America.Published by O'Reilly /k Associates, Inc.. 101 Morris Street,Sebastopol, CA 95472.Editors: Steve Talbott and Gigi KstabrookProduction Editor Madeleine N ew ellPrinting History:

    February 1996: First Edition.August 1998: Second Fdition.

    Nutshell Hsmdlxiok and the N utshell Handbook logo are registeredtrademarks of O'Reilly & Associates, Inc. The use of camel anilllama images in association with the Perl language is a trademarkof O'Reilly & Associates, Inc.Many of the designations used by manufacturers and sellers todistinguish their products are claimed as tradem arks. W here thosedesignations appear in this book, and O'Reilly & Associates. Inc.was aware of a trademark claim, the designations have beenprinted in caps or initial caps.While every precaution has been taken in the preparation of thisbook, the publisher assumes no responsibility for errors orom issions, or for dam ages resulting from the use of the infonnationcontained herein.

    0&&This book is primed on acid-free paper w ith 85% recycled content,15% post-consum er w aste. O'Reilly & Associates is committed tousing paper with the highest recycled content available consistentwith high quality.ISBN: 1-56592-495-9

  • 7/28/2019 Perl 5 Pocket Reference

    4/74

    Table of Contents

    Introduction 1Conventions 1Command-Line Options 2Syntax 3Embedded Docum entation 4Data Types 6Literal Values 6Variables 8Context 9Operators and Precedence 10Statements 11Subroutines, Packages, and Modules 13Object-Oriented Programming 15Standard Methods 16Pragmatic Modules 16Arithmetic Functions 18Conversion Functions 19Structure Conversion 20String Functions 21Array and Hash Functions 22Regular Expressions 25Search and Replace Functions 27File Test Operators 29

  • 7/28/2019 Perl 5 Pocket Reference

    5/74

    Pile Operations 30Input/Output 32Formatted Printing 35Formats 37Tying Variables 38Directory Reading Routines 39System Interaction 39Networking 42System V IPC 43Miscellaneous 44Information from System Databases 45Special Variables 49Special Arrays 53Special Hashes 53Standard Modules 54Environment Variables , 62Multithreading 63The Perl Compiler 63The Perl Debugger 64

  • 7/28/2019 Perl 5 Pocket Reference

    6/74

    Perl 5Pocket ReferenceIntroductionThe Perl 5 Pocket Reference is a quick reference guide to LarryWall's Perl program. It contains a concise description of allstatements, functions, and variables, and lots of other usefulinformation. It is based o n Perl Version 5.005.The purpose of the Pocket Reference is to a id users of Perl infinding the syntax of specific functions and statements, a n dthe meaning of built-in variables. It is not a self-containeduser guide; basic knowledge of the Perl language is required,ll is also not complete ; some of the more obscure variants ofPerl constructs have been left out. But all functions and variables arc ment ioned in at least one way they can be used .for more information o n Perl, visit th e Perl w e b site atbttp://wuw.perl.com.Conventionsthis de no te s text that you en ter literally.this means variable text, i.e., things you must fill in .tbis\ means that this will default to $ _ if omitted,word is a keyword , i.e.. a word wi th a special meaning.RinxrKN | denotes pressing a keyboard key.I.. . 1 denotes an optional part.

    Conventions

  • 7/28/2019 Perl 5 Pocket Reference

    7/74

    Command-Line Options-a Turns on autospli t m od e w hen used w i th - n or - p .

    Splits to @F.- c Check s syntax bu t do es not ex ecu te. It do es run

    BEGIN and EN D blocks.- d ( -.module 1

    Runs the script under the indicated module. Defaultmodule is the debugger . Use -deO to start thedeb ug ger w ithout a script.

    -DJltigs Sets debugging flags.- e commandtitwMay be used to enter a single line of script. Multiple

    -e commands may be given to bui ld up a mult i l inescript .-Prvgex Specifies a regular expression to split on if -a is in

    effect,-h Prints die Perl usage summary. Does not execute.-text Files processed by the < > construct are to be edited

    in place.-Idir The directory is prepended to the search path forPerl m od ules. IN C. With - P , also tells the Cpre pro ce sso r w he re to look for include files.

    - l ( octnum 1(That's the letter ell.) Enables automatic line-endprocessing, e.g., -1013.-mmoduleImports the module before executing the script .module may be followed by an equals sign and acomma-separated l ist of i tems.

    -MmoduleSame as -m, but with more tr ickery.

    - n Assum es an input loo p aro un d the script. Lines arenot printed.

    Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    8/74

    - p Assum es an inpu t lo op aro un d the script . Lines areprinted.- P Runs the C pre pro cess or on the scr ipt before co m pilation by Perl.

    - s In terprets - x x x on the com m and l ine as a sw i tchand sets the corresponding variable Sxxx in thescript.

    -S Uses the PATH env ironm ent variable to sea rch forthe script .- T Tu rns on taint checking,- u D um ps core after com pil ing the scr ipt . To b e usedwith the untittmpQ.) program (w here avai lable).

    Obsoleted.- U Allow s Perl to perform unsafe op era tion s.- v Prints the version and patch level of your Perlexecutab le .-VI war \Prints Perl configuration information, like-V:man.dir .- w Prints w arning s about possible spell ing errors andother error-prone constructs in the script .- x [ dir ] Extracts the script from the input stream. If dir isspecified, Perl sw itche s to this dire ctory befo re running the script .- 0 | vol J

    (That 's the number zero.) Designates an init ial valuefor the record separator $/ . See also -I .SyntaxPerl is a free-format programming language. This means thatin general, i t does not matter how a Perl program is writ tenwith regard to indentation and lines.

    Syntax

  • 7/28/2019 Perl 5 Pocket Reference

    9/74

    An exc eptio n to this rule is w he n the Perl com piler en co un ters a sharp or pound symbol (#) in the input: it then discardsthis symbol and everything following it up to the end of thecurrent input line. This can be used to put comments in Perlprograms. Real programmers put lots of useful comments intheir programs.Th ere are places w her e w hitespace doe s matter : w ithin literaltexts, patterns, and formats.If the Perl co m piler en co un ters the special tok en EN D , itdiscards this symbol and stops reading input. Anything follow ing this tok en is ignored b y the Perl com piler, bu t can beread by the program w he n it is run.When Perl is expecting a new statement and encounters aline that starts w ith =, it skip s all inpu t up to an d inclu ding aline mat starts w ith =cut. This is used to embed programdocumenta t ion .Embedded DocumentationTools exist to extract embedded documentat ion and generateinput suitable for several formatters like troff, iATfcX, andHTML. The following commands can be used to controlembedded documenta t ion :=back See =ov er.=begin FMTSubsequent text up to a matching =end is onlyincluded w he n p rocesse d for formatter FMT.=cut Ends a document sect ion.=end FMTSee =begin.=for FMTThe next paragraph is only included w he n pro cessed for formatter FMT.

    Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    10/74

    = head l headingProduces a first-level heading.=head2 headingProduces a second-level heading.

    =item textSee =over.=over N

    Starts an enumeration with indent N. Items are speci f ied using =item. The enumeration is ended with=back.=p od Introdu ces a do cu m en t section . Any of the

    s-commands can be used to introduce a documentsect ion.These commands apply to the paragraph of text that followsthem; paragraphs are terminated by at least one empty l ine.An indented paragraph is considered to be verbatim text andwil l be rendered as such.Within normal paragraphs, markup sequences can beinser ted:B

  • 7/28/2019 Perl 5 Pocket Reference

    11/74

    XAn index entry.Z A zero-width character.

    Data TypesArray Inde xa ble list of scalar valu esH ash Associative list of scalar va lue sScalar Strings, nu m be rs, and references

    Literal ValuesArray ( 1 , 2, 3) is a list of three ele m en ts.

    (1 . 2, 3)[0] is the first element from this list,( 1 , 2 , 3)[- l] the last e lement.( ) is an em pty list .(1..4) is the same as (1,2,3,4),l ikewise ( 'a ' . . 'z ' ) .( ' a ' ' z ' ) [4 ,7 ,9] is a slice of a list literal.qw /foo ba r . . . / is the sam e as ( ' f o o ' , ' b a r ' , . . . ) .

    Array reference[1,2,3]

    Array reference wi th named indices (pseudo-hash)[(field1 => l,field2 => 2. . . . J]

    Boolean Perl has no boolean data type. Anything that isundefined or evaluates to the null string, the numberzero, or the string "0" is considered false, everythingelse is true (including strings like "00"!).Code referencesub { statements)Filehandles

    STDIN. STDOIJT. STDERR, ARGV, DATA.User-specified: handle, $var.

    Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    12/74

    Globs evaluates to all filenames according to thepattern. Use or glob $var 10 glob from avariable.

    Hash (associative list)(keyl, vail, key2, val2,...)Also (.keyl => vail, key>2 => val2, . . .)

    Hash reference{keyl, vall^key2, val2,...}Here-ls identifierShell-style "here document." See the Perl documentation for details.

    Num er i c123 1_234 123.4 5 E -I 0 Oxff (hex) 0377 (octa l)

    Regular Expressionf\rfstring/modifiersSee the section "Regular Expressions" for details.

    Special tokensFILE : filenam e; LIN E : line nu m be r;PACK AGE : curren t pac kag e;EN D : en d of program; rem aining l ines can beread using the filehandle DATA.String' a b c 'Literal string, no variable interpolation or escapecharacters , exc ept V a n d \ \ . Also: q /a bc / . Almostany pair of delimiters can be used instead of/.../.' a b c "Variables arc interpolated and escape sequences areprocessed. Also: qq/abc/ .Escape sequ en ces : \ t (Tab), \n (Newl ine ) ,\ r (Re turn), \f (Formfeed), \ b (Ba cksp ace),\a (Alarm), \ e (Escape ) . \0 3 3 (octal) , \ x l b (hex) ,\c( (control) .

    \ l an d \u lo w erca se/up perc ase the fol low ing character. \L and \U low erca se/up perc ase until a \E is

    Literal Values

  • 7/28/2019 Perl 5 Pocket Reference

    13/74

    enc ou ntered . \ Q qu otes non-w ord characters until a\E is encountered."command"Evaluates to the output of the command. Also:qx/command/.

    Variables$var A sim ple scalar variable.$var[27]

    28th element of array @var.$p = \@var

    N ow Sp is a reference to array @var.$ $ p [ 2 7 ] 28th element of array referenced by $p.

    Also, $p->(27] .$ v a r l - l ]

    Last element of array @var.$var l$ i | [$ j ]

    Sj-th element of $i-th element of array @var.$var{ ' Feb'}A value from hash %var.

    $p = \% varN ow $p is a reference to hash % var.

    $ $ p ( ' F e b ' |A value from hash referenced by $p .Also. $ p - > { ' F e b ' J .

    $var Last index of array @var.@var The entire array; in scalar context, the number of

    elements in die array.@var[ 3,4,51A slice of array var. varJ ' aV b ' JA slice of %var; same as ($var{ ' a ' },$var{' b ' } ) .

    Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    14/74

    %var The entire hash; in scalar context, true if the hashhas e lements .$ v a r ( ' a ' , l , . . . )Emulates a multidimensional l ist (deprecated).

    Sc = \&mysubN ow $c is a reference to subroutine mysub.

    $ c - > ( orgs)Calls the subroutine via the reference.l>kg::var A va riab le from a pa ck ag e, e.g., $pkg::var, @pkg::ary.

    \tbingie Reference to a thingie, e.g., \Svar, \% hash .'name Refers to all thingies represented by name.*nl = *n2 makes all nl aliases for n2.*nl =\$n2 makes the package var iable $nl an al ias

    f o r $n2 .You can alw ays use a block (see the section "Statements")returning the right type of reference instead of the variableidentifier, e.g., $( . . . ) . 8t{...}. $$p is just a shorthand for ${$p}.ContextBoolean A spe cial form of scalar contex t in w hich it only

    matters if the result is true or false.List A list va lue or an array is ex p ec te d .Scalar A single scalar valu e is ex pe cte d.Void N o va lue is ex pe cte d. If a value is pro vid ed , it isdiscarded.The follow ing functions relate to context:scalar exprForces scalar context for the expression.wantarrayReturns true if the current context expects a listvalue, undef in void context.

    Context

    http://tbingie/http://tbingie/http://svar/http://svar/http://tbingie/
  • 7/28/2019 Perl 5 Pocket Reference

    15/74

    O perators an d PrecedencePerl op era tor s hav e th e follow ing associativity and pr ec ede nc e, l isted from highest prec ed en ce to low est.Assoc.leftleft

    rightrightrightrightleftleftleftleftleft

    leftleftleftleft

    right

    Opera torsterms andlist operators->++*\t+ -

    \-* / % X

    + - . named unaryoperatorstt gt le ge== != eq ne emp&1 *&&II

    >

    DescriptionSee be low .Infix dereference operator.Auto-increment (magical on strings).Auto-decrement.Exponentiat ion.Reference to an object (unary).Unary negation, bi tw ise com plem ent.Unary plus, minus.Binds a scalar expression to a patternmatch.Same, but negates the result.Multiplication, division, modulo,repetit ion.Addition, subtraction, concatenation.Bitw ise shift right, b itw ise shift left.e.g., sin. chdir. -f. -M.Numerical relational operators.String relational operators.Numerical equal , not equal , compare .Str ingwise equal, not equal, compare.Compare operators return -1 (less),0 (equ al), or 1 (greater).Bitwise AND.Bitwise OR, exclusive OR.Logical AND.Logical OR.In scalar context, ninge operator .In list context, enumeration.Alternative range operator.Conditional (if ? then : else) o perator .

    10 I'erl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    16/74

    Assoc.rightleftleft

    rightleftleft

    Opera tors= += -= e tc .=>l ist operators(r ightward)notandor xor

    DescriptionAssignment operators .Comma operator, also list elementseparator.Same, enforces the left operand to hea string.See be low .Low precedence logical NOT.Low precedence logical AND.Low precedence logical OR. exclusiveOK .

    Parentheses can be used to group an expression into a term.A list consists of expressions, variables, or lists, separated bycom m as. An array variable or an array slice may alw ays b eused instead of (or as part of) a list.Perl functions mat can be used as list operators have eithervery h igh or very low precede nce , de pe nd ing on w hetheryou look at the left side of the operator or at the right side ofthe operator . Parentheses can be added around the parameterl is ts to avoid precedence problems.The logical operators do not evaluate the right operand if theresult is alread y k no w n after evaluation of the left o p er an d.StatementsA statem ent is an exp ression , optionally follow ed by a modifier, an d term inated w ith a sem icolon . Statements can becombined to form a block w hen enc losed in {}. The semi colon may be omitted after the last statement of the block.

    Statetnents 11

  • 7/28/2019 Perl 5 Pocket Reference

    17/74

    Execution of expressions can depend on other expressionsusing one of the modifiers if, unless, for, foreach, while, or until,e.g.:

    exprl if e.xprj;exprl foreach list;exprl until expr2:The logical operators I I, &&, or?: a lso al low condit ionalexecution:

    exprl | | exfirJ;ex/>rl ? e.xprj: exprj;blocks may be used to control flow:

    if ( expr) block 11 elsif (iwpn block...] else block Iunless ( cxpr) block I else block ][ laM: I while ( expr) block I continue block II label. I until ( expr) block I continue block]I label. I for ( [ expr I; I expr 1 ; I expr I ) blockI to/*'/, i foreach mrf ( /is/) Woe*I label ] block I continue Woe* I

    for and foreach can be used interchangeably.Program flow can be controlled with:goto labelFinds the statement labeled w ith label and resumesexecution there, label may be an expression that

    evaluates to the name of a label,last I label ]

    Immediately exits the loop in question. Skips thecontinue block.

    12 P erl 5 P ocket Keferettce

  • 7/28/2019 Perl 5 Pocket Reference

    18/74

    next [ label ]Executes the continue block and starts the next i terat ion of the loop.

    redo [ label ]Restar ts the lo op block w i thout evaluat ing the cond i tional again. Skips the continue block.Special forms are:

    do Woe* while expr;do Wot* until expr:w hich are gu aran teed to perform block once before test ingexpr, an d

    do blockw hich effectively turns block into an expression.Su brou tines, Packages, and Modu les^subroutine listExecutes a subroutine declared by a sub declaration,

    and returns the value of the last expressionevaluated in subroutine, subroutine can be anexpression yielding a reference to a code object .The & may be omit ted i f the subrout ine has beendeclared before being used, or the list isparenthes ized.bless ref[ , classname ]

    Turns the object refimo an object in classname.Returns the reference.caller I expr ]Returns a list (Spackage, $file, $line. ...) for a specific subroutine call, caller returns this informationfor the current subroutine, caller(l) for the caller ofthis subrout ine , etc. Returns false if no caller.

    Su brou tines, Packages, and Modu les 13

  • 7/28/2019 Perl 5 Pocket Reference

    19/74

    do su brou tine listDeprecated form of Iksubroutine.goto iksubroutineSubstitutes a call to subroutine for the currentsubroutine.import module [ [ version ] list 1Imports the named items from module.

    no module \ list 1Cancels imported semantics. See use.package ( namespace 1Designates the remainder of the current block as apackage with a namespace, or without one ifnamespace is omitted.prototype functionReairns the prototype of the function as a string, orundef if the function has no prototype.require expr\If expr is numeric, requires Perl to be at least thatversion. Otherwise expr musi be the name of a filethat is included from the Perl library. Does not

    include more than once, and yields a fatal error ifdie file does not evaluate to a true value. If expr is abare word, assumes extension .pm for the name ofthe file. This form of module loading does not riskaltering your namespace.return ( expr )Returns from a subroutine w ith the value specified;if no value, returns undef in scalar context and anempty list in list context.sub I name I [ {prolog ] blockDesignates name as a subroutine. Parameters arc-passed by reference as array @_. Returns the valueof the last expression evaluated, proto can be used

    to define the required parameters. Without a block itis just a forw ard declaration, w ithout the name it isan anonymous subroutine.

    /4 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    20/74

    I sub ) BEGIN blockDefines a setup block to be cal led before execution.I sub ] END blockDefines a c leanup block to be cal led upontermination.

    [ sub ) IN1T blockDefines an initialization block to be called after compilat ion, just before execut ion,use module ( [ v ersion ] list ]Loads the named module into the current package a tcompile t ime.

    Object-Oriented ProgrammingPerl rules of object-oriented programming are as fol lows: An ob ject is simply a referenc e that ha ppe ns t o knoww hich class it be lon gs to. Ob jects are blessed , reference sare not . A class is simply a pac kag e that h ap p en s to pro vid e m etho d s to dea l w ith object re ferenc es. If a pa ck ag e fails toprovide a method, the base classes as l isted in ISA aresea rched . A m eth od is simply a sub rou tine that exp ects an objectreference (or a package name, for stat ic methods) as thefirst argument.

    M ethods can b e called w i th:ohjtvf> method parameters ormethod ohjrefparameters

    Object-Oriented Program ming 15

  • 7/28/2019 Perl 5 Pocket Reference

    21/74

    Standard MethodsThe package UNIVERSAL contains methods that are automatically inherited by all other classes:can methodReturns a reference to the method if its object has it,

    undef otherwise ,isa class Returns true if its object is blessed into a subclass of

    class.VERSION [ need IReturns the version of the class. Checks the versionif need is supplied.Pragmatic ModulesPragmatic modules affect die compilat ion of your program.Pragmatic mo du les can be activated ( imp orted) w ith use an ddeact ivated w ith no. T he se are usually block scop ed.attrs attributes

    Sets/gets attributes of a subroutine,use attrs "method" indicates that the invoking subroutine is a method.use attrs "locked" protects the invoking subroutineagainst concurrent access.autouse modsEach of the named modules will not be loaded untilone of its functions is called.base classesEstablishes an IS-A relat ionship with the base classes

    at compile t ime,blib [ dir ]Uses MakeMaker 's uninstaller! version of a package.

    dir defaults to the current director) ' .

    16 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    22/74

    constant name => valuePragma to declare constants.diagnostics [ -verbose ]Forces verbose warning diagnostics and suppressduplicate w arnings.fields namesImplements compile-time class fields using pseudo-hashes.integer Computes arithmetic in integer instead of doubleprecision,less whatRequests less of something from the compiler(unimplemented).lib namesAdds libraries to @INC, or remove them,locale Uses and avoids POSIX locales for built-in opera-lions,ops operationsRestricts unsafe operations w hen compiling,overload operator => subrefPackages for overloading Perl operators, operator isthe operator (as a string), subrefA reference to thesubroutine handling the overloaded operator.Example: use overload "+" => \&my_add;re behaviorsAlters regular expression behavior.use re "eval" allows zero-width code evaluationassertions (see the section "Regular Expressions").use re "taint" propagates tainting,

    sigtrap infoEnables simple signal handling.Example: use sigtrap qw(SEGV TRAP);

    Pragmatic Modules 17

  • 7/28/2019 Perl 5 Pocket Reference

    23/74

    strict [ constructs ]Restricts unsafe constructs,use strict "refs" restricts the use of symbolicreferences.use strict "vars" requires all variables to be eithermy or fully qualified.use strict "subs" restricts the use of barew ord identifiers that are not subroutines.Without constructs, affects all of them.subs namesPredeclares subroutine names, allowing you to usethem without parentheses even before they aredeclared.Example: use subs qw (ding dong);

    vars namesPredeclares variable names, allow ing you to usethem under the strict pragma.Example: use vars qw ($foo bar);vmsish [ features \Controls VMS-specific language features. VMS only.

    use vmsish "exit" enables VMS-style exit codes.use vmsish "status" allows system commands todeliver VMS-style exit codes to the calling program.use vmsish "time" makes all limes relative to thelocal time zone.W ithou t featu res, affects all of them.Arithmetic Functionsabs exprf Returns the absolute value of its operand.atan2 y, x Returns the arctangent of y/x in the range -n to it.cos expr\ Returns the cosine of expr (expressed in radians),exp expri Returns e to the pow er of expr.int expr] Returns the integer portion of expr.

    18 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    24/74

    log exprf Returns the natural logarithm (base e) of expr.rand I expr ]Returns a random fractional num ber betw een 0(inclusive) and the value of expr (exclusive). Ifexpr is omitted, defaults to 1.sin exprf Returns the sine of expr (expressed in radians),sqrt exprf Returns the square rool of expr.srand I expr ]Sets the random number seed for the rand

    operator,time Returns the number of non-leap seconds sincew hatever time the system considers to be theepoch. Suitable for feeding to gmtime and

    localtime.Conversion Functionschr expr\Returns the character represented by the decimalvalue expr.gmtime I expr ]In list context, converts a lime as returned by thetime function to a 9-elemenl list (0:$sec\ l:$min,2:$hour, 3:$mday, 4:$mon, 5:$year, 6:$w day,7:$yday, 8:$isdst) with the time localized for thestandard Greenwich time zone.In scalar context, converts it to print format.$mon has the range 0 (January) .. 11 (December)and $wday has the range 0 (Sunday) .. 6 (Saturday).expr defaults to the current time,hex exprfReturns the decimal value of expr interpreted as ahex siring,localtime I expr ]Like gmtime, but w ith the time localized for the localtime zone.Conversion Functions 19

  • 7/28/2019 Perl 5 Pocket Reference

    25/74

    oct expr\Returns the decimal value of expr interpreted as anoctal string. If expr starts off w ith Ox, interprets it asa hex string instead.ord expr\Returns the ASCII value of the first character of expr.vec expr, offset, bitsTreats string expr as a vector of unsigned integers ofbits bits each, and yields the decimal value of theelement at offset, bits must be a pow er of 2 betw een1 and 32. May be assigned to.

    Structure Conversionpack template, listPacks the values in list into a binary structure usingtemplate. Returns a string containing the structure.unpack template, exprUnpacks the structure expr into a list, using template.template is a sequence of characters as follows:

    ASCII string, null- / space-paddedBit string in ascending / descending orderSigned / unsigned char valueSingle / double float in native formatHex string, low / high nybble firstSigned / unsigned integer valueSigned / unsigned long valueShort / long in netw ork (big endian) byte orderSigned / unsigned short valueUuencoded string / pointer to a stringPointer to a structure (fixed-length string)Short / long in VAX (little endian) byte orderA BER compressed integerN ull byte / null fill until positionBack up a byte

    20 Perl 5 Pocket Reference

    abcfhi1nsuPVwXX

    ////////////

    ABCdHILNSPV

  • 7/28/2019 Perl 5 Pocket Reference

    26/74

    Each character may be fol lowed by a decimal number thaiwill be used as a repeat count: an asterisk (*) specifies allremaining arguments. If the format i s preceded wi th %n,unpack returns an H-bit checksum instead, n defaults to 16.Whiiespace may be included in the template for readability.

    String Functionschomp fe/fRemoves line endings from all elements of the list ;returns the (total) number of characters removed.chop Iist\C hops off' the last character on all elements of thel ist ; returns the last chopped character.crypt plaintext, saltEncrypts a string (irreversibly).eval expr\

    expr is pa rse d an d exec uted as if it w er e a Perl p ro gram. The value returned is the value of the lastexpression evaluated. If there is a syntax error orruntime error, undef is returned by eval, and $@ is setto the error message. See also eval in the section"Miscellaneous."

    index sir, substr [ , offset I , replacement ] ]Returns die posit ion of substr in str ai or after offset.Replaces the found substring by the replacementtext if specified. If the substring is not found,re turns - 1 .Ic exprf Returns a low ercase version of expr.Icfirst e\pr\Returns expr w i t h iis first character in low ercase .length expr\Returns the length in bytes of expr.quotemeta expr\Returns expr w ith all regular exp ressio n m etacharac ters quoted.

    String Fu nctions 21

  • 7/28/2019 Perl 5 Pocket Reference

    27/74

    rindex sir, substr I , offset |Returns the position of the last substr in sir at orbefore offset.substr expr, qffsel I , leu 1Extracts a substring of length ten starting at qffsel outof expr and returns it. If offset is negative, countsfrom the end of the string. If len is negative, leavesthat many characters off the end of the string. Maybe assigned to.uc expr\ Returns an uppercase version of expr.ucfirst expr]Returns expr w ith its first character in uppercase.

    Array and Hash Functionsdelete %basb\key\delete @bash\keyl, key2, ...JDeletes the specified value(s) from the specifiedhash. Returns the deleted value(s) (unless basb istied to a package that does not support this).each %basbReturns a 2-element list consisting of the key andvalue for the next value of the hash. Entries arereturned in an apparently random order. After allvalues of the hash have been returned, an empty lislis returned. The next call to each after that will start

    iterating again.A call to keys or values w ill reset the iteration.exists exprChecks if the specified hash key exists in this hash.grep e\pr, listgrep block lisl

    Evaluates expr or block for each element of the list,locally setting $_ to refer to the element. Modifying$_ will modify the corresponding element from list.

    Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    28/74

    In list context, returns die list of elements from listfor which expr returned true. In scalar context,returns the number of such elements.join expr, listJoins the separate strings of list into a single stringwith fields separated by the value of expr, andreturns the string.

    keys %hashIn list context, returns a list of all the keys of thenamed hash. In scalar context, returns the number ofelements of the hash.map exf>r, listmap block listEvaluates expr or block for each element of the list,locally setting $_ to refer to the element. ModifyingS_ will modify the corresponding element from list.Returns the list of results.pop [ array ]Pops off and returns the last value of the array. Ifarray is omitted, pops @ARGV or _ depending

    on the current lexical scope.push array, listPushes the values of the list onto the end of thearray. Returns the new length of the array.reverse listIn list context, returns the list in reverse order.In scalar context, concatenates the list elements andreturns the reverse of the resulting string.scalar arrayReturns the number of elements in the array.scalar %basbReturns a true value if the hash has elementsdenned.

    Array and Hash Functions 23

  • 7/28/2019 Perl 5 Pocket Reference

    29/74

    shift I array IShifts the first value of the array off and returns it,shortening the array by 1 and moving everythingdown. If array is omitted, shifts @ARGV or _depending on the current lexical scope.

    sort [ subroutine ] listSorts the list and returns the sorted list value, subroutine, if specified, must return less than zero,zero, or greater dian zero, depending on how theelements of the list (available to the routine as package global variables $a and $b) are to be ordered.subroutine may be (a variable containing) the nameof a user-defined routine, or a block.splice array, offset [, length [ , list ] ]

    Removes the elements of array designated by offset and length, and replaces them with list (if specified). Returns the elements removed. If offset is negative, counts from the end of the array.split I pattern [ , expr\ [ , limit ] 1 ]Splits expr (a string) into a list of strings, and returnsit. If limit is specified, splits into at most that numberof fields. If pattern is omitted, splits at thew hitespace (after skipping any leading w hitespace).If not in list context, returns the num ber of fieldsand splits to @_. See also the section "Search andReplace Functions."unshift array, list

    Prepends list to the front of the array, and returnsdie number of elements in the new array.values %hashReturns a list consisting of all the values of dienamed hash.

    Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    30/74

    Regular ExpressionsKach character matches itself, unless it is one of the specialcharacters + ? . * * $ ( ) [ ] ( ) IV The special meaning of thesecharacters can be escaped using a \ .Matches an arbitrary character, but not a ne w lineunless the s modifier is used (see m//s in section"Search and Replace Functions").

    ( . . . ) G ro up s a series of pattern elem ents to a single element .Matches the beginning of the target. In multilinem od e (se e m //m in sect ion "Search and ReplaceFunctions") also m atches after every n ew linecharacter .

    $ M atches the e n d of the line, or before a final ne w -line character . In multi l ine mode also matchesbefore every ne w line character .[ . . . J Denotes a class of characters to match. ("...] negatesthe class.C..I. . . I . . . )

    Matches one of the alternatives.(?# text} Comment .(?: regex)Like {regex) but does not make back-references .Modifiers may b e pla ced be tw ee n the ? and :( see ? modifier, later in this list).(?= regex)

    Zero-width posit ive look-ahead assertion.(?! regex)

    Zero-width negative look-ahead assertion.(?< regex)

    Zero-w idth posit ive look-b ehind asser t ion.(?

    Regu lar Expressions 25

  • 7/28/2019 Perl 5 Pocket Reference

    31/74

    (?l code))Executes Perl code w hile matching. Alw ays succeedsw ith zero w idth.Requires the re "eval" pragma.(?> regex)Anchored subpattem.O(.cond)ptrue [ I pfalse ] )Selects a pattern depending on the condition, condshould be the number of a parenthesised subpattem, or one of the zero-width look-ahead, look-behind and evaluate assertions.0 modifier)Embedded pattern-match modifier, modifier can beone or more of i, m, s, orx. Modifiers can beswitched off by preceding the letter(s) with a minussign.

    Quantified subpatterns match as many times as possible.When followed with a ? they match the minimum number oftimes. These are the quantifiers:+ Matches the preceding pattern element one or moretimes.? Matches zero or one times.

    * Matches zero or more times.{,) Denotes the minimum n and maximum m matchcount. (} means exactly n times; {,) means at leastn times.A \ escapes any special meaning of the following character ifnon-alphanumeric, but it turns most alphanumeric charactersinto something special:\w Matches alphanumeric, including _, \W matchesnon-alphanumeric.\s Matches w hitespace, \S matches non-w hitespace.\d Matches digits, \D matches non-digits.

    36 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    32/74

    \A M atches the beginning of the string.\Z M atches the en d of the string, or before a new line atthe end .\z M atches the e n d of the string.\b M atches w ord bound ar ies , \B matches

    non-boundar ies .\G M atches w he re the prev ious m // g searc h left off.\t, \ n , V, \f,\a , \ e , \OXY. \xX Y. \c,Y, \I . \u , \L . \U, \E an d \Qhavre their usual meaning, see "String" in the section

    "Literal Values."\w , \\V , \ s , \S, \d , and \DThese may be used within character classes, but \bdenotes a backspace in this context .Back-references:\ 1 . . .\9 Refer to m atc he d subexpressions, g rouped w i th ( ).

    inside the match.\10 and upCan also be used if the pattern matches that manysubexpress ions .See also $1. . .$9. S+. $&. $ \ and $ ' in the section "SpecialVariables."With modifier x, w hitesp ace and com m ents can be use d inthe patterns for readabil i ty purposes.Search and Replace FunctionsIf the right hand side of the =~ o r !* is an expression ratherthan a search pattern, substi tut ion, or transliteration, it isinterpreted as a search pattern at runtime.I expr =" ] [ m ] /pattern/ [ g [ c ] | ( i ) [ m J | o | [ s ] [ x lSearches expr (default: $_) for a pattern.If you prepend an m you can use almost any pair of

    delimiters instead of the slashes.

    Search ana" Replace Fu nctions 27

  • 7/28/2019 Perl 5 Pocket Reference

    33/74

    For =~, its negation P may be used, which is truew hen =~ w ould return a false result.If used in list context, a list is returned consisting ofthe subexpressions matched by the parentheses inthe pattern, i.e., ($!, $2, $3,...).Optional modifiers: c prepares for continuation; gmatches as many times as possible; i searches in acase-insensitive manner; o interpolates variablesonly once, m treats the string as multiple lines; streats the string as a single line; x allow s for regularexpression extensions.If pattern is empty, the most recent pattern from aprevious successful match or replacement is used.With g, the match can be used as an iterator inscalar context.?pattem?This is just like the /pattern/ search, except that itmatches only once betw een calls to the resetoperator.I $ v ar =' I s/pattern/newtext/ [ e ] [ g ] [ i ] ( m ) | o ] ( s ) [ x ]Searches the string v ar (default $_) for a pattern, andif found, replaces that part with the replacementtext. It reairns the number of substitutions made, ifany; if no substitutions are m ade, it returns false.Optional modifiers: g replaces all occurrences of thepattern; e evaluates the replacement string as a Perlexpression; for the other modifiers, see /pattern/matching.Almost any delimiter may replace the slashes; ifsingle quotes are used, no interpolation is done onstrings betw een the delimiters. Otherw ise, stringsare interpolated as if in double quotes.If bracketing delimiters are used, pattern andnetvtext may have their ow n delimiters, e.g.,s(foo)tbar).

    Jfi Peri 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    34/74

    If pattern is empty, the most recent pattern from aprevious successful match or replacement is used.[ %var = ' | Xt/searcblist/refilacementlistf [ c ] [ d ] ( s 1Transliterates all occurrences of the characters foundin the search l ist into the corresponding character inthe replacement l ist . I t returns the number of characters replaced, y may be used instead of tr.Optional modifiers: c complements the searcblist;

    d deletes all characters found in searcblist that donot have a corresponding character inreplacetneutlist; s squeezes a l l sequences of characters that are translated into the same target characterinto one occurrence of this character.

    pos scahtr\Returns the posi t ion w he re the last m //g search leftoff for scalar. May be assigned to.

    qtistrinfif modifiersCompiles the string as a pat tern and returns thecompiled pattern as a scalar value.study SuariStudies the scalar variable $varin anticipation of

    performing many pattern matches on i ts contentsbefore the variable is next modified.File Test OperatorsThese unary opera tors t ake one argument, ei th er a filenameor a filehandle, and test the associated file to see if somethingis true about it. If the argument is omitted, they test $_(exc ept for - t , w hich tests STDIN ). If the special argu m ent _(underscore) i s passed, they use die information from thepreceding test orstat call.- r - w - x

    File is readable/writabie/executable by effectiveuid/gid .

    File Test Operators 29

  • 7/28/2019 Perl 5 Pocket Reference

    35/74

    - o- e- s- f-1

    - b- u

    -O- z- d-S

    - c-8

    R-W-XFile is readable/writable/exeeutable by real uid/gid.File is ow ned by effective/real uid.File exists/has zero size.File exists and has non-zero size. Returns the size.File is a plain file/a directory.

    PFile is a symbolic link/a socket/a named pipe(FIFO).File is a block/character special file,-kFile has setuid/setgid/stieky bit set.- t Tests if filehandle (STDIN by default) is opened to aity.-T -B File is a text/non-text (binary) file. -T and -B returntrue on a null file, or a file at EOF w hen testing afilehandle.-M -A -CFile modifieation/access/inode-change time. Measured in days. Value returned reflects the file age atthe time the script started. See also $*T in the section "Special Variables."

    File OperationsFunctions operating on a list of files return the number offiles successfully operated upon.chmod listChanges the permissions of a list of files. The firstelement of the list must be the numerical mode inoctal, e.g., 0644.chown list

    Changes the ow ner and group of a list of files. Thefirst tw o elements of the list must be the numericaluid and gid. If gid is - 1 , the group is not changed.

    jO Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    36/74

    link oldfile, neufileC reates a n e w filename linked to the old filename.Istat file Like slat, but if the last component of the filename isa symbolic link, stats the link instead of the file illinks to.

    mkdir dir, permCreates a directory w ith given perm issions, e.g. ,0755.

    readlink expr\Returns the value of a symbolic link,

    rename olduame. newnameChanges die name of a file,

    rmdir filename^Deletes the directory if it is empty,stat file Returns a 13-element l ist (0:$dev, l :$ino, 2:$mode.3:$nlink. 4:$uid, 5:Sgid, 6:$rdev, 7:$size, 8:$atime,9:$mtime, 10:$ciime, l l :$blksize, IZiSblocks)../*/?can be a filehandle, an expression evaluating to afilename, o r _ to refer to the last file test o pe ra tio nor stat call. Returns an empty list if die stat fails.Use the standard module File::stat for easy access tothis information,

    symlink oldfile. neufileCreates a new filename symbolically linked to theold filename,

    truncate file, sizeTruncates file to size, file may be a filename or afilehandle.

    unlink lisi-fDeletes a list of files,

    utime list Changes the access and modification times. The firsttw o elem en ts of the list m ust be the num ericalaccess and modification limes.The inode change t ime wil l be set to the currentl ime.

    File O(terations 31

  • 7/28/2019 Perl 5 Pocket Reference

    37/74

    Input /OutputIn input/output operations, filehandle may be a filehandle asopened by the open operator, a predefined filehandle (e.g.,STDOUT) or a scalar variable that evaluates to a reference toor the name of a filehandle to be used.In scalar context, reads a single line from the file

    opened on filehandle. In list context, reads the restof the file. Reads from the input stream formed by the filesspecified in @ARGV, or standard input if no arguments were supplied.binmode filehandle

    Arranges for the file opened on filehandle to be reador written in binary mode as opposed to text mode(null operation on Unix or Mac).close I filehandle ]Closes the file or pipe associated with the filehandle.Resets $.. If ilehandle s omitted, closes the currently selected filehandle.dbmclose %bashDeprecated, use untie instead.dbmopen %basb, dbmnattte, modeDeprecated, use tie instead.eof filehandleReturns true if the next read will return end of file, orif the file is not open.eof Returns the EOF status for the last file read.eof() Indicates EOF on the pseudo-file formed of the fileslisted on the command line.fcntl filehandle, fu nction, %uarImplements the/cf/(2) function. This function has

    nonstandard return values.

    }2 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    38/74

    fileno filehandleReturns die fi le descriptor for a given (open)filehandle.

    (lock filehandle. operationCalls a system-dependent locking routine on the fi le .operation formed b y addin g 1 (sh ared ), 2 (exclusive), 4 (non-blocking) or 8 (unlock).getc ( filehandle ]Yields the next character from the file, or an emptystring on end of fi le. If filehandle is omitted, readsfrom STDIN.ioctl filehandle, function, %varPerforms ioctOX) on the file. This function has nonstandard re turn values,open filehandle [ , filenatne ]Opens a file and associates i t with filehandle. Iffilename is omitted, the scalar variable of the samename as the filehandle must contain the fi lename.T he follow ing f ilename conven t ions apply w he nopening a fi le:

    "file" Opens file for input. Also "file" Opens file for output, creating it if

    necessary."filea

    Opens file i n append mode .a+

  • 7/28/2019 Perl 5 Pocket Reference

    39/74

    and I"Opens a pipe from command cmd, forks ifand is - .file may be &filehnd, in w hich ease the new file-handle is connected to the (previously opened)filehandle JiMmd. If it is &=n,fite will be connectedto the given file descriptor,open returns undef upon failure, true otherw ise.pipe readhandle, writehandleReturns a pair of connected pipes.print I fitehattdle 1 I list\ ]Prints the elemenis of list, converting them to stringsif needed. If ilehandle s omitted, prints by defaultto standard output (or to the last selected output

    channel; see select).printf I fitehattdle \\ list]Equivalent to print ilehandtespnnlt list.read filehandte, %var, length I, offset ]Reads length binary bytes from die file into the variable at offset. Returns number of bytes actually read,0 on eof, and undef on failure.readline exprInternal function that implements the operator.expr must be a typeglob.readpipe exprInternal function that implements the qx// operator.expr is executed as a system command,seek filehandte, [iosition, whenceArbitrarily positions the file. Returns true ifsuccessful,

    select 1 filehandte )Returns die currendy selected filehandle. Sets thecurrent default filehandle for output operations iffilehandle is supplied.

    3'i Per! 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    40/74

    select rbits, wbits, nbils, timeoutPerforms a selecKZ) system call w ith the sa m eparameters .

    sprintf format, listReturns a string resulting from formatting a (possiblyempty) list of values. See the section "FormattedPrinting" for a complete list of formal conversions.See the section "Formats" for an alternative way toobtain formatted output .

    sysopen filehandle, path, mode I , perms )Performs an ofwii(Z) system call. The possible values and flag bits of mode are sys tem-dependent ;they are available via the standard module Fcntl .sysread filehandle, $var, length I , offset ]

    Reads length bytes inlo Siwirat offset. Returns number of bytes actually read, 0 on eof, and undef onfailure.sysseek filehandle, position, w henceArbitrarily po sitio ns the file for us e w ith sysread an dsyswrite. See the Perl documentation for details onthe nonstandard return values of this function.syswrite filehandle, scalar, length | , offset 1Writes length bytes from scalar at offset.tell I filehandle )Returns the current file position for the file. Iffilehandle is omitted, assumes the file last read.

    Formatted Printingprintf a n d sprintf format a list of va lues accord ing to a fonnatstr ing that m a y u s e t h e fo l low ing conve r s ions :%% A percent s ign .% c T h e cha rac te r co r r e spond ing t o th e ordinal va lue .% d A s igned integer .

    Formatted Printing 35

  • 7/28/2019 Perl 5 Pocket Reference

    41/74

    %e A floating-point number (scientific notat ion) .%f A floating-point number (fixed decimal notation).%g A floating-point number (%e or %f notation).%i A synonym for %d.% n T he nu m be r of characters formatted so far is stored

    into the corresponding variable in the parameter l ist .%o An unsigned integer, in octal.% p A pointer (address in hexadecim al) .% s A string.%u An unsigned integer (decimal) .% x An unsign ed integer (hexa dec ima l) .%D An obsolete synonym for %ld.%E Like % e, but using an uppercase "E".%F An obsolete synonym for %f.%G Like % g, but wi th an uppercase "E" ( if applicable) .%0 An obsolete synonym for %lo.%U An obsolete synonym for %lu.%X Like % xT but using uppercase let ters.Th e follow ing f lags can be put betw een the % and the conver sion letter:space Prefix a posit ive number with a space.+ Prefix a positive number wi th a plus sign.

    Left-justify w ith in the field.0 U se ze ro es ins tead of sp ac es to right-justify.* Prefix a no n-z ero octal nu m be r w ith "0", an d a n on

    zero hex number with "Ox".number M inimum field w idth..number For a floating-point number: the number of digitsafter the decimal point.

    For a string: the maximum length.For an integer: the minimum wid th .

    36 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    42/74

    I Interpret integer as " ' long" or "unsigned long"according to the C type,h Interpret integer as "short" or "u nsigned sho rt"according to the C type.

    V Interpret integer according to Perl 's type.An asterisk (*) may be used instead of a number ; the valueof the next item in the list will be used.See the sec tion "Form ats" for an alternative w ay to ob tain format ted output .Formatsformline picture, list

    Formats list according to picture and accumula tes theresult into $"A.write I filehanclle IWrites a formatted record to the specified file, usingthe formal asso ciated w ith that file.Iffilehanclle is omit ted, the currently selected one is

    taken.Formats are defined as fol lows:format I name I =formlist

    fonnlist is a se q u en ce of l ines, each of w hich is ei ther a com ment l ine O in the first column), a picture line, or an argument l ine .A pictu re l ine contains the arg um en ts w hich w ill give va luesto the fields in the lines. Other text is output as given.Argument l ines contain lists of values that are output in theformat and order of the preceding picture l ine.name defaults to STDOIJT if omitted.

    Formats 37

  • 7/28/2019 Perl 5 Pocket Reference

    43/74

    Picture fields@ < . . .@ > . . .@l 1 1...#.##..,@>

    are:Left-adjusted field. Repeat the < to denotethe desired w idth.Right-adjusted fie ld.Centered field.Numeric format with implied decimal point.Multiline field.

    Use * instead of for multiline block filling.Use ~ in a picture line to suppress unw anted empty lines.Use ~" in a picture line to have this format line repeated untilall fields are exhausted.Set $- to zero to force a page break on the next write.See also $*, $", $"A, $"F, $-, and $= in the section 'SpecialVariables."Tying Variablestie var, ctassname, [ list )Ties a variable to a package class that will handle it.list is passed to the class constructor,tied v ar Returns a reference to the object underlying var, orundef if v ar is not tied to a package class,untie v ar Breaks the binding betw een the variable and thepackage class.A class implementing a tied scalar should define die methodsTIESCALAR, FETCH, STORE, and possibly DESTROY.A class implementing a tied ordinary array should define themetliods TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE,and perhaps DESTROY.

    38 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    44/74

    A class imp leme nt ing a lied hash sho uld define the m etho dsTIEHASH, FETCH, STORE, EXISTS, DELETE CLEAR. FIRSTKEY,NEXTKEY, and optionally DESTROY.A class im plem enting a tied filehandle should define them eth od s TIEHAN DLE, at least o n e of PRIN T. PRIN TF. WRITE,READLINE, GETC, READ, and possibly CLOSE and DESTROY.Several base classes to implement t ied variables are availablein the standard modules l ibrary.Directory Reading Rou tinesclosedir dirhandle

    Closes a director) ' opened by opendir.opendir dirhandle, dirnameOpens a di rectory on the handle specified,readdir dirhandleIn scalar context, returns the next entry from thedirectory or undef i f none remains.In list context, returns a list of all remaining entries

    from the directory,rewinddir dirhandlePositions the directory to the beginning,

    seekdir dirhandle, posSets position for readdir on the directory, pav shouldbe a file offset as returned by telldir.

    lelldir dirhandleReturns the position in the directory.System Interactionalarm exprSchedules a SIGALRM to be delivered after expr seconds. If expris 0, cancels a pending t imer.

    Sy stem In terac tion 39

  • 7/28/2019 Perl 5 Pocket Reference

    45/74

    chdir I expr )Changes the w orking directory. Uses $ENV{HOME)or SENVfLOGNAME} if expr is omitted.

    chroot filename^Changes the root directory for the process and itschildren.die [ list ]Prints the value of list to STDERR and exits w ith thecurrent value of $! (errno). If $ is 0, exits w ith thevalue of ($? 8). If ($? 8) is 0, exits w ith 255.list defaults to "Died". Inside aneval, the error message is stuffed into $@, and the evat is terminatedand returns undef; this makes die the way to raise anexception.exec ( program ] listExecutes the system command in list; does notreturn, program can be used to designate the program to execute command.exit [ expr ]Exits immediately w ith the value of expr, whichdefaults to 0 (zero). Calls END routines and objectdestructors before exiting.fork Does afork(2) system call. Returns the process ID ofthe child to the parent process (or undef on failure)and zero to the child process.getlogin Returns the current login name as know n by thesystem . If it returns false, use getpwuid.getpgrp ( pid ]Returns the process group for process pid (0, oromitted, means the current process).getppid Returns the process ID of the parent process.getprtority which, whoReturns the current priority for a process, process

    group, or user. Use getpriority 0,0 to designate thecurrent process.

    40 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    46/74

    glob pat Returns a list of filenames that match the shell pat tern pat.Kill list Sends a signal to a list of processes. The first element of the list must be the signal to send (eithernu m eric, or i ts na m e as a string). N egative signalskil l process groups instead of processes.

    setpgrp put. pgrpSets the process group for the piti (0 means the current process) .setpriority which, who, prioritySets the current priority for a process, processgroup, or a user .sleep I expr ]Causes the program to sleep for expr seconds , or

    forever if no expr. Returns the number of secondsactually slept.syscall listCalls the system call specified in the first element ofthe list, passing the rest of the list as arguments tothe call . Returns -1 on error.system | program J listDoes exactly the same thing as exec list except that afork is perfo rm ed first, and the parent p roc ess w aitsfor the child pro cess to com plete. Du ring the w ait,the signals SIGINT and SIGQU1T are passed to thechild process.

    Returns the exit status of the child process. 0 indicates success, not failure.program can be used to designate the program toexecute command.

    times Returns a 4-element l ist (0:$user, l :$system,2:$cuser, 3:$csystem) giving the user and systemtimes, in seconds, for tliis process and the childrenof this process.

    System Interaction 41

  • 7/28/2019 Perl 5 Pocket Reference

    47/74

    umask ( expr \Sets the umask for the process and returns the oldone. If expr is omitted, returns current umask value.wait Waits for a child process to terminate and returnsthe process ID of the deceased process (-1 if none).The status is returned in $?.

    waitpid pid, flagsPerforms the same function as the correspondingsystem call. Returns 1 when process pid is dead, --1 if nonexistent.warn I list \Prints list on STDERR like die, but doesn't exit, listdefaults to "Warning: something's w rong ".Networkingaccept newsocket, genericsockelAccepts a new socket,bind socket, nameBinds the name to the socket.connect socket, nameConnects the name to the socket,gelpeername socketReturns the socket address of the other end of the

    socket.getsockname socketReturns the name of the socket,getsockopt socket, level, optnameReturns the socket options,listen socket, queuesizeStarts listening on the specified socket, allowingqueuesize connections,

    recv socket, Svar, length, flagsReceives a message on socket of length bytes intoscalar variable Svar.42 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    48/74

    send socket, msg, flags {, to ]Sends a message on the socket.selsockopt socket, level, optname, optva lSets the requested socket opt ion ,

    shutdown socket, howShuts dow n a socket.

    socket socket, dom ain, type, protocolCreates a socket in domain wi th type and protocol

    socketpair socket!, socke!2 , dom ain, type, protocolWorks the same as socket, but creates a pair ofbidirect ional sockets.System VIPCDepending on your system configurat ion, certain system fi lesneed to be required to access the message- and semaphore-specific operat ion names.msgctl id, and, args

    Calls msgc(Kl). If cmd is &IPC_STAT then args mustbe a variable. See the Perl documentation for detailson the nonstandard return values of this function,msgget key,jlagsCreates a message queue for key. Returns the message queue identifier,

    msg rev id , $uar, size, type, flagsReceives a message from queue iV/into $var.

    msgsnd id, msg, flagsSends msg t o que u e id .semcll id. semnum, cmd, argCalls semctld). If cmd is &IPC.STAT or &GETALLthen arg must be a variable.

    semget key, nsems, size, flagsCreates a set of semaphores for key. Returns diemessage semaphore ident i f ier .

    System VIPC 43

  • 7/28/2019 Perl 5 Pocket Reference

    49/74

    semop key, . . .Performs semaphore operations,shmctl id, and, argCalls shmctKl). If and is &IPC_STAT then arg mustbe a scalar variable,

    shmget key, size, flagsCreates shared memory. Returns the shared memorysegment identifier,shmread id, $v ar, pos, sizeReads at most size bytes of die contents of sharedmemory segment id starting at offset pos into Svar.

    shmwrite id, string, pos, sizeWrites at most size bytes of siring into the contentsof shared memory segment id at offset pos.Miscellaneous

    defined exprTests whether the expr has an actual value.do filenameExecutes ilenameas a Perl script. See also require inthe section "Subroutines, Packages, and Modules."

    dump [ label ]Immediate core dump. When reincarnated, starts atlabel. Obsolete.eval ( expr, . . .)Executes the code betw een I and I. Traps runtimeerrors and returns as described with eva\(expr), inthe section "String Functions."local variableGives a temporary value to the named package variable, w hich lasts until the enclosing block, file, oreval exits.

    44 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    50/74

    my variableCreates a scope for the variable lexically local to theenclosing block, file, or eval.ref exf>r\ Returns a true value if expr is a reference. Returnsthe package name if expr has been blessed into apackage .reset I expr 1

    expr is a string of single letters. All variables beginning w ith o n e of tho se letters are reset to their prist ine state.If expr is om itted, re sets ?? searc hes so thai theywork again .Only affects the current package.

    undef lmlue\Undefines the lvalue. Always returns the undefinedvalue .Information from System DatabasesInformation About UsersIn scalar context, each of these routines returns a 10-elementlist :

  • 7/28/2019 Perl 5 Pocket Reference

    51/74

    getpwuid aidGets information by user ID.In scalar context, returns the username.setpwent Resets lookup processing.

    Information About GroupsIn list context, each of these routines returns a 4-element list:(0:$name, l:$passwd, 2:$gid, 3:$members).Smembers contains a space-separated list of the login namesof the group members.Use the standard module User::grent for easy access to thisinformation.endgrent

    Ends lookup processing.getgrent Gets next group information.In scalar context, returns the group name,getgrgid gidGets information by group ID.In scalar context, returns the group name,getgrnam nameGets information by name.In scalar context, returns the group ID.setgrent Resets lookup processing.Information About NetworksIn list context, each of these routines returns a 4-element list:(0:$name, l-.Saliases, 2:$addrtype, 3:$net).Use the standard module N et::netent for easy access to thisinformation.endnetentEnds lookup processing,getnetbyaddr addr, typeGets information by address and type.In scalar context, returns the netw ork name.

    46 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    52/74

    getnetbyname nameGets information by network name.In scalar context, returns the network number,getnetent Gets next netw ork information.In scalar context, returns the network name,setnetent stayopenResets lookup processing.Information About Network Hosts

    In list context, each of these routines returns a list of at least5 elements: (0:$name, l:$aliases, 2:$addrtype. 3:$length,4:Saddr [ , more addresses 1 ).Use the standard module Net::hostent for easy access to thisinformation.endhostentEnds lookup processing,gethostbyaddr addr, addrtypeGets information by IP address.In scalar context, returns the hostname,gethostbyname nameGets information by hostname.In scalar context, returns the host address,gethostentGets next host information.In scalar context, returns the hostname,sethostent stayopenResets lookup processing.Information About Network ServicesIn list context, each of these routines returns a 4-element list:(0:$name. l:$aliases, 2:$port, 3:$proto).Use the standard module Net::servent for easy access to thisinformation.

    Information A bou t Network Services 4 7

  • 7/28/2019 Perl 5 Pocket Reference

    53/74

    endserventEnds lookup processing,getservbyname name, protoGets information by service name.In scalar context, returns the port number,getservbyport port, protoGets information by service port.In scalar context, returns the service name,getserventGets next service information.In scalar context, returns the service name,

    setservent stayopenResets lookup processing.Information About Network ProtocolsIn list context, each of these routines returns a 3-element list:(0:$name, l:$aliases, 2:$proto).Use the standard module N et::protoent for easy access to thisinformation.endprotoentEnds lookup processing,getprotobyname nameGets information by protocol name.In scalar context, returns the protocol number,getprotobynumber numberGets information by protocol number.In scalar context, returns the protocol name,getprotoentGets next protocol information.In scalar context, returns the protocol name,setprotoent stayopenResets lookup processing.

    48 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    54/74

    Special VariablesThe al ternat ive names are provided by the s tandard moduleEnglish.Th e follow ing variables are global and sh ou ld b e localized insubrout ines:S_ Alternative: $ARG.

    The default input, output , and pat tern-searchingspace .S. Alternative: $INPUT_LINE_NTJMBER, SNR.Th e current input l ine n u m b er of the last filehandleread.S/ Alternative: $INPUT_RECORD_SEPARATOR, SRS.Th e input record sepa rator, ne w line by default . Maybe mult icharacter.S, Alternative: $OUTPUT_FIELD_SEPARATOR, SOFS.The output field separator for the print function.$" Alternative: SLIST_SF.PARATOR.The separator that joins elements of arrays interpolated in strings.$\ Alternative: $OUTPUT_RECORD_SEPARATOR,SORS.

    The output record separator for the print function.$* The output format for printed numbers. Deprecated.

    Use printf instead.$* Set to 1 to do mu ltiline m atching w ithin strings.

    Depreca ted ; see the m and s modifiers in the section"Search and Replace Functions."$? Alternative: $CHlLD_ERROR.The status returned by the last \ . . " command, p i p e

    close, wait, waitpid. or system function.$ 1 Alternative: $PERL_VERSION.

    The Perl version number, e.g.. 5.005.

    Special Variables 49

  • 7/28/2019 Perl 5 Pocket Reference

    55/74

    $[ The index of the first element in an array or list, andof the first character in a substring. Default is 0.Deprecated. Do not use.

    $; Alternative: SSUBSCRlPT_SEPARATOR, SSUBSEP.The subscript separator for multidimensional listemulation. Default is "\034".$! Alternative: $OS_ERROR, SERRNO.Used in a numeric context, yields the current valueof errno. Used in a suing context, yields the corresponding error string.5 Alternative: $EVAL_ERROR.The Perl error message from the last eval or do exprcommand.$: Alternative: $FORMAT_LINE_BREAK_CHARACTERS.The set of characters after which a string may bebroken to fill continuation fields (starting w ith *) ina format.$0 Alternative: SPROGRAM.NAME.The name of the file containing the Perl script beingexecuted. May be assigned to.$$ Alternative: SPROCESSJD, $PID.The process ID of the Perl interpreter running thisscript. Altered (in the child process) by fork.$< Alternative: $REAL_USER_ID, $UID.The real user ID of this process.$> Alternative: $EFFECnVE_USER_lD, $EU1D.

    The effective user ID of this process.$( Alternative: $REAL_GROUP_ID. SGID.The real group ID, or space-separated list of groupIDs, of this process.$) Alternative: $EFFECnVE_GROUP_!D, SEGID.The effective group ID. or space-separated list ofgroup IDs, of this process.$~A Alternative: $ACCUMULATOR.The accumulator for formline and write operations.

    50 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    56/74

    $'D Alternative: SDEBUGGING.The debug flags as passed to Perl using -D.$*E Alternative: $EXTENDED_OS_ERROR.Operat ing system dependent error information.

    S*F Alternative: $SYSTEM_FD_MAX.T he higliest system file descriptor, ordinarily 2.

    $"H The current s tate of syntax checks.$*I Alternative: $INPLACE_EDIT.

    In-place edit extension as passed to Perl using -i .$'L Alternative: $I:ORAIAT_FORMFKED.

    Formfeed character used in formats.$*M Em ergency m em ory poo l .$ " 0 A ltemauve: SOSNAME.

    Operat ing sys tem name.S'P Alternative: SPERLDB.

    Internal de bu gg ing fls ig.$"S Current state of the Perl interpreter.$*T Alternative: SBASETIME.T he time (as delivered by time) w he n the pro gramstarted. This value is used by die f i le test operators

    -M . - A . an d - C .$*W Alternative: SWARNING.

    The value of the - w option as passed to Perl .$*X Alternative: $EXECLTABLE_NAME.T he n am e by w hich this Perl interpreter w asinvoked .The fol lowing var iables are context dependent and need notbe localized:$% Alternative: $FORMAT_PAGE_NUMBER.The current page number of the currently selected

    ou tpu t channe l .S= Alternative: $FORMAT_LlNES_PER_PAGE.The page length of the current output channel .Default is 60 lines.

    Special Variables 51

  • 7/28/2019 Perl 5 Pocket Reference

    57/74

    $ - Alternative: $FORMAT_LIN ES_LEFT.The number of l ines remaining on the page.$~ Alternative: $FORMAT_NAME.The name of the current report format.

    $* Alternative: SFORMAT_TOP_N AME.The name of the current top-of-page format.

    $1 Alternative: SOUTPUT_AUTOFLUSH.If set to nonze ro , forces a flush after ev ery w rite orprint on the currently selected output channel.Default is 0.

    SARGV T he n am e of the cu rrent file w h e n re ad ing from < >.T he follow ing variables are alw ays local to the current block:$& Alternative: SMATCH.

    The string matched by the last successful patternmatch.$ ' Alternative: SPREMATCH.T he s ir ing preceding w hat w as m atched by the last

    successful match.$ ' A lternative: SPOSTMATCH.

    T he s tring follow ing w hat w as m atched by the las tsuccessful match.$+ Alternative: $LAST_PAREN_MATCH.

    The last bracket matched by the last search pattern.$ 1 . . . $ 9 . . .Contain the subpatterns from the corresponding sets

    of parentheses in the last pattern successfullymatched. $10 and up are only available if the matchcontained that many subpat terns .

    52 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    58/74

    Special A rraysThe al ternat ive names are provided by the s tandard moduleEnglish.@ARGV Contains the command-line arguments for the script(not including the com m an d na m e, w hich is in SO).EXPORT

    N a m e s (he methods and other symbols a packageexports by default .@EXPORT_OKN a m e s t h e m e t h o d s a n d o t h e r s y m b o l s a p a c k a g e

    can expor t upon expl ic i t reques t .@F W h e n c o m m a n d - l i n e o p t i o n - a i s us ed , con t a ins t h e

    split of th e input l ines .@INC Conta ins t h e list o f p lace s t o l ook for Perl scripts t obe eva lua t ed by the do filename, u s e a n d requirec o m m a n d s . D o n o t modify direct ly, b u t u s e t h e u s elib p r a g m a o r - I command- l i ne op t i on i n s t ead .

    @ISA List o f base c lasses of the cur ren t package ._ Alternative: @ARG.Parameter array for subroutines. Also used by splitif not in list context,Special Hashes%ENV Contains the current environment. The key is thename of an environment variable; the value is i ts

    current setting.%EXPORT_TAGS

    Defines names for sets of symbols.%1NC List of files that have been included with use, require,or do. T he k ey is the filename as specified: the valuethe location of the file.

    Special Hashes S3

  • 7/28/2019 Perl 5 Pocket Reference

    59/74

    %SIG Used to set signal handlers for various signals. Thekey is the na m e of the signal (w ithout the SIG p re fix); the value a subrou tine that is exe cuted w he nthe signal occurs.WARN and DIE are pseudo-signals toattach hand lers to Perl w arnings an d e xce ption s.

    Standard ModulesAnyDBM_FUeProvides a framework for multiple dbm files.AutoLoaderLoads functions only on demand.AutoSplit Splits a package for autoloading.B Experimental pack age that imp lem ents by te com pilation, a Perl to C translator, and other interestingthings.BenchmarkBenchmarks running t imes of code.Bundle::CPANA bu nd le to play w ith all the oilier m od ule s on

    CPAN.Ca rp W arns of errors.CGI Simple Com mo n Gatew ay Interface Class.CGI::ApacheCGI addition for Apache's Perl API.CGI::Cookie

    Interface to N etscape Co okies.CGl:Fast

    CGI interface for FastCGl.CGI.PushSimple interface to Server Push.

    54 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    60/74

    Classr.StructDeclares struct-like datatypes as Perl classes.Coring Accesses Perl configuration information.

    CPAN M ainten anc e of Perl m od ule s from CPAN sites.Cwd Gets the pathn am e of the current w orking directory.Data::Dumper

    Reveals Perl data structures as strings.DB.File Access to Berkeley DB files.Devel::SelfStubber

    Generates stubs for a SelfLoading mo d u le .Oirhandle

    Supplies object methods for directory handles.DynaLoader

    Dynamically loads C libraries into Perl code.English Uses nic e English na m es for ugly pu nc tu ati on variables .

    Env Im ports env ironm ent variables.Exporter

    Implements defaul t import method for modules .ExtUtils::CommandReplacements for common Unix commands (for

    Makefiles).ExtUtils::Embed

    Utilities for embedding Perl in C/C++ applications.ExtUtils::Install

    Installs files from here to there.ExtUtils: installed

    Inventory m anag em ent of installed m odu les .ExtUtils::Liblist

    Determines l ibraries to use and how to use them.ExtUtils::MakeMakerCreates an extension Makefile.

    Standard Modu les 55

  • 7/28/2019 Perl 5 Pocket Reference

    61/74

    ExtUtlls::ManifestUtilities to write and check a MANIFEST file.ExtUtils-MiniperlWrites the C code for perlmain.c.

    ExtUtils:: MkbootstrapMakes a bootstrap file for use by DynaLoader.

    ExtUtils: :MksymlistsWrites linker options files for dynamic extension.ExtUtils: :MM_OS2Methods to override Unix behavior inExtUtils::MakeMaker.

    ExtUtils::MM_UnixM etho ds us ed by ExtUtils: :MakeM aker.ExtUtils::MM_VMSMethods to override Unix behavior inExtUtils;: M akeM aker.

    ExtUtils: :MM_Win32Methods to override Unix behavior inExtUtils::MakeMaker.ExtUtils-Packlist

    Manages packlist files.ExtUtils:: test lib

    Adds blib directories to INC.Fatal Replaces functions with equivalents that succeed or

    die.Fcntl Loads the C fcntl.h defines.Fite::BasenameParses file specifications.File::CheckTree

    Runs many filetest checks on a tree.File::Copy

    Copies files or filehandles.File::DosGlobDOS-like globbing (with extensions).

    56 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    62/74

    File::FindTraverses a file tree.File::PathCreates or remove a series of directories.

    FiIe::SpecPortably performs operations on fi lenames.

    File::Spec::MacMethods for MacOS file specs.

    File::Spec::OS2Methods for OS/2 file specs.

    File::Spec::UnixMethods used by File::Spec for Unix.

    File::Spec::VMSMethods for VMS file specs.

    File::Spec::Win32Methods for Win32 file specs.

    File::statBy name interface to Perl's built-in stat functions.

    FileCacheK eep s m ore files o p e n than the system perm its .

    FileHandleSu pplie s object m eth od s for filehandles.

    FindBin Locates directory of original Perl script.GDBM_FUe

    Access to the gdbm library.Getopt::Long

    Hxtended handling of command-line options. Suitsal l needs .Getopt::StdProce sses s ingle-character sw itches w ith sw itch

    clustering.I18N::Collate

    Co mp ar es 8-bit scalar data according to the currentlocale .

    Standard Modules 5 7

  • 7/28/2019 Perl 5 Pocket Reference

    63/74

    IO Loads various I/O modules .IO::File Su pplies object m eth od s for filehandles.IO::Handle

    Supplies object methods for I/O handles .IO::Pipe

    Supplies object methods for pipes.IO::Seckable

    Supplies seek-based methods for I/O objects.IO::SelectObject interface to the select system call.IO::Socket

    Object interface to socket communications.IPC::Msg

    Interface to System V Message IPC.IPC::Open2Open a pipe to a process for both reading andwrit ing.IPC:;Open3O p en a pi pe to a process for reading, w rit ing, anderror handling.

    IFC::SemaphoreInterface to System V semaphores.

    IPC::SysVSystem V IPC object class.

    Math::BigFloatArbitrary length float math package.Math::BigIntArbitrary size integer math package.

    Math::ComplexComplex numbers and associated mathematicalfunctions.

    NDBM_Filetied access to ndbm files.

    58 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    64/74

    Netr.hostentAccess by nam e to gethostent an d friends.Net : :netentAccess by na m e to getnetent an d friends.

    Net::PingChecks wliether a host is up.

    Net : :pro toentAccess by name to getprotoent and friends.

    Net::serventAccess by na m e to getservent and friends.

    O Experimental compiler backend.Op code Disab les nam ed opcodes w hen compi ling Perl c o d e .OS2::ExtAttr

    Perl access to extended attributes. OS/2 only.OS2::PrfDBPerl extension to access the OS/2 sett ing database.

    OS/2 only.OS2::Process

    Constants for systemC) call on OS/2. OS/2 only.OS2::REXX

    Access to DLLs w ith REXX calling co nv en tio n an dREXX runtime. OS/2 only.

    Pod::HtmlModule to convert POD files to HTML

    Pod::TextConverts POD data to formatted ASCII text.

    POSLX Interface to IEEE Std 1003-1.Safe Co m piles an d exe cute s co de in restr icted

    compar tments .SDBM_File

    tied access to sdbm files.Search::Dict

    Searches for key in dictionary file.

    Standard Modules 59

  • 7/28/2019 Perl 5 Pocket Reference

    65/74

    SelectSaverSaves an d res tore s a sele cted filehandle.SellLoaderLoads functions only on demand.

    Shell Runs shell co m m an ds transparently w ithin Perl.Socket Loads the C soc ket.h defines an d stru ctu re

    manipulators.Symbol M anipulates Perl sym bols an d their na m es.Sysr.HostnameTries every conceivable w ay to get the n am e of this

    system.Sys::Syslog

    Interface to the Unix S)>slog(3) calls.Term::Cap

    Perl interface to Unix lerntcap(3)-Term::CompleteWord complet ion module.Term::ReadLine

    Interface to various readline packages.Test::Harness

    Runs Perl stan da rd test scripts w ith statistics.Text::Abbrev

    Creates an abbreviation table from a list.Text: :ParseWordsParses text into a list of tokens.Text: :SoundexImplementation of the Soundex Algorithm as

    descr ibed by Donald Knuth.Text::Tabs

    Expands and unexpands tabs.Text::Wrap

    Line w rap pin g to form sim ple p aragra phs .Thread Imp lem entation of Perl thread s.

    60 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    66/74

    Thread: :QueueImplementat ion of thread-safe queues .

    Th r ead - S emap h o r eImplementat ion of thread-safe semaphores-

    Thread: :SignalImplementation of reliable signals using threads.

    Th read: Spe cificThread-specific keys.

    Tie::ArraysBase class definitions for tied arrays.

    Tie-HandleBase class definitions for tied filehandles.

    Tie::HashBase class definitions for tied hashes.

    Tie::RefHashUse references as hash keys.

    Tie-ScalarBase class definitions for tied scalars.

    Tie::StdHashBasic methods for tied hashes.

    Tie::StdScalarBasic methods for tied scalars.Tie-SubstrHash

    Fixed table-size, fixed key-length hashing.Time::LocaI

    Efficiently computes time from local and GMT time.UNIVERSALBase class for all classes (blessed references).User.-grent

    Access by name to getgrent and friends.User : :pwent

    Access by name to getpwent and friends.

    Standard M odu les 61

  • 7/28/2019 Perl 5 Pocket Reference

    67/74

    VMS::DCLsymPerl extension to manipulate DCL symbols. VMSonly.

    VMS::FilespecCo nverts betw een VMS an d Unix file specificationsyntax. VMS only.

    VMS::StdioStandard I/O functions via VMS extensions. VMSonly.

    VMS::XSSymSetK eep s sets of sym bol na m es palatable to the VMSlinker.Environment VariablesPerl uses the fol lowing environment variables:HOME U sed if chdir has n o argu m ent.LOGDIR

    Used if chdlr has no argument and HOME is not set.PATH U sed in exec uting su bp ro ces ses , an d in finding the

    Perl script if-S is used.PERL5LIBA co lon -sep arate d list of direc tories to loo k in forPerl library files before looking in the standardlibrary and the current directory.

    PERL5DBThe command to get the debugger code. Defaults toBEGIN {require ' p e r l 5 d b . p l ' }.

    PERLLIB Used instead ofPERL5LD3 if the latter is not defined.

    62 Perl 5 Pocket Reference

    http://%27perl5db.pl%27/http://%27perl5db.pl%27/
  • 7/28/2019 Perl 5 Pocket Reference

    68/74

    MultithreadingMultithreading is an experimental featu re in this release.Su pport for mu ltithreading needs to be built into the Perl executable.Multithreading requires the standard module Thread. Thismodule implements the join, detach, and yield methods discussed here:$tbr-> detachDetach a thread so it ains independently.I $result = ) Sthr->joinWait for the thread to complete. The value returnedis the return value from the thread's suhroutine.lock variableLock a resource against concurrent access.$thr = new Thread su b | args ]Creates a new thread that starts executing in the referenced subroutine. The argsure passed to this subroutine.The return value of this subroutine is delivered by

    the join method,yield Explicitly give up the CPU to some other thread.The Perl Com pilerThe Perl Compiler is an experimental featu re in (bis release.To compile a Perl program foo.pl w ith the C backend:perl -MO=C,-ofoo.c foo.plTo com pile foo.pl w ith the CC backend:perl -MO=CC.-ofoo.c foo.plWalk the opcode tree in execution order, printing terse information about each opcode:perl -MO=Terse,execfoo.pl

    The Perl Compiler 63

    http://foo.pl/http://foo.pl/http://foo.pl/http://foo.pl/http://foo.pl/http://foo.pl/http://foo.pl/http://foo.pl/http://foo.pl/http://foo.pl/
  • 7/28/2019 Perl 5 Pocket Reference

    69/74

    Walk the opcode tree in syntax order, printing lengthierdebug information about each opcode:perl -MO=Debugfoo.plYou can also append ".exec" to walk in execution order.Produce a cross-reference report of the line num bers at w hichall variables, subroutines, and formats are defined and used:perl -MO=Xref foo.plThe P erl Debu g g erThe Perl symbolic debugger is invoked with perl -d.a [ line 1 commandSets an action for line.A Deletes all line actions,b I line | condition 1 ]Sets breakpoint at line; default is the current line,b sitb [ condition )

    Sets breakpoint at the named subroutine,b compile sitbncime

    Stop after the subroutine is compiled,b load fileSets breakpoint at requireing the given file,

    b postpone subname [ condition ]Sets breakpoint at the first line of the subroutineafter it is compiled,c f line ]

    Continues (until line, or another breakpoint, or exit),d I line 1Deletes breakpoint at the given line; default is thecurrent line.D Deletes all breakpoints.(file Switches to ileand starts listing it.h Prints out a long help message.

    64 Perl 5 Pocket Reference

    http://foo.pl/http://foo.pl/http://foo.pl/http://foo.pl/
  • 7/28/2019 Perl 5 Pocket Reference

    70/74

    h and Prints out help for the command and.h h Prints out a con cise he lp m essa ge.H I -number ]

    Displays the last -number c o m m a n d s .1 [ range ]Lists a range of lines, range may he a number ,start-end, start+amount, or a subroutine name. If

    range is omitted, l is ts next w indow .I su b Lists the named subroutine.L Lists lines that ha ve bre akp oin ts or actio ns,m class Prints the methods callable via the given class.m expr Evaluates the expression in list context, prints the

    methods callable on the first element of the result,n [ expr )Single steps around the subroutine call .O I opt [- val \ 1

    Sets or queries values of debugger options.p expr Prints expr.q Q uits . You may also use you r | H.or] character,r Returns from the current sub rou tine.R Restarts the debugger,s I expr 1

    Single steps.S [ ! ] patternLists the names of all subroutines (not) matching the

    pattern,t Toggles trace m od e.t expr Traces through execution of expr.T Prints a stack trace.V f package I pattern 1 JLists variables matching pattern in A package. Default

    package is main.

    The P erl Debu g g er 65

  • 7/28/2019 Perl 5 Pocket Reference

    71/74

    w [ line ]Lists w ind ow aro un d the specif ied l ine.W Deletes all w atch-expressions.

    W expr Adds a global w atch-expression.x expr Evaluates expr in list context, dumps the result.X I pattern ILike V, but assumes current package.command Executes command as a Perl statement.

    Returns to the executed line.Lists previous w indo w .

    = [ alias value ]Sets alias, or lists current aliases.

    /pattern/ Searches forward for pattern.^pattern? Searches backw ard for pattern.< commandSets an action to be executed before every debugger

    prompt . commandAdds an action to the list of actions to be executedbefore every debugger prompt .

    > commandSets an action to be executed after every debuggerprompt , commandAdds an action to the list of actions to be executedafter every debugger prompt.

    { cmd Defines a debugger command to run before eachp r ompt .

    \\ cmd Adds a debugger command to the l ist of debuggercommands to run before each prompt .

    66 Perl 5 Pocket Reference

  • 7/28/2019 Perl 5 Pocket Reference

    72/74

    ! I ( - \number }Re-executes a command. Default is the previouscommand.! [ pattern \He-executes the last command that started w ithpattern.!! [ command )Runs command in a subprocess.I cmd Run debugger command cmd through the currentpager.II cmd Same, temporarily selects DB::OUT as w ell.

    [RETURN! Repeats last s or n.

    The Perl Debugger 67

    http://number/http://number/http://number/
  • 7/28/2019 Perl 5 Pocket Reference

    73/74

    M o re T itles from 0'y^JiPerl

    Learning Pe rl, 2nd Edit ionby Randal L Schwartz& Tom Christiansen2ndEdition July 1997ISBN1-56592-284-0

    Per i Cookbookby Tbm Christiansen& Nathan Tbrtington1st Edition August 1998ISBN' 1-56592-24J-3

    Programming Per l ,2nd Edit ionby Larry Wall, Tbm ChristiansenG Randal L Scbtiwlz2nd Edition September 19%ISBN1-56592-149-6

    Ad vanced Perl Prog ramm ingbySriram Srinirasan1st Edition August 1997ISBN 1-56592-2204

    Learning Perl on W in32 Systemsby RandalL Schwartz. Ent Olson& Tbm Christiansen1st Edition August 1997ISBN1-56592-324-3

    Mastering Regular Expressionsby Jeffrey E />***1st Edition January 1997ISBX'l-56592-257-3

    Per l in a Nutshel lby Stephen Spuinltour, EII01 Sitter& Nathan Patuanlban1st Edition September 1998ISBS 1-56592-2X6-7

    Mastering Algorithmsw ith Per lby Jon Orutmt, Jorkko llietanieini6 John Macdotmld1st Edition Sefttember 1998ISBN 1-56592-398-7

    W eb Cl ient P rogramm ingw ith Per lby Clinton none1st Edition March 1997ISBN 1-56592-214 X

    CG I Prog ramm ing on theW or ld W ide W ebby Sbisbir Gwuknaram1st Edition March 1996ISBN1-56592- 16H-2

    O'REILLY"waw-f 800-998-9938 * [email protected] http://www.oreilly.com/

    OUR PRODUCTS AW A / A H A S U HI A SOOKSICPS OR SGI WA M srcsi KM YOUFOBmrommon: 800-998-9938 * 707-829-0515 [email protected]

    mailto:[email protected]:[email protected]://www.oreilly.com/mailto:[email protected]:[email protected]://www.oreilly.com/mailto:[email protected]
  • 7/28/2019 Perl 5 Pocket Reference

    74/74

    O'REILLY

    Perl 5 Pocket Referencea 'lliis quick-reference guide to the Perl programminglanguage pun ides a com plete overview of the language,from variables to input and output, from Bow control toregular expressions, from functions to documentformatsall packed into a convenient, carry-around booklet.Included is a summary of Perl syntax rules, a complete list ofstandaal library modules with brief descriptions, anil aprecedence table for Perl operators. Updated for Perl Version5.005, this boo klet cov ers the new est Peri features like e nh an ce dregular expressions, multithreading, and the Perl compiler.T he Perl 5Pocket Reference \s the perfect companion to LearningPerl, a carefully pac ed tutorial co ur se by Randal L. Schw artz, andProgramming Perl, the com plete , authoritative reference w orkCOauthored by Perl developer tany Wall. Tom Christiansen, andSchwartz .Johan Vromans has engaged in software engineering researchsince 1975. Co nvinced of the Importance of a go od progra m m ingenvironment, he became an expert in using GNU Kmacs and thePerl programming language. Also, he was instrumental inbringing the Internet to the N etherlands as a commercial activity.He currently o w ns his own consulting business called SquirrelConsultancy. He can be reached at JVromansQsquirret.nl

    Visit O'Reilly on the Web atwww.oreilly.com

    http://jvromansqsquirret.nl/http://www.oreilly.com/http://www.oreilly.com/http://jvromansqsquirret.nl/