home *** CD-ROM | disk | FTP | other *** search
Wrap
Text File | 1999-10-14 | 70.5 KB | 1,006 lines
=head1 NAME perlop - Perl operators and precedence =head1 SYNOPSIS Perl operators have the following associativity and precedence, listed from highest precedence to lowest. Note that all operators borrowed from C keep the same precedence relationship with each other, even where C's precedence is slightly screwy. (This makes learning Perl easier for C folks.) With very few exceptions, these all operate on scalar values only, not array values. left terms and list operators (leftward) left -> nonassoc ++ -- right ** right ! ~ \ and unary + and - left =~ !~ left * / % x left + - . left << >> nonassoc named unary operators nonassoc < > <= >= lt gt le ge nonassoc == != <=> eq ne cmp left & left | ^ left && left || nonassoc .. ... right ?: right = += -= *= etc. left , => nonassoc list operators (rightward) right not left and left or xor In the following sections, these operators are covered in precedence order. Many operators can be overloaded for objects. See L<overload>. =head1 DESCRIPTION =head2 Terms and List Operators (Leftward) A TERM has the highest precedence in Perl. They include variables, quote and quote-like operators, any expression in parentheses, and any function whose arguments are parenthesized. Actually, there aren't really functions in this sense, just list operators and unary operators behaving as functions because you put parentheses around the arguments. These are all documented in L<perlfunc>. If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call. In the absence of parentheses, the precedence of list operators such as C<print>, C<sort>, or C<chmod> is either very high or very low depending on whether you are looking at the left side or the right side of the operator. For example, in @ary = (1, 3, sort 4, 2); print @ary; # prints 1324 the commas on the right of the sort are evaluated before the sort, but the commas on the left are evaluated after. In other words, list operators tend to gobble up all the arguments that follow them, and then act like a simple TERM with regard to the preceding expression. Note that you have to be careful with parentheses: # These evaluate exit before doing the print: print($foo, exit); # Obviously not what you want. print $foo, exit; # Nor is this. # These do the print before evaluating exit: (print $foo), exit; # This is what you want. print($foo), exit; # Or this. print ($foo), exit; # Or even this. Also note that print ($foo & 255) + 1, "\n"; probably doesn't do what you expect at first glance. See L<Named Unary Operators> for more discussion of this. Also parsed as terms are the C<do {}> and C<eval {}> constructs, as well as subroutine and method calls, and the anonymous constructors C<[]> and C<{}>. See also L<Quote and Quote-like Operators> toward the end of this section, as well as L<"I/O Operators">. =head2 The Arrow Operator Just as in C and C++, "C<-E<gt>>" is an infix dereference operator. If the right side is either a C<[...]> or C<{...}> subscript, then the left side must be either a hard or symbolic reference to an array or hash (or a location capable of holding a hard reference, if it's an lvalue (assignable)). See L<perlref>. Otherwise, the right side is a method name or a simple scalar variable containing the method name, and the left side must either be an object (a blessed reference) or a class name (that is, a package name). See L<perlobj>. =head2 Auto-increment and Auto-decrement "++" and "--" work as in C. That is, if placed before a variable, they increment or decrement the variable before returning the value, and if placed after, increment or decrement the variable after returning the value. The auto-increment operator has a little extra builtin magic to it. If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern C</^[a-zA-Z]*[0-9]*$/>, the increment is done as a string, preserving each character within its range, with carry: print ++($foo = '99'); # prints '100' print ++($foo = 'a0'); # prints 'a1' print ++($foo = 'Az'); # prints 'Ba' print ++($foo = 'zz'); # prints 'aaa' The auto-decrement operator is not magical. =head2 Exponentiation Binary "**" is the exponentiation operator. Note that it binds even more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is implemented using C's pow(3) function, which actually works on doubles internally.) =head2 Symbolic Unary Operators Unary "!" performs logical negation, i.e., "not". See also C<not> for a lower precedence version of this. Unary "-" performs arithmetic negation if the operand is numeric. If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned. One effect of these rules is that C<-bareword> is equivalent to C<"-bareword">. Unary "~" performs bitwise negation, i.e., 1's complement. For example, C<0666 &~ 027> is 0640. (See also L<Integer Arithmetic> and L<Bitwise String Operators>.) Unary "+" has no effect whatsoever, even on strings. It is useful syntactically for separating a function name from a parenthesized expression that would otherwise be interpreted as the complete list of function arguments. (See examples above under L<Terms and List Operators (Leftward)>.) Unary "\" creates a reference to whatever follows it. See L<perlref>. Do not confuse this behavior with the behavior of backslash within a string, although both forms do convey the notion of protecting the next thing from interpretation. =head2 Binding Operators Binary "=~" binds a scalar expression to a pattern match. Certain operations search or modify the string $_ by default. This operator makes that kind of operation work on some other string. The right argument is a search pattern, substitution, or transliteration. The left argument is what is supposed to be searched, substituted, or transliterated instead of the default $_. The return value indicates the success of the operation. (If the right argument is an expression rather than a search pattern, substitution, or transliteration, it is interpreted as a search pattern at run time. This can be is less efficient than an explicit search, because the pattern must be compiled every time the expression is evaluated. Binary "!~" is just like "=~" except the return value is negated in the logical sense. =head2 Multiplicative Operators Binary "*" multiplies two numbers. Binary "/" divides two numbers. Binary "%" computes the modulus of two numbers. Given integer operands C<$a> and C<$b>: If C<$b> is positive, then C<$a % $b> is C<$a> minus the largest multiple of C<$b> that is not greater than C<$a>. If C<$b> is negative, then C<$a % $b> is C<$a> minus the smallest multiple of C<$b> that is not less than C<$a> (i.e. the result will be less than or equal to zero). Note than when C<use integer> is in scope, "%" give you direct access to the modulus operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster. Binary "x" is the repetition operator. In scalar context, it returns a string consisting of the left operand repeated the number of times specified by the right operand. In list context, if the left operand is a list in parentheses, it repeats the list. print '-' x 80; # print row of dashes print "\t" x ($tab/8), ' ' x ($tab%8); # tab over @ones = (1) x 80; # a list of 80 1's @ones = (5) x @ones; # set all elements to 5 =head2 Additive Operators Binary "+" returns the sum of two numbers. Binary "-" returns the difference of two numbers. Binary "." concatenates two strings. =head2 Shift Operators Binary "<<" returns the value of its left argument shifted left by the number of bits specified by the right argument. Arguments should be integers. (See also L<Integer Arithmetic>.) Binary ">>" returns the value of its left argument shifted right by the number of bits specified by the right argument. Arguments should be integers. (See also L<Integer Arithmetic>.) =head2 Named Unary Operators The various named unary operators are treated as functions with one argument, with optional parentheses. These include the filetest operators, like C<-f>, C<-M>, etc. See L<perlfunc>. If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call. Examples: chdir $foo || die; # (chdir $foo) || die chdir($foo) || die; # (chdir $foo) || die chdir ($foo) || die; # (chdir $foo) || die chdir +($foo) || die; # (chdir $foo) || die but, because * is higher precedence than ||: chdir $foo * 20; # chdir ($foo * 20) chdir($foo) * 20; # (chdir $foo) * 20 chdir ($foo) * 20; # (chdir $foo) * 20 chdir +($foo) * 20; # chdir ($foo * 20) rand 10 * 20; # rand (10 * 20) rand(10) * 20; # (rand 10) * 20 rand (10) * 20; # (rand 10) * 20 rand +(10) * 20; # rand (10 * 20) See also L<"Terms and List Operators (Leftward)">. =head2 Relational Operators Binary "E<lt>" returns true if the left argument is numerically less than the right argument. Binary "E<gt>" returns true if the left argument is numerically greater than the right argument. Binary "E<lt>=" returns true if the left argument is numerically less than or equal to the right argument. Binary "E<gt>=" returns true if the left argument is numerically greater than or equal to the right argument. Binary "lt" returns true if the left argument is stringwise less than the right argument. Binary "gt" returns true if the left argument is stringwise greater than the right argument. Binary "le" returns true if the left argument is stringwise less than or equal to the right argument. Binary "ge" returns true if the left argument is stringwise greater than or equal to the right argument. =head2 Equality Operators Binary "==" returns true if the left argument is numerically equal to the right argument. Binary "!=" returns true if the left argument is numerically not equal to the right argument. Binary "E<lt>=E<gt>" returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. Binary "eq" returns true if the left argument is stringwise equal to the right argument. Binary "ne" returns true if the left argument is stringwise not equal to the right argument. Binary "cmp" returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument. "lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specified by the current locale if C<use locale> is in effect. See L<perllocale>. =head2 Bitwise And Binary "&" returns its operators ANDed together bit by bit. (See also L<Integer Arithmetic> and L<Bitwise String Operators>.) =head2 Bitwise Or and Exclusive Or Binary "|" returns its operators ORed together bit by bit. (See also L<Integer Arithmetic> and L<Bitwise String Operators>.) Binary "^" returns its operators XORed together bit by bit. (See also L<Integer Arithmetic> and L<Bitwise String Operators>.) =head2 C-style Logical And Binary "&&" performs a short-circuit logical AND operation. That is, if the left operand is false, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated. =head2 C-style Logical Or Binary "||" performs a short-circuit logical OR operation. That is, if the left operand is true, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated. The C<||> and C<&&> operators differ from C's in that, rather than returning 0 or 1, they return the last value evaluated. Thus, a reasonably portable way to find out the home directory (assuming it's not "0") might be: $home = $ENV{'HOME'} || $ENV{'LOGDIR'} || (getpwuid($<))[7] || die "You're homeless!\n"; In particular, this means that you shouldn't use this for selecting between two aggregates for assignment: @a = @b || @c; # this is wrong @a = scalar(@b) || @c; # really meant this @a = @b ? @b : @c; # this works fine, though As more readable alternatives to C<&&> and C<||> when used for control flow, Perl provides C<and> and C<or> operators (see below). The short-circuit behavior is identical. The precedence of "and" and "or" is much lower, however, so that you can safely use them after a list operator without the need for parentheses: unlink "alpha", "beta", "gamma" or gripe(), next LINE; With the C-style operators that would have been written like this: unlink("alpha", "beta", "gamma") || (gripe(), next LINE); Use "or" for assignment is unlikely to do what you want; see below. =head2 Range Operators Binary ".." is the range operator, which is really two different operators depending on the context. In list context, it returns an array of values counting (by ones) from the left value to the right value. This is useful for writing C<foreach (1..10)> loops and for doing slice operations on arrays. In the current implementation, no temporary array is created when the range operator is used as the expression in C<foreach> loops, but older versions of Perl might burn a lot of memory when you write something like this: for (1 .. 1_000_000) { # code } In scalar context, ".." returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of B<sed>, B<awk>, and various editors. Each ".." operator maintains its own boolean state. It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, I<AFTER> which the range operator becomes false again. (It doesn't become false till the next time the range operator is evaluated. It can test the right operand and become false on the same evaluation it became true (as in B<awk>), but it still returns true once. If you don't want it to test the right operand till the next evaluation (as in B<sed>), use three dots ("...") instead of two.) The right operand is not evaluated while the operator is in the "false" state, and the left operand is not evaluated while the operator is in the "true" state. The precedence is a little lower than || and &&. The value returned is either the empty string for false, or a sequence number (beginning with 1) for true. The sequence number is reset for each range encountered. The final sequence number in a range has the string "E0" appended to it, which doesn't affect its numeric value, but gives you something to search for if you want to exclude the endpoint. You can exclude the beginning point by waiting for the sequence number to be greater than 1. If either operand of scalar ".." is a constant expression, that operand is implicitly compared to the C<$.> variable, the current line number. Examples: As a scalar operator: if (101 .. 200) { print; } # print 2nd hundred lines next line if (1 .. /^$/); # skip header lines s/^/> / if (/^$/ .. eof()); # quote body # parse mail messages while (<>) { $in_header = 1 .. /^$/; $in_body = /^$/ .. eof(); # do something based on those } continue { close ARGV if eof; # reset $. each file } As a list operator: for (101 .. 200) { print; } # print $_ 100 times @foo = @foo[0 .. $#foo]; # an expensive no-op @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items The range operator (in list context) makes use of the magical auto-increment algorithm if the operands are strings. You can say @alphabet = ('A' .. 'Z'); to get all the letters of the alphabet, or $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15]; to get a hexadecimal digit, or @z2 = ('01' .. '31'); print $z2[$mday]; to get dates with leading zeros. If the final value specified is not in the sequence that the magical increment would produce, the sequence goes until the next value would be longer than the final value specified. =head2 Conditional Operator Ternary "?:" is the conditional operator, just as in C. It works much like an if-then-else. If the argument before the ? is true, the argument before the : is returned, otherwise the argument after the : is returned. For example: printf "I have %d dog%s.\n", $n, ($n == 1) ? '' : "s"; Scalar or list context propagates downward into the 2nd or 3rd argument, whichever is selected. $a = $ok ? $b : $c; # get a scalar @a = $ok ? @b : @c; # get an array $a = $ok ? @b : @c; # oops, that's just a count! The operator may be assigned to if both the 2nd and 3rd arguments are legal lvalues (meaning that you can assign to them): ($a_or_b ? $a : $b) = $c; This is not necessarily guaranteed to contribute to the readability of your program. Because this operator produces an assignable result, using assignments without parentheses will get you in trouble. For example, this: $a % 2 ? $a += 10 : $a += 2 Really means this: (($a % 2) ? ($a += 10) : $a) += 2 Rather than this: ($a % 2) ? ($a += 10) : ($a += 2) =head2 Assignment Operators "=" is the ordinary assignment operator. Assignment operators work as in C. That is, $a += 2; is equivalent to $a = $a + 2; although without duplicating any side effects that dereferencing the lvalue might trigger, such as from tie(). Other assignment operators work similarly. The following are recognized: **= += *= &= <<= &&= -= /= |= >>= ||= .= %= ^= x= Note that while these are grouped by family, they all have the precedence of assignment. Unlike in C, the assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to. This is useful for modifying a copy of something, like this: ($tmp = $global) =~ tr [A-Z] [a-z]; Likewise, ($a += 2) *= 3; is equivalent to $a += 2; $a *= 3; =head2 Comma Operator Binary "," is the comma operator. In scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. This is just like C's comma operator. In list context, it's just the list argument separator, and inserts both its arguments into the list. The =E<gt> digraph is mostly just a synonym for the comma operator. It's useful for documenting arguments that come in pairs. As of release 5.001, it also forces any word to the left of it to be interpreted as a string. =head2 List Operators (Rightward) On the right side of a list operator, it has very low precedence, such that it controls all comma-separated expressions found there. The only operators with lower precedence are the logical operators "and", "or", and "not", which may be used to evaluate calls to list operators without the need for extra parentheses: open HANDLE, "filename" or die "Can't open: $!\n"; See also discussion of list operators in L<Terms and List Operators (Leftward)>. =head2 Logical Not Unary "not" returns the logical negation of the expression to its right. It's the equivalent of "!" except for the very low precedence. =head2 Logical And Binary "and" returns the logical conjunction of the two surrounding expressions. It's equivalent to && except for the very low precedence. This means that it short-circuits: i.e., the right expression is evaluated only if the left expression is true. =head2 Logical or and Exclusive Or Binary "or" returns the logical disjunction of the two surrounding expressions. It's equivalent to || except for the very low precedence. This makes it useful for control flow print FH $data or die "Can't write to FH: $!"; This means that it short-circuits: i.e., the right expression is evaluated only if the left expression is false. Due to its precedence, you should probably avoid using this for assignment, only for control flow. $a = $b or $c; # bug: this is wrong ($a = $b) or $c; # really means this $a = $b || $c; # better written this way However, when it's a list context assignment and you're trying to use "||" for control flow, you probably need "or" so that the assignment takes higher precedence. @info = stat($file) || die; # oops, scalar sense of stat! @info = stat($file) or die; # better, now @info gets its due Then again, you could always use parentheses. Binary "xor" returns the exclusive-OR of the two surrounding expressions. It cannot short circuit, of course. =head2 C Operators Missing From Perl Here is what C has that Perl doesn't: =over 8 =item unary & Address-of operator. (But see the "\" operator for taking a reference.) =item unary * Dereference-address operator. (Perl's prefix dereferencing operators are typed: $, @, %, and &.) =item (TYPE) Type casting operator. =back =head2 Quote and Quote-like Operators While we usually think of quotes as literal values, in Perl they function as operators, providing various kinds of interpolating and pattern matching capabilities. Perl provides customary quote characters for these behaviors, but also provides a way for you to choose your quote character for any of them. In the following table, a C<{}> represents any pair of delimiters you choose. Non-bracketing delimiters use the same character fore and aft, but the 4 sorts of brackets (round, angle, square, curly) will all nest. Customary Generic Meaning Interpolates '' q{} Literal no "" qq{} Literal yes `` qx{} Command yes (unless '' is delimiter) qw{} Word list no // m{} Pattern match yes (unless '' is delimiter) qr{} Pattern yes (unless '' is delimiter) s{}{} Substitution yes (unless '' is delimiter) tr{}{} Transliteration no (but see below) Note that there can be whitespace between the operator and the quoting characters, except when C<#> is being used as the quoting character. C<q#foo#> is parsed as being the string C<foo>, while C<q #foo#> is the operator C<q> followed by a comment. Its argument will be taken from the next line. This allows you to write: s {foo} # Replace foo {bar} # with bar. For constructs that do interpolation, variables beginning with "C<$>" or "C<@>" are interpolated, as are the following sequences. Within a transliteration, the first ten of these sequences may be used. \t tab (HT, TAB) \n newline (NL) \r return (CR) \f form feed (FF) \b backspace (BS) \a alarm (bell) (BEL) \e escape (ESC) \033 octal char (ESC) \x1b hex char (ESC) \c[ control char \l lowercase next char \u uppercase next char \L lowercase till \E \U uppercase till \E \E end case modification \Q quote non-word characters till \E If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u> and C<\U> is taken from the current locale. See L<perllocale>. All systems use the virtual C<"\n"> to represent a line terminator, called a "newline". There is no such thing as an unvarying, physical newline character. It is an illusion that the operating system, device drivers, C libraries, and Perl all conspire to preserve. Not all systems read C<"\r"> as ASCII CR and C<"\n"> as ASCII LF. For example, on a Mac, these are reversed, and on systems without line terminator, printing C<"\n"> may emit no actual data. In general, use C<"\n"> when you mean a "newline" for your system, but use the literal ASCII when you need an exact character. For example, most networking protocols expect and prefer a CR+LF (C<"\012\015"> or C<"\cJ\cM">) for line terminators, and although they often accept just C<"\012">, they seldom tolerate just C<"\015">. If you get in the habit of using C<"\n"> for networking, you may be burned some day. You cannot include a literal C<$> or C<@> within a C<\Q> sequence. An unescaped C<$> or C<@> interpolates the corresponding variable, while escaping will cause the literal string C<\$> to be inserted. You'll need to write something like C<m/\Quser\E\@\Qhost/>. Patterns are subject to an additional level of interpretation as a regular expression. This is done as a second pass, after variables are interpolated, so that regular expressions may be incorporated into the pattern from the variables. If this is not what you want, use C<\Q> to interpolate a variable literally. Apart from the above, there are no multiple levels of interpolation. In particular, contrary to the expectations of shell programmers, back-quotes do I<NOT> interpolate within double quotes, nor do single quotes impede evaluation of variables when used within double quotes. =head2 Regexp Quote-Like Operators Here are the quote-like operators that apply to pattern matching and related activities. Most of this section is related to use of regular expressions from Perl. Such a use may be considered from two points of view: Perl handles a a string and a "pattern" to RE (regular expression) engine to match, RE engine finds (or does not find) the match, and Perl uses the findings of RE engine for its operation, possibly asking the engine for other matches. RE engine has no idea what Perl is going to do with what it finds, similarly, the rest of Perl has no idea what a particular regular expression means to RE engine. This creates a clean separation, and in this section we discuss matching from Perl point of view only. The other point of view may be found in L<perlre>. =over 8 =item ?PATTERN? This is just like the C</pattern/> search, except that it matches only once between calls to the reset() operator. This is a useful optimization when you want to see only the first occurrence of something in each file of a set of files, for instance. Only C<??> patterns local to the current package are reset. while (<>) { if (?^$?) { # blank line between header and body } } continue { reset if eof; # clear ?? status for next file } This usage is vaguely deprecated, and may be removed in some future version of Perl. =item m/PATTERN/cgimosx =item /PATTERN/cgimosx Searches a string for a pattern match, and in scalar context returns true (1) or false (''). If no string is specified via the C<=~> or C<!~> operator, the $_ string is searched. (The string specified with C<=~> need not be an lvalue--it may be the result of an expression evaluation, but remember the C<=~> binds rather tightly.) See also L<perlre>. See L<perllocale> for discussion of additional considerations that apply when C<use locale> is in effect. Options are: c Do not reset search position on a failed match when /g is in effect. g Match globallylhein st nds, l conurrence ofs g Mi note ma-ertenion vettern match, a sp g Mm Ttes ring and sltiple leve bes g Mo Comp (<>tern maty thee be g Ms Ttes ring and slgle quoe be g Mx Usxpec acdedgular expressions fr Optno "/" in C<=dee mrall C<he hab bon C<$> ms in opnal co(ThW wha C<=~>msou maycased w exy>teir addnl -copdleus, ic,dnl -le a kagharacter. of sldee mrall Ifs is a uticular retheful or disching froUbox>terha cm do t apptextaeff"/", an avoid LTS (n se to doer plakstend Pee Ifno "?" ino t <=dee mrall, C<he habching-y th-e betruof a s?> TERN? >ply . Mno "'" in C<=dee mrall,dnlriable literpolation. a utol dimedgohe haattERN? OpttERN? y be textaeffiables wh,ile when caubiterpolationedg( in pattern froateomp (<thels to timhe restern frorch posa uluation andept that diswC<he habdee mrall a usegle quotes i(TheNs iat app> o)>d in > o|soumtly.t be an erpolationedganse the liycalokke theacd-of-ing and a ts.) Mno want to s a usetern frobe inseomp (<tty thee be,ditiC<\Q>/o>ter vao t <=ry ( anddee mrallThis is avoidspectaniovetrun-timheateomp (ons thyou in sseful orwC<he habue--i wan reserpolation.will t'taracwiof ╗.nexracwan resexyƒ<he ha ctaniovetrun-timheateomp (ons thyou in sseful orwC<he habue--i wan reserp9Howll ati tn ╗.n\@\Qhop (o ╗tupoint o s<hseo t <=d=ry ou in ssefulariable literher pouotes i(Tg is sldee ssefularimxra>. ou inll nant iions o t < ou froateop> o)>d see onlyimsey/" in an lv(o" o t<ddeltisyƒ<ly>l optiin opnal co(ThW wha n resexd forns o t < ouhopg>-le a part frosexd, of// of nt larte C<=~> or C<!~RE elarte C<whsns th--i wanubhis is not whaoptiinby pouoteine r ferher pouat diswC<p g M( ts1>, o$2>, o$3>...)okke theacd-ofthe e ts1>coop.timhraconskagepecificd-ofpointdi-errndles a a 4'ndbhd-viurrsidW ha cta activranooteine r ferher pouotes i(T to RE e C<!niovetr OpttElarte ttor> is erndeltisgharactely.tactoutoteine r fer,See amsey/larteidere C<!iinupperlnurr ns o Examsterect. d nn(TTY,S'/dev/s y');. <TTY> =~ /^y/i && iso(); #rticisoy dedesi (rct. e { /Vrches : *([0-9.]*)/set $arches a= $1;versio somee {m#^/usr/sppol/udep#;rsio #rppo plan'ndg (pio $arga= she t;dy } } continupris ie {/$arg/o; #ridspectniovetrun-ure versio e { ($F1, $F2, $Etcon= ($isoy=~ /^(\S+)\s+(\S+)\s*(.*)/s)rsion of (o" co(amsteprelas n$isoyis otance. Onltwicuo redept thatlocls r ne--i wal Cpecifio"sig not onseomloce. eld see $F1, $F2, cifat$Etc?PATTER C<ions are: OpperaifIfs ible literhwa act"sig xd, g MifwC<he tern maty theerns o T ouhopg>-modion rpression satch, a>tern maty thee b--a usefr,Sy thee bdo t mfs ill tsC<=d ssiabletacter pouo" in rp9Howefulbhd-vtsCPATen ofperltTER C<=~> g isn larte C<=~> ,efulr C<!~RE larte Oprch thatnub" in whaoptiinby prch thoteine r ferher pouo opnal co(ThW wha .o t < o activ nooteine r fer,efulr C<!~RE larte Oprch thwhaoptiiatn in ,C<=di < o acwa acteine r ferheiouept th} oacdedgularns o td via the C<=~> ,the cu~>ecutt. O of//g>-fon of th} some is spatlo C<!s thTRUEdi <ime is ser,SeeptFALSEdi < o acart fosxrdditi is s.o T ou st nds,ns than lv(o" ce ofs mraitem adely.obalusQ>/o> ou s()rssxnc nds;.obn C<use sxnc/ s>g i Aonurrence ofs nrpo a s globash thatnylhein st nds, otanceitgQ>ns th--i wan in aperlldee mrahabchia usatby ptio>/o> ouhopc>-modion rp(e. rp of//gc>)okkModioyo>/o> outargetatn in tions globash thllylhein st ndsns o Ydee mraateomme I of//g>- is seretactI of/\G.../g>estehe e t\Gdnl -E ezheo-tadctIt"she nds, use is sereonlyixrhan st nds,tehe e> ou e viuusatiof//g>,aifIfs ,alefte f?PATTER t\Gdnt"she nds,art frosup rt evaluoutrltTERhopg>-modion r; and st sp tactoutohopg>,R t\Gdnbhd-vtsCju" ctheeatio\A> aperl us'ndrhc hellSeeptmp (<ssefuler pouofer ns o Examsterect. # larte C<=~> . ($C<e,$fati,$fas t hon= (`upll t`y=~ /(\d+\.\d+)pg);rsio #rvia the C<=~> io tinu on a $/n= "";rs } foned($teiagiaphn= coontinu } }$teiagiaphn=~ /[a-z]['")]*[.!?]+['")]*\spg)ntinu $o Ct slti++;inu }ers }ure verse vpris i"$o Ct slti\n";rsio #rusQ>/of//gcetactI\Gio $_n= "p oqp qq";dy } }$i++ 2)ntin }e vpris i"1: '";dy }e vpris i$1} /(o)pgc;vpris i"',n s=",n s,n"\n";rs }e vpris i"2: '";dy }e vpris i$1}e {/\G(q)pgc;vvpris i"',n s=",n s,n"\n";rs }e vpris i"3: '";dy }e vpris i$1} /(p)pgc;vpris i"',n s=",n s,n"\n";rs }}s o T ou(o" co(amsteprtouldvpris ect. 1: 'oo',n s=4. 2: 'q',n s=5. 3: 'pp',n s=7. 1: '',n s=7. 2: 'q',n s=8. 3: '',n s=8. . Aesexyƒ<hidis atly.C<tex>-thee viannrrndarthop\G.../gc>g iYdee mr. idsbonellyarc a opo(Ts thee point oto sltisanse in tteit-by-teitpatdoul oi-err Ctdrh ╗.neCPATen s th-nstern f opo(Tty theern iEe catlopo(Tt in see e ofs tehe e> ou e viuush-nou(e-vtsC f?ct. $_n= <<'EOL';dy }e $ua = now URI::URL "http://www/";vv oiraifI$ua eq "xXx";rs EOLrs LOOP:io tin }e vpris (" oigas "), (ro LOOP}e {/\G\d+\b[,.;]?\s*pgc;in }e vpris (" lowlrcase"), (ro LOOP}e {/\G[a-z]+\b[,.;]?\s*pgc;in }e vpris (" UPPERCASE"), (ro LOOP}e {/\G[A-Z]+\b[,.;]?\s*pgc;in }e vpris (" Capielliz(r"), (ro LOOP}e {/\G[A-Z][a-z]+\b[,.;]?\s*pgc;in }e vpris (" MiXeD"), (ro LOOP}e {/\G[A-Za-z]+\b[,.;]?\s*pgc;in }e vpris (" llpsseumeric"), (ro LOOP}e {/\G[A-Za-z0-9]+\b[,.;]?\s*pgc;in }e vpris (" l C-noise"), (ro LOOP}e {/\G[^A-Za-z0-9]+pgc;in }e vpris ".ATTus'ndrll!\n";rs }}s o Ho acart> ououtperl(relasyis otlyarc a l Cs)ect. l C-noise lowlrcase l C-noise lowlrcase UPPERCASE l C-noise. UPPERCASE l C-noise lowlrcase l C-noise lowlrcase l C-noise. lowlrcase lowlrcase l C-noise lowlrcase lowlrcase l C-noise. MiXeD l C-noise.ATTus'ndrll!ct. =asem q/STRING/ct. =asem C<'STRING'>. . AesQ>/lC-quthed, lasrc a " in rpAebacks(o" f oThW Ctsansbacks(o" . unltisafollowlinby > oudelamasrcely.a frditibacks(o" ,ler tern fcaserltTERdelamasrcely.backs(o" fisaateompolaterns o }e $isoy= q!I "aid, "Ydee"aid, 'Sthllaid<im.'"!;rs }$bary= q('n of of om.');. $bazy= '\n'; #raltwi-<ssrrh rpr in ct. =asem qq/STRING/ct. =asem "STRING". . AeddeblC-quthed, ateompolater " in rs o }e $_ .= qqin }e (***ATTER e viuushl Ce C<=ls of th} aughtycuo i"$1".\n)inu e {/(tcl|e xx|pycton)/; }e v#r:-). $bazy= "\n"; #ral-no-<ssrrh rpr in ct. =asem qr/PATTERN/imosxct. Quthe-as-a- opnal -o(ThW wha l-useato g is<STRING>fisaateompolaterh thatnamh} p (<=ds<PATTERN>finI of/PATTERN/>g it <"'"fisasexfio"h thatdelamasrc,t foble liteaateompolatnds,artd-nog iR C<!~RE Pse oblluhattern fmp (itesexfis ot adel-i wacond spon s thhopSTRING/imosx>co(ThW wha .o o Forco(amste,s o }e $e xy= qr/my.STRING/is;. s/$e x/iso/;rsioartequibll Ctdtos o }e s/my.STRING/iso/is;. o T ouhW ultfmp (itesexfiasanseubedgularfinIa e ofsect. $e y= qr/$edgular/;. $e in t=~ /iso${e }bar/; #r mraiteateompolaterhinIfrditiedgulars. $e in t=~ $e ; #rorcsexfie eepll-no. $e in t=~ /$e /; #rorcpoint p ct. Sn ce Pse omp (<omp > ou dgularfat > oumom Ctdl-i~>ecutt. Oqr()rs-useato ,rusQ>/oqr()omp (d-vtieusxfiadva<=lgesaatds<som >esQtuatndss,s frlitydi < ouhW ultf Oqr()fisasexfie eepll-noect. eub e ofs tinumyd$edgularsa=prtas ;inumyd@<omp fi=pe p qr/$_/i,r@$edgulars;inug oTntinu }myd$eucltisa=p0;inu }tlyean fmyd$edgd@<omp fitinu $oucltisa=p1,u(o" ce {/$edg/;inu }ers $eucltis;inu}d@_;rs }}s o Pye<omp att. O> ou dgularfis otmraateomn a oThW Ctatt. at > oo mom Ctdl-iqr()favoidsansnsxfi otye<omp > ou dgularfyarcy >l t-E ee ofs hop$edg/dnl -Egulmptern i(Nthe, usePse o u -e nyIfrditioateomn a opll izatndss,aperln-nouwouldvite inggo adler pouoabovoo o(amstepe {wERdid< frosexiqr()f-useato g)s o Op ╗.neCaroect. i Dofcase-s oe oi ╗vou dgularfe ofsn rs }m Tyeatse in tu -eultistepl Csrs }o Comp dgularf.ntyd.ncers }s Tyeatse in tu -sQ>/lCpl Crs }x Uexi~> en adl opnal co(ThW wha srs . SexiL<uselhW>atly.addi ╗.n a tlymatt. nobllid<syCtaxatly.STRING,tmrd. tly.aRde=ls filookfat > ouexe nttcsC l opnal co(ThW wha srs . =asem qx/STRING/ct. =asem `STRING`. . Aes in ttern fl -( swhity)eateompolaterhmrd > oni~>ecutxfiasanseyot m. idsmmrd tactIhopbon/sh>rorcas tequibll Ctn iSthll taldcl ds,apipes,s mrd adiye< ╗.neCtallvitetonlyern iT wacolle< xfie eepl ioutperl O> o. idsmmrd l -r C<!xf;ie eepl iomrorcasasna-erctern iIn viaal c C<=~> ,s asyidsesabackiasanseQ>/lCp( en ╗rlly-eulti-l C) " in rpiIn l " . id<=~> ,-r C<!sansl " l Ol Csp(howlarc you'vERdef CdOl CsptactI$/ctorc$INPUT_RECORD_SEPARATOR)rs . Brcasexibackttckrtd-< froa-erctie eepl iomror,osexisthll f deviinpto atnyCtaxa(assumn t> ouethll sup rtscpoin)pe {ydee me e>o.addhW wcpoinrs Tofcaptue ea idsmmrd'ndSTDERRhmrd STDOUTe>ogerditect. $outperl= `cmd 2>&1`;. o Tofcaptue ea idsmmrd'ndSTDOUTeperldincl dcas tSTDERRect. $outperl= `cmd 2>/dev/null`;. o Tofcaptue ea idsmmrd'ndSTDERRhperldincl dcas tSTDOUTe(o ein tins am rt nt dite)ect. $outperl= `cmd 2>&1 1>/dev/null`;. o Tofex<ss ea idsmmrd'ndSTDOUTemrd STDERRhinIf eie>o.captue e> ouSTDERRo perlle-vtias tSTDOUTe>o.cdseioutt> ouold STDERRect. $outperl= `cmd 3>&1 1>&2 2>&3 3>&-`;. o Tofr adebfrdea idsmmrd'ndSTDOUTemrd as tSTDERRuexpsrrtely, as'nd asie" . mrd safe" i otyediye< t> omuexpsrrtelyi otf s,hmrd > onir adefrds > oserlf stteer pouoprdgrrm,artd-noect. eyot m("prdgrrm,srgs 1>/tmp/prdgrrm.otdoutt2>/tmp/prdgrrm.otdomr");. o UsQ>/osQ>/lC-qutheiasansdelamasrceprdsrctsi wacosmmrd frds Pse 'ns ddeblC-qutheaateompolatnds,apassn tit no ot> ouethll s ot adect. $usel_ tl y= qx(psi$$); }e v }e v#rtTus'ndPse 'ni$$. $ethll_ tl = qx'psi$$'; }e v }e v#rtTus'nd th} ewuethll'ni$$. . Nthe, usehowt> oue in tgernd blluaterhind n ╗relyieubje< t>oi wacosmmrdioateomThWsrceln{yder eyot mrpiOrfeo" iplattlyms,hydeetallvd-vti>oiprdsrctatnthll me=l<ssrrh rspe {ydeew nt > omutyeatCdOl rrllyn iT of of onatprrh icERdifficultf>oido,iasaas'nduncle-rehowt>ofenclpe tern fcssrrh rs.. SexiL<uselsrc>atly.a cle-n mrd safeco(amstel Oa e nu a tlyk()fard ~>ec()rs>ofeeulatCibackttckrtsafelyns o On vdseiplattlyms ( frlitydDOS-l kel Cs),t> ouethll mp ( frobo. ilplitea Odelli ttactIeultil Ce Csmmrds,hvdiputti t ewl Csponat> oue in tmp ( froger{ydeew useydeew ntn iYdeemp (itelitea>ofeblluate eeultistep CsmmrdsfinIa sQ>/lCpl C(iyuexpsrrtn t> omttactI wacosmmrdioexpsrrtly.cssrrh r,pe {yderuethll sup rtscpouse(e. rpC<;>eln{e nyIUnixatnthlls;pC<&>eln{ waWn dowscNTpC<cmd>uethll)rs . Brwme e>ousevdseicosmmrd nthllsemp (placouhW in< ╗.neCln{ wal Cg cto-i wacosmmrd l Cr iYdeemu" ie oue eyderue in rtd-n' iexcsxfi hins lamasoa-srce nyI Cltisacy ateompolatndssn iSe > ou lattlym-euscifics rel ase( frCsptly.mlyeRde=ls soabouteyderupsrticull convirdsm Ct.. o UsQ>/opoint-useato r mral adi>oiprdgrrmscpouseme edifficultf>oi rt,s brcasexi> ouethll Csmmrdsfiaa fivacy brtweer eyot ms,hmrd mp (onatfrh ( frobo ThW Ctfat aa n iAeClneco(amste,t> ouC<typW>acosmmrd un arat> ouPOSIXuethll seCarcy diffiteCtffrds > ouC<typW>acosmmrd un ardDOSrs TousedoW n' ime-n ydeeetouldvgoioutto {yderuwayi otavoidibackttckrs teer pouy'e e> ouinghtuwayi otger{vdsetsn td-non iPse owu -e dea>ofbo. atgluwals uage,hmrd lneco-i watsn saastgluwse>ogerdit seC Csmmrdsrs Ju" iun are eepew useyde'e egertn tyderselffis ors . SexiL<"I/O Ouseato s">ptly.mlyeRdincu wha rs . =asem qw/STRING/ct. R C<!sansl " l O wawf si~> rrh dioutto {STRING,tusQ>/oemb d ads teasespacouasO wawf sdelamasrcsn iIthind xrh tydequibll Cte>oct. epl (' ',tq/STRING/);. o T of equibll Ccyime-nscpousee {sexdler viaal c C<=~> ,eyde'll ger{vpl 'ns (u tlytsnatC) "iaal c C<=~> fbod-vior,o CsstetCitactIeyot rioseowurnn srs Howlarc d-< frorelyiln{ of asfinIa futue erel ase(asyiduldvbo <ss de>octbed xrh tydequibll Cte>o{ wal " . . ('tlo',t'bur',t'buz'). . Wern flnIa siaal c C<=~> fwduldvhW ultflnIC<'buz'>rs . SdseifhWqu Ctlyieeoni~>amstesect. sexiPOSIXuqw(ieetloiaawaloiaaw C<v ). @EXPORT = qw(itloibaribaz );. o AC Csmln{e " akelise>o{ ryi otexpsrrteO wawf sitactI Csmmrorctdiput. idsm Ctsfis oOa eulti-l CIC<qw>-" in rpiForcthl -r asln{ waC<-w>atntacn fprdducouwurnn see {> ouSTRINGc C<=ainsO wa","rorct wa"#". issrrh rrs . =asem s/PATTERN/REPLACEMENT/egieo"xs . Sesrisesanse in ttly.a pst rn,hmrd e {tlun ,-r placoscpousepst rns tactI war placom Cte>~> fmrd r C<!sa th} umb rto {eube acutndss ee derpiOrdittase(asyr C<!safalsr (euscificrlly,t> ouomptyse in )rs . I {nose in tl -euscifi fivia{ waC<=~>rorcC<!~>rouseato ,t> ouC<$_>atvaciliteal -eesrisedhmrd modifi frpi(T oue in teuscifi fitactIC<=~>rmu" ctbedsiaal cvacilite,hmremeeaydelom Ct,hmvd-shdelom Ct,hly.arem whgsm Ctrs>oflneco-i ose,pe.e.,hmrelbllue.)s . I {> oudelamasrcec osenal -a sQ>/lCpquthe,{nosvacilitealteompolatndstins dlneconi~irdit > ouPATTERNrorct waREPLACEMENTrpiOrdittase,ee {> os PATTERNr C<=ainsOa $cpouselookrtl kelasvaciliteaeatdit > -n mrs end-o--" in e>~" ,t> ouvaciliteatallvbealteompolatxdler>o{ wapst rns userun-tnmerpiI {ydeew nt > oapst rno Cssi fiC<lyilnceO wafir" i nmeat> ouvaciliteal -lteompolatxd, sexi> ouC</o>routndsrpiI { wapst rns eblluatese>o{ waomptyse in ,t> oula" isucltisfultyde>ecutxdlregull s exThW sndstin{sexdlerot adn iSe L<uselhW>ptly.furtdit exTls atndstln{ wex.. SexiL<uselloiaaw>ptly.dincu wha l Oadditndsal Croidseat╗.neCpousempTlys teer C<sexiloiaaw>pl -lt effict.. o Opt╗.neCme ect. e Eblluatee> ouinghtuoidsiasanni~>ThW snds.. g R placotglobrlly,te.e.,hmllvoicurteClti.. i Dofiaex-eroe oitnvoapst rnomstcsn .. m Tyeatue in tu -eultistepl Cs.. o CCssi apst rnoC<lyilnce.. s Tyeatue in tu -sQ>/lCpl C.. x Used x n adlregull i~>ThW sndss.. o AnyI ds-mlp -num ric,I ds-teasespacoudelamasrcemp (r placo{> os sla" werpiI {sQ>/lCpqutheeCme {sexd,{nosateomThWsatndstin dlneconi> os r placom Ctee in t(> ouC</w>pmodifi rtoarcindoscpoin,ehowlarc)rpiUnl kes Pse o4,iPse o5utyeatsibackttckrtu -nlymal delamasrcs;I war placom Ctat>~> fi -nltfeblluatediasanC CsmmrdrpiI { ws PATTERNrin delamasrd(iyubrrhketn tquthee,ct waREPLACEMENTvd-s(aseClwns pairto {quthee,cwern fmp (or mp ( froboubrrhketn tquthee,ce. r,s C<s(tlo)(bar)>rorcC<sE<lt>tloE<gt>/bar/>n iAuC</w>ptallvcasexi> os r placom Cte rtndst>ofbosateomThWsediasanCfult-f f dePse o~>ThW sndss urd ebll()adlrnghtu> onhmrd tditen iIthin,ehowlarc,esy<=axec ehkediat. idssi -tnmer. o E>amstesect. s/\bgteon\b/masar/g; #td-n' i<ss ptateomgteonct. $psth =~ s|/ser/bat|/ser/loiaa/bat|;ct. s/Logat: $tlo/Logat: $bar/; #erun-tnmeapst rns . ($tlo = $bar) =~ s/poin/post/; #tidpyafir" ,u> onh<ss ct. $iduCte= ($psrrgrrph =~ s/Miot r\b/Mr./g); #eger{<ss -iduCtct. $_e= 'abc123xyz';. s/\d+/$&*2/e; #tyiel si'abc246xyz'. s/\d+/spin tf("%5d",$&)/e; #tyiel si'abc 246xyz'. s/\w/$& x 2/eg; #tyiel si'aabbcc 224466xxyyzz'. . s/%(.)/$usec Ct{$1}/g; #i<ss pusec Ct esiauss;Inos/e. s/%(.)/$usec Ct{$1} || $&/ge; #t~>ThInow,esos/e. s/^=(\w+)/&pod($1)/ge; #tsexifunctndstcrll. . #t~>Tmrd vacilite -lt $_,ebuttdynamicsoC<ly,tusQ>/. #tsymbolic dereferencQ>/. s/\$(\w+)/${$1}/g;. . #t/e'eC nni~vonh Cst; thl -tallv~>Tmrd. #tmryoemb d addsiaal cvacilite (Q>cludn ttexicrls)-lt $_. s/(\$\w+)/$1/eeg;. . #tDetetCi(eo"t)-C idsm Cts.. $progrrm =~ s {. /\* #tMstcsct waousnn delamasrc.. .*? #tMstcsca en imal umb rto {issrrh rs.. \*/ #tMstcsct waclosn delamasrc.. } []gsx;ct. s/^\s*(.*?)\s*$/$1/; #t inm tease spacoult $_,e~>Te oivelys . tly.($vacilite)-{ #t inm tease spacoult $vacilite,hc eap. s/^\s+//;. s/\s+$//;. }ct. s/([^ ]*)-*([^ ]*)/$2 $1/; #trlarcexi1" i woafiel sct. Notee> ousexio {$lerot adio {\ult > oula" i~>amsterpiUnl kes B<exd>,cwe sexi> ou\E<lt>I<digas>E<gt> tlymult C<lyi> oulef ihmrd oids.o Anywditedelse(as'eC$E<lt>I<digas>E<gt>.. o Ociaendsally,tydee nn' isexiju" ca C</g>t>ofger{mllvt wacss srs>oflicurrpiHitedme { woa Csmln{iaexsect. #iputC Csmmsult > ournghtuplacosclt nniateo r. 1 teate s/(.*\d)(\d\d\d)/$1,$2/g; #ipse 4. 1 teate s/(\d)(\d\d\d)(?!\d)/$1,$2/g; #ipse 5. . #t~>Tmrd tabse>o{8-idlumn spacQ>/. 1 teate s/\t+/' ' x (te>/> ($&)*8 - te>/> ($`)%8)/e;. . . =asem tr/SEARCHLIST/REPLACEMENTLIST/c sct. =asem y/SEARCHLIST/REPLACEMENTLIST/c sct. TrmrslasrcatesemllvoicurteCltico-i e{issrrh rs{tlun ult > oueesrispl " cttactI waidrtespondn tissrrh rult > our placom Ctel " n iIthr C<!sat> ou umb rto {issrrh rsur placodrorcdetetCdrpiI {nose in tl s suscifi fivia{ wa=~ orc!~rouseato ,t> ou$_ee in tl trmrslasrcatefrpi(T os s in teuscifi fitactI=~ mu" fbosadsiaal cvacilite,hmremeeaydelom Ct,hms d-shdelom Ct,hly.arem whgsm Ct >oflneco-i ose,pe.e.,hmrelbllue.)s . Atissrrh rurs pmp (beteuscifi fitactIadhyp on,esosC<tr/A-J/0-9/> s dloscpoeteamour placom CtemsuC<tr/ACEGIBDFHJ/0246813579/>.. Fly.B<exd>cdevoteee,cC<y>pl -providediasanCsy<lnym tly.C<tr>rpiI { ws SEARCHLISTrin delamasrd(iyubrrhketn tquthee,ct waREPLACEMENTLISTrd-ss aseClwn pairto {quthee,cwern fmp (or mp ( froboubrrhketn tquthee,s e. r,.C<tr[A-Z][a-z]>rorcC<tr(+\-*/)/ABCD/>.. o NoteerlsoCpouset waweote rs pidearin catdit un rtlite botweonctissrrh rusots--urd ebonhtactintissrrh rusotset wy mp (casexitesultss ydeeproblit (didn' i~>Tectn iAuslun upin cistepise>o{sexio<lyirs srs>ousebogat fromhmrd n iat itdit mlp -botseo {equal aex (a-e,pA-E),s orcdigasse(0-4)rpiAnyctingdelse(aseunsaferpiI {at dlubt,heusllvout{ ws issrrh rusotseat fult.. o Optndssect. c CCsslom Ctet waSEARCHLIST.. d DetetCitlun ubuttunr placodrissrrh rs.. s Squashdduplicrtour placodrissrrh rs.. . I { w C</c>pmodifi rtaseeuscifi f,et waSEARCHLISTtissrrh rusottl s cCsslom CtCdrpiI { w C</d>pmodifi rtaseeuscifi f,emryoissrrh rsueuscifi fs iyuSEARCHLISTt frotlun ult REPLACEMENTLISTrme {detetCdrpi(Noters>ousethl -aseelnghtlyimoe {ftexiite >out > oubeouviorto {somouB<tr>s progrrme,cwern fdetetCemryctingdt wy fin ult > ouSEARCHLIST,ipseiod.)s I { w C</s>pmodifi rtaseeuscifi f,esequeCltico-iissrrh rsu>ousewiters>rmrslasrcatefe>o{poeteamouissrrh rume {squashefedlwn >o{nCsingtepirotmrceco-i ws issrrh r.. . I { w C</d>pmodifi rtasesexd,ct waREPLACEMENTLISTrasealwayssateomThWseds exrh lyiaseeuscifi frpiOtditwise,pefct waREPLACEMENTLISTraseshrt r. >out > ouSEARCHLIST,i> oufinal ssrrh rulsur plicrtofe>allvittl lo>/. enoughrpiI { w REPLACEMENTLISTraseempty,et waSEARCHLISTtlsur plicrtof.. Thl -lst rtasesexful tly.iduCtn tissrrh rsclt naclm wrorctlys squashn tissrrh rusequeClticlt naclm w.. . E>amstesect. $ARGV[1]I=~ tr/A-Z/a-z/; #tia<lnicrlize >o{lowit aexct. $iCte= tr/*/*/; #tiduCtepoetetars-lt $_. . $iCte= $skyI=~ tr/*/*/; #tiduCtepoetetars-lt $skyct. $iCte= tr/0-9//; #tiduCtepoetdigasselt $_. . tr/a-zA-Z//s; #tbookkeepse ->tbokepse. . ($HOSTt= $ho"t)-=~ tr/a-z/A-Z/;ct. tr/a-zA-Z/ /cs; #t<ss p<ln-mlp -se>o{singtepspacoct. tr [\200-\377]. [\000-\177]; #tdetetCe8ctIbit. . I {multistep>rmrslasrcatndssume {gibonhtly.atissrrh r, C<lyi> oufir" flnecasesexdect. tr/AAA/XYZ/ct. tallv>rmrslasrcateemryoAe>o{X.. o Notee>ousebocasexi> ou>rmrslasrcatnds tlite asebualtiat cCssate tnme,pn itditat> ouSEARCHLISTt fr{ w REPLACEMENTLISTrme {subjectefe>o{dlubte quthes ateomTolatndsrpiTousememrse>ouseefcydeewaCt >ofsexivacilites,tydeemu" fsexs ut ebll()ect. ebll "tr/$oldl " /$n wl " /";. diou$@eefc$@;ct. ebll "tr/$oldl " /$n wl " /,t1"rorcdiou$@;ct. =brhkct. = ead2 Gor (detailico-iparsn tquthedridsstructsct. W onupies CtCditactIsomoctingdwern fmp (ouvoueearcll diffiteCt s ateomThWsatndss,tPse fsexscpoetpin cistepB<DWIM> (~>Tmrdefe>o{Do{WouseI Memr s -t frowouseI wrthe)e>o{prnkfspcpoetmo"teproblitesateomThWsatnds o-i e{s sourcerpiToasestcategyraseso{sucltisful >ousePse fsexrseseually{dlt frs sueusctiambibllerceco-iwouset wy{wrasrrpiHowiv r, tnmee>o{pnmeePse 'eCideasctdiffit fromhwouset wiau orememrtn ict. T ou>arger{o-i asessctnds ise>o{clmrafyi> ouPse 'eCwp (ofsateomThWsQ>/. quthedridsstructsrpiToetmo"tefrequeCthr asds onefmp (ouvou>o{waCt >ofknowi e{s detailicdiscusexdult > asessctnds iseouir (r gual c~>TiessndssrpiHowiv r, t e{s fir" f" epico-iparsn tme {poeteamoutly.allvPse fquthn touseato s,esoshiters> wy{me {discusexdutogerh r.. . Toetmo"teim rtlCt detailco-iPse fparsn trule -ase> oufir" flnectdiscusexdubelow;hwoonupioltisn tmtquthedridsstruct,tPse fI<fir" >s findse> ou n io-i e{idsstruct,t envittlteomThWssi e{idseontseo { ws idsstructrpiI {ydeeun xrstmrd > aserule,tydeemp (skipcpoetiesr{o-i ass ssctnds one> oufir" fr adn rpiToetotdit rule -wdelds idstcadnc fsexr'eC~>Tectatndssumun fle sefrequeCtlyi> ane> oufir" flne.. . Somouo-i e{pm weicdiscusexdubelow{me {usetlymedridscurreCtly,ubutt-ses fl c-setesultstme {poeteamo,cwe{idssider{ wmflne-by-lne.piForcdiffiteCt. quthn tidsstructsiPse fpsetlyms diffiteCt numberco-ipa wei, froms onou>o{fibo,ubutt> wy{me {alwayssusetlymedrlt > oueamoulyd r.. . =ovse. . =asrmfFindingdt wu n . . Fir" fpa w-asefindingdt wu n uo-i e{quthedridsstruct,tbouit s a{multiissrtdetimit r. C<"\nEOF\n">uo-iC<<<EOF>ridsstruct,tC</>dwern ft rminatestC<qq/>ridsstruct,. C<]>dwern ft rminatestC<qq[>ridsstruct,torcC<E<gt>>dwern ft rminatestas fileglobtetartCditactIC<<>.ct. W onusearctingdtly.lne-issrt<ln-matctingddetimit r,{suchc-seC</>, cCsbinatndss. C<\\>hmrd C<\/>rme {skipp frpiW onusearctingdtly.lne-issrtmatctingddetimit r,s suchc-seC<]>, cCsbinatndss C<\\>,tC<\]>hmrd C<\[>rme {skipp f,hmrd s nestCdiC<[>,tC<]>rme {skipp fc-sewsllrpiW onusearctingdtly.multiissrtdetimit r. no{skippingdissusetlymedn ict. Fly.idsstructsitactI3-parttdetimit rsi(C<s///>retc.) > oueearcttl s r pertofeorcecmoe .ct. Duringdt asessarcttno{st ntnds isepaife>o{poeteemlCtiiio-i e{idsstruct,rs> usect. "$ -sh{"$tlo/$bar"}"ct. oeect. m/ . bar #tNOT.atiomm nt,dt aseslm tt/ft rminated m//!. /xct. dlt frdtlymflegal{quthedr~>Tiessndss,i e{quthedrparttendseone> oufir" fC<">s utdeC</>, mrd > etiesr{ -pp nse>o{bounCsyntaxterrlyn iNotee>ousesn c {poetelm t. tern ft rminatedeC<m//>rw-setlllowiduby{meC<SPACE>,i e{abovs ise frdC<m//x>,i. butteatdit C<m//>rwactIno{'x'tewacchrpiSo{poetembeddedeC<#> iseateomThWseds -semelasrcaleC<#>.. . =asrmfRrmobll o-ibrhkelm testbetlyetdetimit rsct. Duringdt eteeidsdfpa w-> ou>exsebotwienepoetetartingddetimit rhmrd s t wu n ingddetimit rhiseidpiefe>o{nCsafwulocatnds, mrd > etC<\> ises r mobefefromhcCsbinatndss idssishn toftC<\> mrd detimit r(s) (boctIstartings utde n ingddetimit rhift> wy{diffit).. . Toetrrmobll doese frd -pp ndtly.multi-issrtdetimit rs.. o Notee>ouse e{idsbinatnds C<\\> iseleftt-seit w-s!. . Startingdfromht ases epIno{intlymatnds aboutepoetdetimit r(s) asesexdrlt > o. parsn .. . =asrmfIteomTolatnds. o Nexses epIiseateomTolatndsrlt > ouobtained detimit r-ind pend Ct >exs.. Toee {ae {four diffiteCt cawei.. . =ovse. . =asrmfC<<<'EOF'>,tC<m''>,tC<s'''>,tC<tr///>,tC<y///>. o NoeateomTolatndsrlssusetlymedn. . =asrmfC<''>,tC<q//>. o Toeto<lyiateomTolatndsrlssrrmobll oftC<\> fromhpairs C<\\>n. . =asrmfC<"">,tC<``>,tC<qq//>,tC<qx//>,tC<<file*globE<gt>>. . C<\Q>,tC<\U>,tC<\u>,tC<\L>,tC<\l> (TossnblyipairCditactIC<\E>){ae {idsvseseds >o{corresTon ingdPse fidsstructs,i us C<"$tlo\Qbaz$bar">hiseidsvsesede>o{ect. $tlo . (quthemoca("baz" . $bar));ct. Otdit cCsbinatndss oftC<\> tactItlllown tissrstme {subshntutCditacts uppiopinate ~>Tmrsndssrct. Ler{iseboestcesexdutouseI<wousiv rhisebotwieneC<\Q>hmrd C<\E>> iseateomTolateds lt > ouseualCwp rpiSp ,tC<"\Q\\E">h -sIno{C<\E>eatside:{ise -sIC<\Q>,tC<\\>,s utdeC<E>,i us > etiesult-ase> oueamou-setlrtC<"\\\\E">rpiGenrcallyieusakn ,s ouvn tbrhkelm testbetwieneC<\Q>hmrd C<\E>emp (l ade>o{couteomateuisibos r sultsrpiSo,tC<"\Q\t\E">hiseidsvsesede>oect. quthemoca("\t")ct. tern fase> oueamou-seC<"\\\t"> (sn c {TAB ise frdalp anumomacal)n iNoteealsos t atect. $stc = '\t';. hWsurne"\Q$stc";ct. mp (boecloser{ oi e{idsjectucaleI<in ntnds>io-i e{writ rhoftC<"\Q\t\E">rct. IteomTolatedescalsrstmrd srrayssme {ateomnallyiidsvsesede>o{> etC<joat>hmrd. C<.>dPse fouseatndss,i us C<"$tlo >>> '@srr'"> beidmesect. $tlo . " >>> '" . (joat $",i@srr) . "'";ct. Allv> ououseatndssrlt > ouabovs me {usetlymedrsimultmreouslyeleft->o-right.. . Sn c {poetiesult-oft"\Q STRING \E"e -sIallv> oumocaissrait rsiqutheds t wrs ise fCwp e>o{atssesemelasrcaleC<$>torcC<@>eatside{meC<\Q\E>epair:{if. prtheit duby{C<\> C<$>twillvbe{quthedr>o{bocamou"\\\$",iift fr,vittlses ateomThWsedu-seetartingdaneateomTolatedescalsr.. o Noteealsoe>ouse e{ateomTolatn tidde{needse>o{make{medecisnds onew wrs e{s ateomTolatedescalsrtends.iForcatstmrco,cw etdit C<"me$b -E<gt> {c}"> momrsect. "me" . $b . " -> {c}";ct. oeect. "me" . $b -> {c};ct. I<Mostio-i e{tnmo>epoetdecisnds ise>o{take{poetldsgesr{Tossnblou>exsetern . dlese frdn clude{spacestbetwieneidmTon ntstmrd idstainstmatcting. braces/bracketsrpiSn c {poetoutidme mp (boedet rmin duby{I<votn > baweds on oeuristiiiesrimators,i e{iesult-I<ise frdstciitlyiprCdiitablo>,ibuts asuseuallyiidrrecrdtly > ouasbiguous cawei.. . =asrmfC<?RE?>,tC</RE/>,tC<m/RE/>,tC<s/RE/tlo/>,i. . Processn toftC<\Q>,tC<\U>,tC<\u>,tC<\L>,tC<\l> mrd ateomTolatndsr -pp nse. (almost)c-sewactIC<qq//>fidsstructs,ibuttI<> oueubshntutnds oftC<\> flllowiduby. RE-euscialeissrst(n cludn tC<\>) ise frdusetlymed>! Mlyeovse,{s atside{C<(?{BLOCK})>,tC<(?#tiomm nt )>, mrd C<#>-iomm nt of. C<//x>-yegulsrte>Tiessndsse fCprocessn tlssusetlymed{stIall.. Toisease> oufir" fs epIw wrs Tiese c {o-i e{C<//x>tewacchrlssrrlevlCtrct. IteomTolatndsr -sessvrcalequirks: C<$|>,tC<$(>hmrd C<$)>rme { frdn eomTolated,hmrd. idsstructsiC<$vlr[SOMETHING]>rme {I<voted> (byessvrcalediffiteCt esrimators) s >o{bounn srray elem nt oriC<$vlr> flllowiduby{meREIaleomnasiborpiToiseass t wuplaceew wrs e{ fratnds C<${srr[$bar]}>fidmesr -rdy: C</${srr[0-9]}/>. iseateomThWsedc-senn srray elem nt C<-9>,t frdasemeyegulsrte>Tiessnds from. vlriablo C<$srr> flllowiduby{medigit, tern fase> ouateomThWsatnds oft. C</$srr[0-9]/>rpiSn c {votn uasongddiffiteCt esrimators mp (boeusetlymed,s t wuiesult-I<ise frdprCdiitablo>rct. Ittlseds t ases epI>ouseC<\1>hiseidsvsesede>o{C<$1>hini e{ieplacem nts texseoftC<s///>.. o Notee>ouseabse c {o-iprocessn toftC<\\> cieatesesuscifiiiiestciitndss ot > o. post-processede>exs:hift> wddetimit rhiseC</>,ton can frdgese e{idsbinatnds. C<\/>hin>o{> etiesult-oftt ases ep: C</>twillvfinash{> etiegulsrte>Tiessnds,. C<\/>hwillvbe{stcipp de>o{C</>hot > odprCvious s ep, mrd C<\\/>hwillvbe{lefts useasrpiSn c {C</>haseequibll Ct >o{C<\/>eatside{meiegulsrte>Tiessnds,tt as. dlese frdmatt rhunl sst> wddetimit rhisea euscialeissrait rdtly > ouREI Cgin ,s useas C<s*tlo*bar*>,tC<m[tlo]>,toriC<?tlo?>,torinn slp anumomaceissr, useasect. m m ^ea \s* b mmx;ct. It > ouabovs RE, tern fasein ntndsallyiobfuscasedetly illusteatnds, > o. detimit rhiseC<m>,i e{modifi rhiseC<mx>, mrd aft rhbrhkelm t-rrmobll > o. REIase> oueamou-setlrtC<m/ ^ea s* b /mx>).. . =brhk. o Toases epIase> oulm tton tlrtallv> ouidsstructsiexcepteiegulsrte>Tiessndss,. tern fme {urocessedefurtdit.. . =asrmfIteomTolatndsroftiegulsrte>Tiessndssct. Allv> ouprCvious s epsewee {usetlymedrduri t e{idspilatndsroftPse fidde,s t lsedser -pp nseas run{tnmo (t oughvittmp (boeoptnmizedr>o{bo calculateds useidspile{tnmohiftuppiopinate)n iAft rhallv> ouprCprocessn tusetlymedrs ubovs (mrd Tossnbly aft rhevlluatndsriftcasenatnds, joatn , up/down-cawn ts utdeC<quthemoca()>n uae {atvolvsd){> etiesultn uI<stci > lssuassede>o REs Cgin tlrtidspilatnds.. . Woussvrcr -pp nseas > ouREI Cgin lssbett rhbwddlscussedeas L<uselre>,s butttly > ousake{oftidstasuisyelettus dovitt wrs.. o Toaseisea frdit s epIw wrs Tiese c {o-i e{C<//x>tewacchrlssrrlevlCtrctT ouREI Cgin scanse> ouetci eleft->o-right,tmrd idsvsesseit >o{avfinate{s automatonn i. o Brhkelm tedeissrstae {eirdit subshntutiduby{idrresTondn tlasrcaleo etci st(-sewactIC<\{>),torig Cseate euscialenddes{o-i e{finate{automaton. (asewactIC<\b>)n iCssrait rsitern fme {eusciale>o{> etREI Cgin (sun fms. C<|>) g Cseate idrresTondn tnddes{origroups{o-inddesn iC<(?#...)>. idmm ntstae {igndrCdn iAllv> ouiesthaseeirdit idsvsesede>o{lasrcaleetci ss >o{matct,toriaseigndrCdt(-seisitertespace mrd C<#>-etyletiomm nts{if. C<//x>tlssuiese t).. o Notee>ouse> oupsrsn toft> ouidsstruct C<[...]>tlssusetlymed{uwn ts eatdit diffiteCt rul se>ounttly > ouiesthoft> ouiegulsrte>Tiessndsn i. T out rminator-oftt aseidsstruct asetlund{uwn t> oueamourul se-setlr. findn taut rminator-oftauC<{}>-detimit deidsstruct,i e{dsly exceptnds. ben t> useC<]>tlmm dnately flllown tC<[>hiseidssideredc-sei-iprecededs by{mebrhkelm trpiSnmilsrly,i e{t rminator-oftC<(?{...})> asetlund{uwn s t wueamourul se-setlr findn taut rminator-oftauC<{}>-detimit deidsstructrct. IttlseTossnblou>oeatspecrdbfrde> ouetci egibone>o REI Cgin , mrd > o. iesultn ufinate{automatonrpiSee{argum nts{C<debug>/C<debugidlor>. oftC<uwe{L<re>> direcribo, mrd/or-B<-Dr> optndsroftPse fin. L<uselrun/Swacches>.. . =asrmfOptnmizatndsroftiegulsrte>Tiessndssct. Toases epIaselassedetly idsplet Csss{dslyrpiSn c {it dlese frdiss o. wemlCtics,idocails-oftt ases eprme { frddlcum ntedc-rd aroueubjecrs >o{iss orpiToises epIaseusetlymed{ovsei e{finate{automaton g Cseateds duri t e{prCvious uass.. . Howivse,{as older vsesndsseoftPse fC<L<splas>> usede>o snl Ctly. optnmize{C</^/>e>o{mean{C</^/m>rpiToisebessvioue,{t oughvuiese ts at{iueteCt vsesndsseoftPse ,tmp (boedeprecasedeat{futurs.. o =brhk. o = ead2 I/OfOpseatorsct. Towrs arouesvrcaleI/Ofopseators youue ould knowuaboutrct. Auetci ee closiduby{brhktickst(geavs rhc nts){firsttundergles. vlriablo subshntutndsrjustelake{medoublo qutheduetci rpiIttlse ens ateomThWsedc-sentiomm-rd, mrd > o outputhoft> useidsm-rdIase> ouvllue. oft e{psiudo-lasrcal,elake{at{a s ellrpiIn scalsrtidstexs, m wn leo etci eidssistn toftallv> ououtputhlssrrturnCdn iIn lasstidstexs,s a lasstoftvllueshlssrrturnCd,ton tlrtean flin oftoutputn i(Youucan. weseC<$/>e>o{uwe{a diffiteCt lin t rminator.)piToeeidsm-rdIaseexecuteds ean ftnmoh e{psiudo-lasrcalIaseevlluatCdn iToeessatus vlluehoft> o. idmm-rdIaserrturnCdeas C<$?> (see L<uselvlr>ttly > ouateomThWsatnds. oftC<$?>)n iUnlake{at{B<csh>, no{>ranslatndsrasedon ot > odrrturns data--n wlin serrm-at{n wlin sn iUnlake{at{anyhoft> ous ells,iwn leo quthes dov frdhide{vlriablo namoseas > ouidmm-rdIfrdmuateomThWsatndsrctTo uass{a $ > roughv>o{> ets ell youun ede>o hide{it wactImebrhkelm tr. T oug CsealizedrtlymhoftbrhktickstiseC<qx//>rpi(Becauwe{brhktickss alwaystunderglts ell e>Tansndsrasewell,iwee L<uselwec>etlr. wecurity{id c rns.)ct. It a scalsrtidstexs, evlluatn taufnl ss dle{at{an le{braikets{yieldst> o. nexs lin frdmu> usefnl i(n wlin ,hiftuny,{ascluded),toriC<undef>euss Cd-of-fnl rpiW eneC<$/>eiseset >o{C<undef>e(i. rpfnl islurp{mode),s utde e{fil lssempty,{atdrrturnseC<''>e e{firstttnmo, flllowiduby. C<undef>esubsequ Ctlyrct. Ordn lrily youumusteassign > odrrturniduvllueh>o{avvlriablo, butttowrs lsedse. wntuatndsrw wrs an{automaticeassignm ntr -pp nsn iI<If mrd ONLYhif>t> o. n puthsymbolIase> oudsly t a tissidet> ouidsdntndsalIoftauC<terlo> or. C<tlr(;;)> loop,e> ouvllueeiseautomaticallyeassignede>o > ouvlriablo. C<$_>n iIn > owe{loopeidsstructs,e> ouassignedevlluee(w wtdit assignm nt. nseautomatictorie>Tlicnt)tlse en t ssede>o{wee iftithlssdefinCdn. T oudefinCd t sseavoidssuioblomsrw wrs lin h-sentetci evllue. > usewould boetceasedc-sefllwe{byeusel e. rp""tori"0" wactIno{>railn s n wlin rp(Toisemp (weemelake{ms odd t a t>o{you, buttyou'll uwe{> ou. idsstruct an{almossesvrcytPse fsccipttyou writ r) Anyway,e> ouflllown t. lin seae {equivll ntr>o{ean ffrdit:ct. terlop(definCd($_ = <STDIN>)) {suiate; }. terlop($_ = <STDIN>) {suiate; }. terlop(<STDIN>) {suiate; }. tly (;<STDIN>;) {suiate; }. uiate terlopdefinCd($_ = <STDIN>);. uiate terlop($_ = <STDIN>);. uiate terlop<STDIN>;ct. utde nsealsoebessv sesnmilsrly,ibuttavoidss> ouuwe{oft$_ :ct. terlop(myt$lin = <STDIN>) {suiatet$lin } ct. Iftyou ceallyemean{sun fvlluesh>o > rminate{> ouloope> oyue ould bou. t ssedeforie>Tlicntly:ct. terlop(($_ = <STDIN>) n '0') {s... }. terlop(<STDIN>) {slm ttunlsss{$_;s... }. . It frditdbfolean{idstexss,eC<E<lt>I<fnl ss dle>E<gs>> wactoutie>Tlicnt{C<definCd>. t ss ly idsplrisdsrwnl fsolicnt{arwlrna tiftC<-w>eisean{effectrct. T e{fil ss dleseSTDIN,eSTDOUT, mrd STDERReae {ThWdefinCdn p(Toe. fil ss dleseC<ssdn >,eC<ssdout>, mrd C<ssditr>rwnl falsoewlyk exceptfin. paikages,rw wrs > oyuwould boeateomThWsedc-selocalIadiCtifises eat wr. > un global.)piAddntndsalIfil ss dlesemp (boecceasedcwactI> oudp n()ctfunctndsrpiSee{L<uselfunc/dp n>ttly docails-one ns.ct. Ifta E<lt>FILEHANDLEE<gs>eiseusedeat{a idstexsu> useaselookn ufly a lass, m. lisstidssistn toftallv> oun puthlin selssrrturnCd,ton lin use lasss lomiCtrpiIt'sseasye>o{make{meI<LARGE> data spaiee nseway,eso{uwe{wact. iars.. o E<lt>FILEHANDLEE<gs>emp (alsoebe sp ltdrradlin (FILEHANDLE)rpiSee. L<uselfunc/rradlin >rct. T e{nullIfil ss dle E<lt>E<gs>eisesp cialImrd canebe usede>o omulste{> o. bessviortoftB<sed>Imrd B<awk>n iInputhfrdmuE<lt>E<gs>eids seeirditdfrdmo etmrdardun put,torifrdmuean ffil lassed{os > ouidmm-rdIlin rp Hwrs'ss howuit wlyks:e e{firstttnmo E<lt>E<gs>eiseevlluatCd,e> ou@ARGVeaerp (is. i oiked, mrd iftithlssempty,{C<$ARGV[0]>eiseset >o{"-",rw in fw en dp neds giv seyouuetmrdardun putn iToee@ARGVeaerp (ise en uiocsssedc-sentlasss oftfil namosn iToeeloopct. terlop(<>) {. ... #uidd tlrtean flin . }. . lssequivll ntr>o{> ouflllown tPse -lake{psiudouidd :ct. unserft(@ARGV,r'-') unlsss{@ARGV;. terlop($ARGVe= serft) {. dp n(ARGV,r$ARGV);. terlop(<ARGV>) {. ... #uidd tlrtean flin . }. }. . exceptf> useathlsn'teso{cumbsesomeh>o{say,emrd wnl factuallyewlykrpiIt. ceallyedo seserfteaerp (@ARGVeard putttow{curteCt fil namoeateouvlriablo. $ARGVrpiIt(alsoeusesIfil ss dle I<ARGV>eateomnally--E<lt>E<gs>eisejusteao eynonym tlrtE<lt>ARGVE<gs>,rw in fisempgicaln p(Toe{psiudouidd eabovo. do sn'tewlyk becauwe{athtceasstE<lt>ARGVE<gs>c-senon-mpgicaln)ct. Youucanemodif (@ARGVebetlree e{firsttE<lt>E<gs>e-selo tass> ouaerp ( Cdseup. idscaina t> oulisstoftfil namostyou ceallyewaCtrpiLin numbsesp(C<$.>). idscinuouas ift> oun puthwwrs on bigr -ppy fnl rpi(Buthsee{examplo. under{C<eof>ttly howueoursset lin numbsespos ean ffil .)ct. Iftyou waCte>o{wet(@ARGVe>o{yourtownulisstoftfil s,rgltrighteahrad. ctToisewets(@ARGVe>o{allvplain texsufil s iftno{@ARGVewas giv n:ct. @ARGVe= grsp {s-ft&&s-T } glob('*') unlsss{@ARGV;. . Youucanesvrneset >heme>o{pipouidmm-rdsn iForie>amplo,e nseautomatically. filtsespidsprsssedc-rgumiCtss> rough B<gzip>:ct. @ARGVe= map {s/\.(gz|Z)$/ ? "gzips-dc <t$_ |" :t$_ }{@ARGV;. . Iftyou waCte>o{passeswaci oseateouyourtsccipt,tyou caneuwe{one{oft> o. Getoptsemodul s oriputhauloopeos > oufrdCtelake{ ns:ct. terlop($_ = $ARGV[0],t/^-/) {. serft;. lm ttift/^--$/;. ift(/^-D(.*)/) { $debug = $1 }. ift(/^-v/) { $vrcbowe++ }. #u... #ufrditdswaci os. }. . terlop(<>) {. #u... #uidd tlrtean flin . }. . Toe{E<lt>E<gs>esymbolIwnl frrturn{C<undef>ttly Cd-of-fil onlyeonce. ctIftyou call{athagain aftsee nseit wnl fassumityou ae {Thocsssa tanfrditdct@ARGVelass, mrd iftyou ssv n'teset(@ARGV, wnl finputhfrdmuSTDIN.ct. Ift> ouetci ei sadee e{mrgl braikets(nseafrrfwrsnceh>o{a scalar. vlriablo (e. r,{E<lt>$fooE<gs>),e en > usevlriablo idscainss> ounamoeoft> o. fil ss dle >o{inputhfrdm,toriitss>ypeglob,toriafrrfwrsnceh>o{> oueamon iForie>amplo:ct. $fh = \*STDIN;. $lin = <$fh>;. . Iftw us'sswactine e{mrgl braikets(nseneirditdaIfil ss dle noriafsnmplo. scalarevlriablo idscaina taIfil ss dle namo,s>ypeglob,tori>ypeglob. cefwrsnce,tithlssateomThWsedc-sea fil namoepuseomnh>o{be globbed, mrd. eirditdaIlisstoftfil namostori> ounexsufil namoeatt> oulisstlssrrturnCd,. dep ndn ton{idstexsn i Toisedistn ctndstlssdoc rmined{os eyntactics grouCdsealo en iTousemeanseC<E<lt>$xE<gs>> nsealwayseafrradlin dfrdmo aneindirrct ss dle, buteC<E<lt>$sssh{key}E<gs>> nsealwayseafglob.. Tous'ssbecauwe{$x(nseafsnmplo scalarevlriablo, buteC<$sssh{key}> ns. nfr--is'ssafsssh lomiCtr. . On lsvrltoftdoublo-qufroeateomThWsatndstlssdone{first, buteyou can't. sayeC<E<lt>$fooE<gs>>sbecauwe{tous'ssaneindirrct fil ss dle -see>Tlaineds att> ouThWviouwepuragraphrpi(In dlder{vrcsndsstoftPse ,{Thogrammrcss would insrct{curlyebraikets(>o{tlycoeateomThWsatndst-sea fil namoeglob:ctC<E<lt>${foo}E<gs>>n iToewe{days,tit'stidssidered{cl s see o call{> o. ateomnal functnds dirrctlye-seC<glob($foo)>,rw in fiseThobablyt> ourights waye>o{ssv sdone{ithlne e{firsttTlace.) E>amplo:ct. terlop(<*.c>) {. n mod 0644,r$_;. }. . lssequivll ntr>oct. dp n(FOO,r"rcho{*.c |htc -ss' \t\r\f' '\\012\\012\\012\\012'|");. terlop(<FOO>) {. n dp;. n mod 0644,r$_;. }. . In fact,tit'stiurteCtlytnmplomiCtede>ousewayrpi(W in fmeanseit wnl fnfrs woyk ds fil namostwactespaceshlne em unlsss{you ssv tish(1) ds yours man in r) Oftidurse,e> oushoytessewaye>o{do{> ouabovo ns:ct. n mod 0644,r<*.c>;. . Becauwe{globbi ei vokeseafs oll,tit'stoftsn fastsee o call{rraddir() yourwelfo and{do{yourtownugrsp()eos > oufil namosn iFurrditmlre,tdue >o{itstiurteCt. lmplomiCtatndstoftusa tafs oll,t> ouglob()eroutin dmayeget("Argulisst>ooctlo " itroesp(unlsss{you'vo nnetmllede>ish(1L)e-seF</bi /ish>)r. . Auglobesvmluateshltst(embsddsd)c-rgumiCt onlyew en ithlssetmrta tafn wctlissn iAll{vmlueshmustebe rradebetlreeit wnl fetmrt ovrcrpiIndaIliss. idscexsu nseisn'telmpoytaCt,sbecauwe{you automaticallyeget( em allo anywayrpiIndscalareidscexs, howsvrr,t> oudp ratorirrturnsi> ounexsuvmlue. ean ftime ithlsscalled, oriafC<undef>tvmlue iftyou'vo justerun ousn Ass tly fil ss dlessaneautomaticfC<defined> nsegen ratedew en > ouglobs ociurshlne e tessepmrt ofiafC<terlo> oriC<tly> -sbecauwe{logal globerrturnss (e. rea fil scalledeF<0>) would frditwiwe{t rminatet> ouloopr. Again,fC<undef>tlssrrturnCd onlyeonce. So iftyou're{exprcta tafsirgl vmlue s trdmuafglob,tithlssmun fbettsee o sayct. ($fil ) = <blurn *>;. . >ounct. $fil s= <blurn *>;. . becauwe{toouluseom wnl faleomnatetbetween rrturna taIfil namoemrd. rrturna tFALSE.ct. Ittyou're{trya t>o{do{vlriablo ateomTolatnds,tit'stdefinitelyebettse. >o uwe{toouglob()efunctnds,sbecauwe{> oudlder{nfratndstcanecauwe{peoplo. >o{beidso idsfusedcwacte> ouindirrct fil ss dle nfratnds.ct. @fil s =uglob("$dir/*.[ch]");. @fil s =uglob($fil s[$i]);. . =hrad2 ConetmCt Fdlda . . Lake{C,tPse {doeseafcrctain amouCt ofiexprsssndstsvmluatndst-s. idmpil stime,ew ensvrrtithdoc rminese>ouseall{-rgumiCtss>o{anctdp ratoriae {staticfand{ssv tno sadeeeffrctsrpiIndpmrticular,uetci . idscatenatndstsspp nseat{cdmpil stimetbetween literalse>ousedon'sedo. vlriablo substntutnds.piBaikslssh ateomThWsatndst-lsotsspp nseat. idmpil stime.piYou canesayct. 'Nowhlss e timettly all' .p"\n" .. 'good menh>o{idso >o.'ct. and{ nseall{rrducesh>o{one{etci ei eomnallyrpiLakewiwe,tifo you sayct. tlrean f$fil s(@fil namos) {. ift(-ss$fil s> 5 + 100 * 2**16) { }. }. . e idmpil m wnl fThWidmputet> ounumbsre>ous. exprsssndstrsprssiCtsssoe>ouse> ouineomThWsers won'sessv t>o.. . =hrad2 Bitwiwe{Stci eOp rators. . Bltstci stoftany saz dmayeb dmanipulatedebyt> oubitwiwe{dp ratorss (C<~ |h& ^>)r. . Ift> oudp raCdse>o{a bi aryubitwiwe{dpiae {stci stoftdiffwrsnt saz s,. B<|>fand{B<^>{dps wnl fact -seife> oushoyterudp raCdessdc-dditndsalo z roubitseos > ouright, terlop> ouB<&>{dp wnl fact -seife> oulo ers dp raCdewere{truscatedh>o{> oul ngcteofe> oushoyterrpiNotee>ouse> os graCularityttly sun fexs nsndstor{truscatndstlssone{or{mlre I<bytes>.ct. # ASCII-basedce>amploss. pci t("j p \n" ^("safs"; # pci tss"JAPH\n". pci t("JA"s|("s ph\n"; # pci tss"japh\n". pci t("japh\nJusk"s& '_____'; # pci tss"JAPH\n";. pci t('p N$' ^("sE<H\n"; # pci tss"Pse \n";. . Iftyou arouineondn t>o{manipulateubitstci s,tyou should b dcrctain >ous. you're{supplya tbitstci s: Iftanedp raCdenseafnumbsr,e>ousewnl flmplyctafB<numsric>ubitwiwe{dp ratnds.pYou mayee>Tlicitlytshowrw in ftyp eofctdp ratids youuineondebytusa tC<""> oriC<0+>,rashlne e e>amplossbslow.ct. $foo =u 150u |u 105 ; # yasldse255 (0x96 |u0x69ense0xFF). $foo =u'150' |u 105 ; # yasldse255. $foo =u 150u |u'105'; # yasldse255. $foo =u'150' |u'105'; # yasldseetci e'155'p(under{ASCII)ct. $baz =u0+$foo &u0+$bar; # bocteops e>Tlicitlytnumsric. $biz =u"$foo" ^("$bar"; # bocteops e>Tlicitlytetci yct. See L<p rlfunc/vec>utly i tlymatndston howt>o{manipulateuindividual bits. ln{a bisuvrctly.. . =hrad2 Ineoger{Arithmstic. . BytdefaulttPse {assumese>ouseisumustedo{most ofiitsearithmsticuins tloata tpoine.piButebytsaya . . uwe{ineoger;. . you mayetell e idmpil m >ouseis'stokaye>o{uwe{ineoger{dp ratndsss trdmuhere{to{> ouondeofe> ouonclosa tBLOCKn iAstlnn rtBLOCK may. iduneommand{ nsebytsaya . . no ineoger;. . w in flsstseuneil{> ouondeofe> useBLOCKn. . T oubitwiwe{dp rators ("&", "|", "^", "~", "<<", and{">>")c-lwayss prdduce ineograltrssultsrpi(Buteweet-lsotL<Bitwiwe{Stci eOp rators>.)ctHowsvrr,tC<uwe{ineoger>tetnl fhashmeana . tly em.piBytdefault,t> oirtrssults arouineomThWsedrashunsngnCd. lneogersrpiHowsvrr,tifeC<uwe{ineoger>tishlneeffrct,t> oirtrssults aro. lneomThWsedrashsngnCd{ineogersrpiFly e>amplo,tC<~0>tuwuallyesvmluates. >o{aIl-rge ineograltvmluerpiHowsvrr,tC<uwe{ineoger; ~0>tish-1eos >wos-idmplomiCt man ines.. . =hrad2 Floata -poine{Arithmstic. . WerlopC<uwe{ineoger>tprdvides{ineoger-onlyearithmstic,t> orouis{no. snmilareways{to{prdvide rdundn tor{truscatndstuseadcrctain numbsreofctdecnmaltplacesrpiFly rdundn t>o{aIcrctain numbsreoftdigits,uepci tf()ctly pci tf()uis{uwuallye> ouoasnesserdueo.. . Floata -poine{numbsrs arouonlyeapprdximatndss{to{wousea ma ematicianctwould call{rraltnumbsrsrpiT orouarouinfinitelyemlre rralse>oun tloats,. sotsdso idrnCrsumusteb dcutrpiFly e>amplo:. . pci tf "%.20g\n", 123456789123456789;. # prdduces 123456789123456784. . Tessn tfly e>act equalitytofttloata -poine{equalitytoy i equalitytis. nfrea good idearpiHoro'seaf(rolatnvelyee>T nsnve) woyk-ardundh>o{idsparo. w e> or >wottloata -poine{numbsrs arouequalt>o{aIpmrticular numbsreofctdecnmaltplacesrpiSee Knu> , volume II,ttly aemlre robustetrratmiCt ofct nse>opic.ct. subttp_equalt{. mye($X,t$Y,t$POINTS) =u@_;. mye($tX,t$tY);. $tX =uepci tf("%.${POINTS}g", $X);. $tY =uepci tf("%.${POINTS}g", $Y);. hWsurnt$tX eqt$tY;. }. . T ouPOSIX mddul s(pmrteofe> oustmCdmrd pse {dietcibutnds)flmplomiCts. ceil(),ttloor(),tand{afnumbsreofeo> or ma ematicaltand{ rigdsdsotric. functndssrpiT o Ma ::Cdmplox mddul s(pmrteofe> oustmCdmrd pse ctdietcibutnds)fdefines{afnumbsreofema ematicaltfunctndsse> usecane-lsoctwork dstrsaltnumbsrsrpiMa ::Cdmplox nfreaseefficiiCt asePOSIX,tbutctPOSIX can'sework with cdmplox numbsrsr. . Rdundn tin financialeapplicatndss{canessv tssridusflmplicatndss,tand. e rdundn tsothod usedcshould b dspecnfiedcThWiiwelyrpiIne ewe. cases,tisuprdbablyepays{nfreto{>rustew in svrrdsystem rdundn tis. b n tusedcbytPse ,tbuteto{n stesdclmplomiCt e rdundn tfunctnds you. needcyourwelf.. . =hrad2 Bigger{Numbsrs. . T oustmCdmrd Ma ::BigICt and Ma ::BigFloat mddul s{prdvide. variablecThWiiwndsturithmsticuand dvse oaded{dp rators.. At e idst ofisdso spaceuand idnsnderablecspeed,t> oyctavoid e nlymaltpitfalls{associasedrwith lnmised-ThWiiwndscthWThWsiCtatndss.ct. uwe{Ma ::BigICt;. $x =uMa ::BigICt->new('123456789123456789');. pci t($x *($x;ct. # pci tss+15241578780673678515622620750190521.