1N/A=head1 NAME
1N/A
1N/Aperlop - Perl operators and precedence
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/A=head2 Operator Precedence and Associativity
1N/A
1N/AOperator precedence and associativity work in Perl more or less like
1N/Athey do in mathematics.
1N/A
1N/AI<Operator precedence> means some operators are evaluated before
1N/Aothers. For example, in C<2 + 4 * 5>, the multiplication has higher
1N/Aprecedence so C<4 * 5> is evaluated first yielding C<2 + 20 ==
1N/A22> and not C<6 * 5 == 30>.
1N/A
1N/AI<Operator associativity> defines what happens if a sequence of the
1N/Asame operators is used one after another: whether the evaluator will
1N/Aevaluate the left operations first or the right. For example, in C<8
1N/A- 4 - 2>, subtraction is left associative so Perl evaluates the
1N/Aexpression left to right. C<8 - 4> is evaluated first making the
1N/Aexpression C<4 - 2 == 2> and not C<8 - 2 == 6>.
1N/A
1N/APerl operators have the following associativity and precedence,
1N/Alisted from highest precedence to lowest. Operators borrowed from
1N/AC keep the same precedence relationship with each other, even where
1N/AC's precedence is slightly screwy. (This makes learning Perl easier
1N/Afor C folks.) With very few exceptions, these all operate on scalar
1N/Avalues only, not array values.
1N/A
1N/A left terms and list operators (leftward)
1N/A left ->
1N/A nonassoc ++ --
1N/A right **
1N/A right ! ~ \ and unary + and -
1N/A left =~ !~
1N/A left * / % x
1N/A left + - .
1N/A left << >>
1N/A nonassoc named unary operators
1N/A nonassoc < > <= >= lt gt le ge
1N/A nonassoc == != <=> eq ne cmp
1N/A left &
1N/A left | ^
1N/A left &&
1N/A left ||
1N/A nonassoc .. ...
1N/A right ?:
1N/A right = += -= *= etc.
1N/A left , =>
1N/A nonassoc list operators (rightward)
1N/A right not
1N/A left and
1N/A left or xor
1N/A
1N/AIn the following sections, these operators are covered in precedence order.
1N/A
1N/AMany operators can be overloaded for objects. See L<overload>.
1N/A
1N/A=head2 Terms and List Operators (Leftward)
1N/A
1N/AA TERM has the highest precedence in Perl. They include variables,
1N/Aquote and quote-like operators, any expression in parentheses,
1N/Aand any function whose arguments are parenthesized. Actually, there
1N/Aaren't really functions in this sense, just list operators and unary
1N/Aoperators behaving as functions because you put parentheses around
1N/Athe arguments. These are all documented in L<perlfunc>.
1N/A
1N/AIf any list operator (print(), etc.) or any unary operator (chdir(), etc.)
1N/Ais followed by a left parenthesis as the next token, the operator and
1N/Aarguments within parentheses are taken to be of highest precedence,
1N/Ajust like a normal function call.
1N/A
1N/AIn the absence of parentheses, the precedence of list operators such as
1N/AC<print>, C<sort>, or C<chmod> is either very high or very low depending on
1N/Awhether you are looking at the left side or the right side of the operator.
1N/AFor example, in
1N/A
1N/A @ary = (1, 3, sort 4, 2);
1N/A print @ary; # prints 1324
1N/A
1N/Athe commas on the right of the sort are evaluated before the sort,
1N/Abut the commas on the left are evaluated after. In other words,
1N/Alist operators tend to gobble up all arguments that follow, and
1N/Athen act like a simple TERM with regard to the preceding expression.
1N/ABe careful with parentheses:
1N/A
1N/A # These evaluate exit before doing the print:
1N/A print($foo, exit); # Obviously not what you want.
1N/A print $foo, exit; # Nor is this.
1N/A
1N/A # These do the print before evaluating exit:
1N/A (print $foo), exit; # This is what you want.
1N/A print($foo), exit; # Or this.
1N/A print ($foo), exit; # Or even this.
1N/A
1N/AAlso note that
1N/A
1N/A print ($foo & 255) + 1, "\n";
1N/A
1N/Aprobably doesn't do what you expect at first glance. The parentheses
1N/Aenclose the argument list for C<print> which is evaluated (printing
1N/Athe result of C<$foo & 255>). Then one is added to the return value
1N/Aof C<print> (usually 1). The result is something like this:
1N/A
1N/A 1 + 1, "\n"; # Obviously not what you meant.
1N/A
1N/ATo do what you meant properly, you must write:
1N/A
1N/A print(($foo & 255) + 1, "\n");
1N/A
1N/ASee L<Named Unary Operators> for more discussion of this.
1N/A
1N/AAlso parsed as terms are the C<do {}> and C<eval {}> constructs, as
1N/Awell as subroutine and method calls, and the anonymous
1N/Aconstructors C<[]> and C<{}>.
1N/A
1N/ASee also L<Quote and Quote-like Operators> toward the end of this section,
1N/Aas well as L<"I/O Operators">.
1N/A
1N/A=head2 The Arrow Operator
1N/A
1N/A"C<< -> >>" is an infix dereference operator, just as it is in C
1N/Aand C++. If the right side is either a C<[...]>, C<{...}>, or a
1N/AC<(...)> subscript, then the left side must be either a hard or
1N/Asymbolic reference to an array, a hash, or a subroutine respectively.
1N/A(Or technically speaking, a location capable of holding a hard
1N/Areference, if it's an array or hash reference being used for
1N/Aassignment.) See L<perlreftut> and L<perlref>.
1N/A
1N/AOtherwise, the right side is a method name or a simple scalar
1N/Avariable containing either the method name or a subroutine reference,
1N/Aand the left side must be either an object (a blessed reference)
1N/Aor a class name (that is, a package name). See L<perlobj>.
1N/A
1N/A=head2 Auto-increment and Auto-decrement
1N/A
1N/A"++" and "--" work as in C. That is, if placed before a variable,
1N/Athey increment or decrement the variable by one before returning the
1N/Avalue, and if placed after, increment or decrement after returning the
1N/Avalue.
1N/A
1N/A $i = 0; $j = 0;
1N/A print $i++; # prints 0
1N/A print ++$j; # prints 1
1N/A
1N/AThe auto-increment operator has a little extra builtin magic to it. If
1N/Ayou increment a variable that is numeric, or that has ever been used in
1N/Aa numeric context, you get a normal increment. If, however, the
1N/Avariable has been used in only string contexts since it was set, and
1N/Ahas a value that is not the empty string and matches the pattern
1N/AC</^[a-zA-Z]*[0-9]*\z/>, the increment is done as a string, preserving each
1N/Acharacter within its range, with carry:
1N/A
1N/A print ++($foo = '99'); # prints '100'
1N/A print ++($foo = 'a0'); # prints 'a1'
1N/A print ++($foo = 'Az'); # prints 'Ba'
1N/A print ++($foo = 'zz'); # prints 'aaa'
1N/A
1N/AC<undef> is always treated as numeric, and in particular is changed
1N/Ato C<0> before incrementing (so that a post-increment of an undef value
1N/Awill return C<0> rather than C<undef>).
1N/A
1N/AThe auto-decrement operator is not magical.
1N/A
1N/A=head2 Exponentiation
1N/A
1N/ABinary "**" is the exponentiation operator. It binds even more
1N/Atightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is
1N/Aimplemented using C's pow(3) function, which actually works on doubles
1N/Ainternally.)
1N/A
1N/A=head2 Symbolic Unary Operators
1N/A
1N/AUnary "!" performs logical negation, i.e., "not". See also C<not> for a lower
1N/Aprecedence version of this.
1N/A
1N/AUnary "-" performs arithmetic negation if the operand is numeric. If
1N/Athe operand is an identifier, a string consisting of a minus sign
1N/Aconcatenated with the identifier is returned. Otherwise, if the string
1N/Astarts with a plus or minus, a string starting with the opposite sign
1N/Ais returned. One effect of these rules is that C<-bareword> is equivalent
1N/Ato C<"-bareword">.
1N/A
1N/AUnary "~" performs bitwise negation, i.e., 1's complement. For
1N/Aexample, C<0666 & ~027> is 0640. (See also L<Integer Arithmetic> and
1N/AL<Bitwise String Operators>.) Note that the width of the result is
1N/Aplatform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64
1N/Abits wide on a 64-bit platform, so if you are expecting a certain bit
1N/Awidth, remember to use the & operator to mask off the excess bits.
1N/A
1N/AUnary "+" has no effect whatsoever, even on strings. It is useful
1N/Asyntactically for separating a function name from a parenthesized expression
1N/Athat would otherwise be interpreted as the complete list of function
1N/Aarguments. (See examples above under L<Terms and List Operators (Leftward)>.)
1N/A
1N/AUnary "\" creates a reference to whatever follows it. See L<perlreftut>
1N/Aand L<perlref>. Do not confuse this behavior with the behavior of
1N/Abackslash within a string, although both forms do convey the notion
1N/Aof protecting the next thing from interpolation.
1N/A
1N/A=head2 Binding Operators
1N/A
1N/ABinary "=~" binds a scalar expression to a pattern match. Certain operations
1N/Asearch or modify the string $_ by default. This operator makes that kind
1N/Aof operation work on some other string. The right argument is a search
1N/Apattern, substitution, or transliteration. The left argument is what is
1N/Asupposed to be searched, substituted, or transliterated instead of the default
1N/A$_. When used in scalar context, the return value generally indicates the
1N/Asuccess of the operation. Behavior in list context depends on the particular
1N/Aoperator. See L</"Regexp Quote-Like Operators"> for details.
1N/A
1N/AIf the right argument is an expression rather than a search pattern,
1N/Asubstitution, or transliteration, it is interpreted as a search pattern at run
1N/Atime.
1N/A
1N/ABinary "!~" is just like "=~" except the return value is negated in
1N/Athe logical sense.
1N/A
1N/A=head2 Multiplicative Operators
1N/A
1N/ABinary "*" multiplies two numbers.
1N/A
1N/ABinary "/" divides two numbers.
1N/A
1N/ABinary "%" computes the modulus of two numbers. Given integer
1N/Aoperands C<$a> and C<$b>: If C<$b> is positive, then C<$a % $b> is
1N/AC<$a> minus the largest multiple of C<$b> that is not greater than
1N/AC<$a>. If C<$b> is negative, then C<$a % $b> is C<$a> minus the
1N/Asmallest multiple of C<$b> that is not less than C<$a> (i.e. the
1N/Aresult will be less than or equal to zero).
1N/ANote that when C<use integer> is in scope, "%" gives you direct access
1N/Ato the modulus operator as implemented by your C compiler. This
1N/Aoperator is not as well defined for negative operands, but it will
1N/Aexecute faster.
1N/A
1N/ABinary "x" is the repetition operator. In scalar context or if the left
1N/Aoperand is not enclosed in parentheses, it returns a string consisting
1N/Aof the left operand repeated the number of times specified by the right
1N/Aoperand. In list context, if the left operand is enclosed in
1N/Aparentheses, it repeats the list. If the right operand is zero or
1N/Anegative, it returns an empty string or an empty list, depending on the
1N/Acontext.
1N/A
1N/A print '-' x 80; # print row of dashes
1N/A
1N/A print "\t" x ($tab/8), ' ' x ($tab%8); # tab over
1N/A
1N/A @ones = (1) x 80; # a list of 80 1's
1N/A @ones = (5) x @ones; # set all elements to 5
1N/A
1N/A
1N/A=head2 Additive Operators
1N/A
1N/ABinary "+" returns the sum of two numbers.
1N/A
1N/ABinary "-" returns the difference of two numbers.
1N/A
1N/ABinary "." concatenates two strings.
1N/A
1N/A=head2 Shift Operators
1N/A
1N/ABinary "<<" returns the value of its left argument shifted left by the
1N/Anumber of bits specified by the right argument. Arguments should be
1N/Aintegers. (See also L<Integer Arithmetic>.)
1N/A
1N/ABinary ">>" returns the value of its left argument shifted right by
1N/Athe number of bits specified by the right argument. Arguments should
1N/Abe integers. (See also L<Integer Arithmetic>.)
1N/A
1N/ANote that both "<<" and ">>" in Perl are implemented directly using
1N/A"<<" and ">>" in C. If C<use integer> (see L<Integer Arithmetic>) is
1N/Ain force then signed C integers are used, else unsigned C integers are
1N/Aused. Either way, the implementation isn't going to generate results
1N/Alarger than the size of the integer type Perl was built with (32 bits
1N/Aor 64 bits).
1N/A
1N/AThe result of overflowing the range of the integers is undefined
1N/Abecause it is undefined also in C. In other words, using 32-bit
1N/Aintegers, C<< 1 << 32 >> is undefined. Shifting by a negative number
1N/Aof bits is also undefined.
1N/A
1N/A=head2 Named Unary Operators
1N/A
1N/AThe various named unary operators are treated as functions with one
1N/Aargument, with optional parentheses.
1N/A
1N/AIf any list operator (print(), etc.) or any unary operator (chdir(), etc.)
1N/Ais followed by a left parenthesis as the next token, the operator and
1N/Aarguments within parentheses are taken to be of highest precedence,
1N/Ajust like a normal function call. For example,
1N/Abecause named unary operators are higher precedence than ||:
1N/A
1N/A chdir $foo || die; # (chdir $foo) || die
1N/A chdir($foo) || die; # (chdir $foo) || die
1N/A chdir ($foo) || die; # (chdir $foo) || die
1N/A chdir +($foo) || die; # (chdir $foo) || die
1N/A
1N/Abut, because * is higher precedence than named operators:
1N/A
1N/A chdir $foo * 20; # chdir ($foo * 20)
1N/A chdir($foo) * 20; # (chdir $foo) * 20
1N/A chdir ($foo) * 20; # (chdir $foo) * 20
1N/A chdir +($foo) * 20; # chdir ($foo * 20)
1N/A
1N/A rand 10 * 20; # rand (10 * 20)
1N/A rand(10) * 20; # (rand 10) * 20
1N/A rand (10) * 20; # (rand 10) * 20
1N/A rand +(10) * 20; # rand (10 * 20)
1N/A
1N/ARegarding precedence, the filetest operators, like C<-f>, C<-M>, etc. are
1N/Atreated like named unary operators, but they don't follow this functional
1N/Aparenthesis rule. That means, for example, that C<-f($file).".bak"> is
1N/Aequivalent to C<-f "$file.bak">.
1N/A
1N/ASee also L<"Terms and List Operators (Leftward)">.
1N/A
1N/A=head2 Relational Operators
1N/A
1N/ABinary "<" returns true if the left argument is numerically less than
1N/Athe right argument.
1N/A
1N/ABinary ">" returns true if the left argument is numerically greater
1N/Athan the right argument.
1N/A
1N/ABinary "<=" returns true if the left argument is numerically less than
1N/Aor equal to the right argument.
1N/A
1N/ABinary ">=" returns true if the left argument is numerically greater
1N/Athan or equal to the right argument.
1N/A
1N/ABinary "lt" returns true if the left argument is stringwise less than
1N/Athe right argument.
1N/A
1N/ABinary "gt" returns true if the left argument is stringwise greater
1N/Athan the right argument.
1N/A
1N/ABinary "le" returns true if the left argument is stringwise less than
1N/Aor equal to the right argument.
1N/A
1N/ABinary "ge" returns true if the left argument is stringwise greater
1N/Athan or equal to the right argument.
1N/A
1N/A=head2 Equality Operators
1N/A
1N/ABinary "==" returns true if the left argument is numerically equal to
1N/Athe right argument.
1N/A
1N/ABinary "!=" returns true if the left argument is numerically not equal
1N/Ato the right argument.
1N/A
1N/ABinary "<=>" returns -1, 0, or 1 depending on whether the left
1N/Aargument is numerically less than, equal to, or greater than the right
1N/Aargument. If your platform supports NaNs (not-a-numbers) as numeric
1N/Avalues, using them with "<=>" returns undef. NaN is not "<", "==", ">",
1N/A"<=" or ">=" anything (even NaN), so those 5 return false. NaN != NaN
1N/Areturns true, as does NaN != anything else. If your platform doesn't
1N/Asupport NaNs then NaN is just a string with numeric value 0.
1N/A
1N/A perl -le '$a = NaN; print "No NaN support here" if $a == $a'
1N/A perl -le '$a = NaN; print "NaN support here" if $a != $a'
1N/A
1N/ABinary "eq" returns true if the left argument is stringwise equal to
1N/Athe right argument.
1N/A
1N/ABinary "ne" returns true if the left argument is stringwise not equal
1N/Ato the right argument.
1N/A
1N/ABinary "cmp" returns -1, 0, or 1 depending on whether the left
1N/Aargument is stringwise less than, equal to, or greater than the right
1N/Aargument.
1N/A
1N/A"lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specified
1N/Aby the current locale if C<use locale> is in effect. See L<perllocale>.
1N/A
1N/A=head2 Bitwise And
1N/A
1N/ABinary "&" returns its operands ANDed together bit by bit.
1N/A(See also L<Integer Arithmetic> and L<Bitwise String Operators>.)
1N/A
1N/ANote that "&" has lower priority than relational operators, so for example
1N/Athe brackets are essential in a test like
1N/A
1N/A print "Even\n" if ($x & 1) == 0;
1N/A
1N/A=head2 Bitwise Or and Exclusive Or
1N/A
1N/ABinary "|" returns its operands ORed together bit by bit.
1N/A(See also L<Integer Arithmetic> and L<Bitwise String Operators>.)
1N/A
1N/ABinary "^" returns its operands XORed together bit by bit.
1N/A(See also L<Integer Arithmetic> and L<Bitwise String Operators>.)
1N/A
1N/ANote that "|" and "^" have lower priority than relational operators, so
1N/Afor example the brackets are essential in a test like
1N/A
1N/A print "false\n" if (8 | 2) != 10;
1N/A
1N/A=head2 C-style Logical And
1N/A
1N/ABinary "&&" performs a short-circuit logical AND operation. That is,
1N/Aif the left operand is false, the right operand is not even evaluated.
1N/AScalar or list context propagates down to the right operand if it
1N/Ais evaluated.
1N/A
1N/A=head2 C-style Logical Or
1N/A
1N/ABinary "||" performs a short-circuit logical OR operation. That is,
1N/Aif the left operand is true, the right operand is not even evaluated.
1N/AScalar or list context propagates down to the right operand if it
1N/Ais evaluated.
1N/A
1N/AThe C<||> and C<&&> operators return the last value evaluated
1N/A(unlike C's C<||> and C<&&>, which return 0 or 1). Thus, a reasonably
1N/Aportable way to find out the home directory might be:
1N/A
1N/A $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
1N/A (getpwuid($<))[7] || die "You're homeless!\n";
1N/A
1N/AIn particular, this means that you shouldn't use this
1N/Afor selecting between two aggregates for assignment:
1N/A
1N/A @a = @b || @c; # this is wrong
1N/A @a = scalar(@b) || @c; # really meant this
1N/A @a = @b ? @b : @c; # this works fine, though
1N/A
1N/AAs more readable alternatives to C<&&> and C<||> when used for
1N/Acontrol flow, Perl provides C<and> and C<or> operators (see below).
1N/AThe short-circuit behavior is identical. The precedence of "and" and
1N/A"or" is much lower, however, so that you can safely use them after a
1N/Alist operator without the need for parentheses:
1N/A
1N/A unlink "alpha", "beta", "gamma"
1N/A or gripe(), next LINE;
1N/A
1N/AWith the C-style operators that would have been written like this:
1N/A
1N/A unlink("alpha", "beta", "gamma")
1N/A || (gripe(), next LINE);
1N/A
1N/AUsing "or" for assignment is unlikely to do what you want; see below.
1N/A
1N/A=head2 Range Operators
1N/A
1N/ABinary ".." is the range operator, which is really two different
1N/Aoperators depending on the context. In list context, it returns a
1N/Alist of values counting (up by ones) from the left value to the right
1N/Avalue. If the left value is greater than the right value then it
1N/Areturns the empty list. The range operator is useful for writing
1N/AC<foreach (1..10)> loops and for doing slice operations on arrays. In
1N/Athe current implementation, no temporary array is created when the
1N/Arange operator is used as the expression in C<foreach> loops, but older
1N/Aversions of Perl might burn a lot of memory when you write something
1N/Alike this:
1N/A
1N/A for (1 .. 1_000_000) {
1N/A # code
1N/A }
1N/A
1N/AThe range operator also works on strings, using the magical auto-increment,
1N/Asee below.
1N/A
1N/AIn scalar context, ".." returns a boolean value. The operator is
1N/Abistable, like a flip-flop, and emulates the line-range (comma) operator
1N/Aof B<sed>, B<awk>, and various editors. Each ".." operator maintains its
1N/Aown boolean state. It is false as long as its left operand is false.
1N/AOnce the left operand is true, the range operator stays true until the
1N/Aright operand is true, I<AFTER> which the range operator becomes false
1N/Aagain. It doesn't become false till the next time the range operator is
1N/Aevaluated. It can test the right operand and become false on the same
1N/Aevaluation it became true (as in B<awk>), but it still returns true once.
1N/AIf you don't want it to test the right operand till the next
1N/Aevaluation, as in B<sed>, just use three dots ("...") instead of
1N/Atwo. In all other regards, "..." behaves just like ".." does.
1N/A
1N/AThe right operand is not evaluated while the operator is in the
1N/A"false" state, and the left operand is not evaluated while the
1N/Aoperator is in the "true" state. The precedence is a little lower
1N/Athan || and &&. The value returned is either the empty string for
1N/Afalse, or a sequence number (beginning with 1) for true. The
1N/Asequence number is reset for each range encountered. The final
1N/Asequence number in a range has the string "E0" appended to it, which
1N/Adoesn't affect its numeric value, but gives you something to search
1N/Afor if you want to exclude the endpoint. You can exclude the
1N/Abeginning point by waiting for the sequence number to be greater
1N/Athan 1.
1N/A
1N/AIf either operand of scalar ".." is a constant expression,
1N/Athat operand is considered true if it is equal (C<==>) to the current
1N/Ainput line number (the C<$.> variable).
1N/A
1N/ATo be pedantic, the comparison is actually C<int(EXPR) == int(EXPR)>,
1N/Abut that is only an issue if you use a floating point expression; when
1N/Aimplicitly using C<$.> as described in the previous paragraph, the
1N/Acomparison is C<int(EXPR) == int($.)> which is only an issue when C<$.>
1N/Ais set to a floating point value and you are not reading from a file.
1N/AFurthermore, C<"span" .. "spat"> or C<2.18 .. 3.14> will not do what
1N/Ayou want in scalar context because each of the operands are evaluated
1N/Ausing their integer representation.
1N/A
1N/AExamples:
1N/A
1N/AAs a scalar operator:
1N/A
1N/A if (101 .. 200) { print; } # print 2nd hundred lines, short for
1N/A # if ($. == 101 .. $. == 200) ...
1N/A next line if (1 .. /^$/); # skip header lines, short for
1N/A # ... if ($. == 1 .. /^$/);
1N/A s/^/> / if (/^$/ .. eof()); # quote body
1N/A
1N/A # parse mail messages
1N/A while (<>) {
1N/A $in_header = 1 .. /^$/;
1N/A $in_body = /^$/ .. eof;
1N/A if ($in_header) {
1N/A # ...
1N/A } else { # in body
1N/A # ...
1N/A }
1N/A } continue {
1N/A close ARGV if eof; # reset $. each file
1N/A }
1N/A
1N/AAs a list operator:
1N/A
1N/A for (101 .. 200) { print; } # print $_ 100 times
1N/A @foo = @foo[0 .. $#foo]; # an expensive no-op
1N/A @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
1N/A
1N/AThe range operator (in list context) makes use of the magical
1N/Aauto-increment algorithm if the operands are strings. You
1N/Acan say
1N/A
1N/A @alphabet = ('A' .. 'Z');
1N/A
1N/Ato get all normal letters of the English alphabet, or
1N/A
1N/A $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
1N/A
1N/Ato get a hexadecimal digit, or
1N/A
1N/A @z2 = ('01' .. '31'); print $z2[$mday];
1N/A
1N/Ato get dates with leading zeros. If the final value specified is not
1N/Ain the sequence that the magical increment would produce, the sequence
1N/Agoes until the next value would be longer than the final value
1N/Aspecified.
1N/A
1N/ABecause each operand is evaluated in integer form, C<2.18 .. 3.14> will
1N/Areturn two elements in list context.
1N/A
1N/A @list = (2.18 .. 3.14); # same as @list = (2 .. 3);
1N/A
1N/A=head2 Conditional Operator
1N/A
1N/ATernary "?:" is the conditional operator, just as in C. It works much
1N/Alike an if-then-else. If the argument before the ? is true, the
1N/Aargument before the : is returned, otherwise the argument after the :
1N/Ais returned. For example:
1N/A
1N/A printf "I have %d dog%s.\n", $n,
1N/A ($n == 1) ? '' : "s";
1N/A
1N/AScalar or list context propagates downward into the 2nd
1N/Aor 3rd argument, whichever is selected.
1N/A
1N/A $a = $ok ? $b : $c; # get a scalar
1N/A @a = $ok ? @b : @c; # get an array
1N/A $a = $ok ? @b : @c; # oops, that's just a count!
1N/A
1N/AThe operator may be assigned to if both the 2nd and 3rd arguments are
1N/Alegal lvalues (meaning that you can assign to them):
1N/A
1N/A ($a_or_b ? $a : $b) = $c;
1N/A
1N/ABecause this operator produces an assignable result, using assignments
1N/Awithout parentheses will get you in trouble. For example, this:
1N/A
1N/A $a % 2 ? $a += 10 : $a += 2
1N/A
1N/AReally means this:
1N/A
1N/A (($a % 2) ? ($a += 10) : $a) += 2
1N/A
1N/ARather than this:
1N/A
1N/A ($a % 2) ? ($a += 10) : ($a += 2)
1N/A
1N/AThat should probably be written more simply as:
1N/A
1N/A $a += ($a % 2) ? 10 : 2;
1N/A
1N/A=head2 Assignment Operators
1N/A
1N/A"=" is the ordinary assignment operator.
1N/A
1N/AAssignment operators work as in C. That is,
1N/A
1N/A $a += 2;
1N/A
1N/Ais equivalent to
1N/A
1N/A $a = $a + 2;
1N/A
1N/Aalthough without duplicating any side effects that dereferencing the lvalue
1N/Amight trigger, such as from tie(). Other assignment operators work similarly.
1N/AThe following are recognized:
1N/A
1N/A **= += *= &= <<= &&=
1N/A -= /= |= >>= ||=
1N/A .= %= ^=
1N/A x=
1N/A
1N/AAlthough these are grouped by family, they all have the precedence
1N/Aof assignment.
1N/A
1N/AUnlike in C, the scalar assignment operator produces a valid lvalue.
1N/AModifying an assignment is equivalent to doing the assignment and
1N/Athen modifying the variable that was assigned to. This is useful
1N/Afor modifying a copy of something, like this:
1N/A
1N/A ($tmp = $global) =~ tr [A-Z] [a-z];
1N/A
1N/ALikewise,
1N/A
1N/A ($a += 2) *= 3;
1N/A
1N/Ais equivalent to
1N/A
1N/A $a += 2;
1N/A $a *= 3;
1N/A
1N/ASimilarly, a list assignment in list context produces the list of
1N/Alvalues assigned to, and a list assignment in scalar context returns
1N/Athe number of elements produced by the expression on the right hand
1N/Aside of the assignment.
1N/A
1N/A=head2 Comma Operator
1N/A
1N/ABinary "," is the comma operator. In scalar context it evaluates
1N/Aits left argument, throws that value away, then evaluates its right
1N/Aargument and returns that value. This is just like C's comma operator.
1N/A
1N/AIn list context, it's just the list argument separator, and inserts
1N/Aboth its arguments into the list.
1N/A
1N/AThe C<< => >> operator is a synonym for the comma, but forces any word
1N/Ato its left to be interpreted as a string (as of 5.001). It is helpful
1N/Ain documenting the correspondence between keys and values in hashes,
1N/Aand other paired elements in lists.
1N/A
1N/A=head2 List Operators (Rightward)
1N/A
1N/AOn the right side of a list operator, it has very low precedence,
1N/Asuch that it controls all comma-separated expressions found there.
1N/AThe only operators with lower precedence are the logical operators
1N/A"and", "or", and "not", which may be used to evaluate calls to list
1N/Aoperators without the need for extra parentheses:
1N/A
1N/A open HANDLE, "filename"
1N/A or die "Can't open: $!\n";
1N/A
1N/ASee also discussion of list operators in L<Terms and List Operators (Leftward)>.
1N/A
1N/A=head2 Logical Not
1N/A
1N/AUnary "not" returns the logical negation of the expression to its right.
1N/AIt's the equivalent of "!" except for the very low precedence.
1N/A
1N/A=head2 Logical And
1N/A
1N/ABinary "and" returns the logical conjunction of the two surrounding
1N/Aexpressions. It's equivalent to && except for the very low
1N/Aprecedence. This means that it short-circuits: i.e., the right
1N/Aexpression is evaluated only if the left expression is true.
1N/A
1N/A=head2 Logical or and Exclusive Or
1N/A
1N/ABinary "or" returns the logical disjunction of the two surrounding
1N/Aexpressions. It's equivalent to || except for the very low precedence.
1N/AThis makes it useful for control flow
1N/A
1N/A print FH $data or die "Can't write to FH: $!";
1N/A
1N/AThis means that it short-circuits: i.e., the right expression is evaluated
1N/Aonly if the left expression is false. Due to its precedence, you should
1N/Aprobably avoid using this for assignment, only for control flow.
1N/A
1N/A $a = $b or $c; # bug: this is wrong
1N/A ($a = $b) or $c; # really means this
1N/A $a = $b || $c; # better written this way
1N/A
1N/AHowever, when it's a list-context assignment and you're trying to use
1N/A"||" for control flow, you probably need "or" so that the assignment
1N/Atakes higher precedence.
1N/A
1N/A @info = stat($file) || die; # oops, scalar sense of stat!
1N/A @info = stat($file) or die; # better, now @info gets its due
1N/A
1N/AThen again, you could always use parentheses.
1N/A
1N/ABinary "xor" returns the exclusive-OR of the two surrounding expressions.
1N/AIt cannot short circuit, of course.
1N/A
1N/A=head2 C Operators Missing From Perl
1N/A
1N/AHere is what C has that Perl doesn't:
1N/A
1N/A=over 8
1N/A
1N/A=item unary &
1N/A
1N/AAddress-of operator. (But see the "\" operator for taking a reference.)
1N/A
1N/A=item unary *
1N/A
1N/ADereference-address operator. (Perl's prefix dereferencing
1N/Aoperators are typed: $, @, %, and &.)
1N/A
1N/A=item (TYPE)
1N/A
1N/AType-casting operator.
1N/A
1N/A=back
1N/A
1N/A=head2 Quote and Quote-like Operators
1N/A
1N/AWhile we usually think of quotes as literal values, in Perl they
1N/Afunction as operators, providing various kinds of interpolating and
1N/Apattern matching capabilities. Perl provides customary quote characters
1N/Afor these behaviors, but also provides a way for you to choose your
1N/Aquote character for any of them. In the following table, a C<{}> represents
1N/Aany pair of delimiters you choose.
1N/A
1N/A Customary Generic Meaning Interpolates
1N/A '' q{} Literal no
1N/A "" qq{} Literal yes
1N/A `` qx{} Command yes*
1N/A qw{} Word list no
1N/A // m{} Pattern match yes*
1N/A qr{} Pattern yes*
1N/A s{}{} Substitution yes*
1N/A tr{}{} Transliteration no (but see below)
1N/A <<EOF here-doc yes*
1N/A
1N/A * unless the delimiter is ''.
1N/A
1N/ANon-bracketing delimiters use the same character fore and aft, but the four
1N/Asorts of brackets (round, angle, square, curly) will all nest, which means
1N/Athat
1N/A
1N/A q{foo{bar}baz}
1N/A
1N/Ais the same as
1N/A
1N/A 'foo{bar}baz'
1N/A
1N/ANote, however, that this does not always work for quoting Perl code:
1N/A
1N/A $s = q{ if($a eq "}") ... }; # WRONG
1N/A
1N/Ais a syntax error. The C<Text::Balanced> module (from CPAN, and
1N/Astarting from Perl 5.8 part of the standard distribution) is able
1N/Ato do this properly.
1N/A
1N/AThere can be whitespace between the operator and the quoting
1N/Acharacters, except when C<#> is being used as the quoting character.
1N/AC<q#foo#> is parsed as the string C<foo>, while C<q #foo#> is the
1N/Aoperator C<q> followed by a comment. Its argument will be taken
1N/Afrom the next line. This allows you to write:
1N/A
1N/A s {foo} # Replace foo
1N/A {bar} # with bar.
1N/A
1N/AThe following escape sequences are available in constructs that interpolate
1N/Aand in transliterations.
1N/A
1N/A \t tab (HT, TAB)
1N/A \n newline (NL)
1N/A \r return (CR)
1N/A \f form feed (FF)
1N/A \b backspace (BS)
1N/A \a alarm (bell) (BEL)
1N/A \e escape (ESC)
1N/A \033 octal char (ESC)
1N/A \x1b hex char (ESC)
1N/A \x{263a} wide hex char (SMILEY)
1N/A \c[ control char (ESC)
1N/A \N{name} named Unicode character
1N/A
1N/AB<NOTE>: Unlike C and other languages, Perl has no \v escape sequence for
1N/Athe vertical tab (VT - ASCII 11).
1N/A
1N/AThe following escape sequences are available in constructs that interpolate
1N/Abut not in transliterations.
1N/A
1N/A \l lowercase next char
1N/A \u uppercase next char
1N/A \L lowercase till \E
1N/A \U uppercase till \E
1N/A \E end case modification
1N/A \Q quote non-word characters till \E
1N/A
1N/AIf C<use locale> is in effect, the case map used by C<\l>, C<\L>,
1N/AC<\u> and C<\U> is taken from the current locale. See L<perllocale>.
1N/AIf Unicode (for example, C<\N{}> or wide hex characters of 0x100 or
1N/Abeyond) is being used, the case map used by C<\l>, C<\L>, C<\u> and
1N/AC<\U> is as defined by Unicode. For documentation of C<\N{name}>,
1N/Asee L<charnames>.
1N/A
1N/AAll systems use the virtual C<"\n"> to represent a line terminator,
1N/Acalled a "newline". There is no such thing as an unvarying, physical
1N/Anewline character. It is only an illusion that the operating system,
1N/Adevice drivers, C libraries, and Perl all conspire to preserve. Not all
1N/Asystems read C<"\r"> as ASCII CR and C<"\n"> as ASCII LF. For example,
1N/Aon a Mac, these are reversed, and on systems without line terminator,
1N/Aprinting C<"\n"> may emit no actual data. In general, use C<"\n"> when
1N/Ayou mean a "newline" for your system, but use the literal ASCII when you
1N/Aneed an exact character. For example, most networking protocols expect
1N/Aand prefer a CR+LF (C<"\015\012"> or C<"\cM\cJ">) for line terminators,
1N/Aand although they often accept just C<"\012">, they seldom tolerate just
1N/AC<"\015">. If you get in the habit of using C<"\n"> for networking,
1N/Ayou may be burned some day.
1N/A
1N/AFor constructs that do interpolate, variables beginning with "C<$>"
1N/Aor "C<@>" are interpolated. Subscripted variables such as C<$a[3]> or
1N/AC<< $href->{key}[0] >> are also interpolated, as are array and hash slices.
1N/ABut method calls such as C<< $obj->meth >> are not.
1N/A
1N/AInterpolating an array or slice interpolates the elements in order,
1N/Aseparated by the value of C<$">, so is equivalent to interpolating
1N/AC<join $", @array>. "Punctuation" arrays such as C<@+> are only
1N/Ainterpolated if the name is enclosed in braces C<@{+}>.
1N/A
1N/AYou cannot include a literal C<$> or C<@> within a C<\Q> sequence.
1N/AAn unescaped C<$> or C<@> interpolates the corresponding variable,
1N/Awhile escaping will cause the literal string C<\$> to be inserted.
1N/AYou'll need to write something like C<m/\Quser\E\@\Qhost/>.
1N/A
1N/APatterns are subject to an additional level of interpretation as a
1N/Aregular expression. This is done as a second pass, after variables are
1N/Ainterpolated, so that regular expressions may be incorporated into the
1N/Apattern from the variables. If this is not what you want, use C<\Q> to
1N/Ainterpolate a variable literally.
1N/A
1N/AApart from the behavior described above, Perl does not expand
1N/Amultiple levels of interpolation. In particular, contrary to the
1N/Aexpectations of shell programmers, back-quotes do I<NOT> interpolate
1N/Awithin double quotes, nor do single quotes impede evaluation of
1N/Avariables when used within double quotes.
1N/A
1N/A=head2 Regexp Quote-Like Operators
1N/A
1N/AHere are the quote-like operators that apply to pattern
1N/Amatching and related activities.
1N/A
1N/A=over 8
1N/A
1N/A=item ?PATTERN?
1N/A
1N/AThis is just like the C</pattern/> search, except that it matches only
1N/Aonce between calls to the reset() operator. This is a useful
1N/Aoptimization when you want to see only the first occurrence of
1N/Asomething in each file of a set of files, for instance. Only C<??>
1N/Apatterns local to the current package are reset.
1N/A
1N/A while (<>) {
1N/A if (?^$?) {
1N/A # blank line between header and body
1N/A }
1N/A } continue {
1N/A reset if eof; # clear ?? status for next file
1N/A }
1N/A
1N/AThis usage is vaguely deprecated, which means it just might possibly
1N/Abe removed in some distant future version of Perl, perhaps somewhere
1N/Aaround the year 2168.
1N/A
1N/A=item m/PATTERN/cgimosx
1N/A
1N/A=item /PATTERN/cgimosx
1N/A
1N/ASearches a string for a pattern match, and in scalar context returns
1N/Atrue if it succeeds, false if it fails. If no string is specified
1N/Avia the C<=~> or C<!~> operator, the $_ string is searched. (The
1N/Astring specified with C<=~> need not be an lvalue--it may be the
1N/Aresult of an expression evaluation, but remember the C<=~> binds
1N/Arather tightly.) See also L<perlre>. See L<perllocale> for
1N/Adiscussion of additional considerations that apply when C<use locale>
1N/Ais in effect.
1N/A
1N/AOptions are:
1N/A
1N/A c Do not reset search position on a failed match when /g is in effect.
1N/A g Match globally, i.e., find all occurrences.
1N/A i Do case-insensitive pattern matching.
1N/A m Treat string as multiple lines.
1N/A o Compile pattern only once.
1N/A s Treat string as single line.
1N/A x Use extended regular expressions.
1N/A
1N/AIf "/" is the delimiter then the initial C<m> is optional. With the C<m>
1N/Ayou can use any pair of non-alphanumeric, non-whitespace characters
1N/Aas delimiters. This is particularly useful for matching path names
1N/Athat contain "/", to avoid LTS (leaning toothpick syndrome). If "?" is
1N/Athe delimiter, then the match-only-once rule of C<?PATTERN?> applies.
1N/AIf "'" is the delimiter, no interpolation is performed on the PATTERN.
1N/A
1N/APATTERN may contain variables, which will be interpolated (and the
1N/Apattern recompiled) every time the pattern search is evaluated, except
1N/Afor when the delimiter is a single quote. (Note that C<$(>, C<$)>, and
1N/AC<$|> are not interpolated because they look like end-of-string tests.)
1N/AIf you want such a pattern to be compiled only once, add a C</o> after
1N/Athe trailing delimiter. This avoids expensive run-time recompilations,
1N/Aand is useful when the value you are interpolating won't change over
1N/Athe life of the script. However, mentioning C</o> constitutes a promise
1N/Athat you won't change the variables in the pattern. If you change them,
1N/APerl won't even notice. See also L<"qr/STRING/imosx">.
1N/A
1N/AIf the PATTERN evaluates to the empty string, the last
1N/AI<successfully> matched regular expression is used instead. In this
1N/Acase, only the C<g> and C<c> flags on the empty pattern is honoured -
1N/Athe other flags are taken from the original pattern. If no match has
1N/Apreviously succeeded, this will (silently) act instead as a genuine
1N/Aempty pattern (which will always match).
1N/A
1N/AIf the C</g> option is not used, C<m//> in list context returns a
1N/Alist consisting of the subexpressions matched by the parentheses in the
1N/Apattern, i.e., (C<$1>, C<$2>, C<$3>...). (Note that here C<$1> etc. are
1N/Aalso set, and that this differs from Perl 4's behavior.) When there are
1N/Ano parentheses in the pattern, the return value is the list C<(1)> for
1N/Asuccess. With or without parentheses, an empty list is returned upon
1N/Afailure.
1N/A
1N/AExamples:
1N/A
1N/A open(TTY, '/dev/tty');
1N/A <TTY> =~ /^y/i && foo(); # do foo if desired
1N/A
1N/A if (/Version: *([0-9.]*)/) { $version = $1; }
1N/A
1N/A next if m#^/usr/spool/uucp#;
1N/A
1N/A # poor man's grep
1N/A $arg = shift;
1N/A while (<>) {
1N/A print if /$arg/o; # compile only once
1N/A }
1N/A
1N/A if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
1N/A
1N/AThis last example splits $foo into the first two words and the
1N/Aremainder of the line, and assigns those three fields to $F1, $F2, and
1N/A$Etc. The conditional is true if any variables were assigned, i.e., if
1N/Athe pattern matched.
1N/A
1N/AThe C</g> modifier specifies global pattern matching--that is,
1N/Amatching as many times as possible within the string. How it behaves
1N/Adepends on the context. In list context, it returns a list of the
1N/Asubstrings matched by any capturing parentheses in the regular
1N/Aexpression. If there are no parentheses, it returns a list of all
1N/Athe matched strings, as if there were parentheses around the whole
1N/Apattern.
1N/A
1N/AIn scalar context, each execution of C<m//g> finds the next match,
1N/Areturning true if it matches, and false if there is no further match.
1N/AThe position after the last match can be read or set using the pos()
1N/Afunction; see L<perlfunc/pos>. A failed match normally resets the
1N/Asearch position to the beginning of the string, but you can avoid that
1N/Aby adding the C</c> modifier (e.g. C<m//gc>). Modifying the target
1N/Astring also resets the search position.
1N/A
1N/AYou can intermix C<m//g> matches with C<m/\G.../g>, where C<\G> is a
1N/Azero-width assertion that matches the exact position where the previous
1N/AC<m//g>, if any, left off. Without the C</g> modifier, the C<\G> assertion
1N/Astill anchors at pos(), but the match is of course only attempted once.
1N/AUsing C<\G> without C</g> on a target string that has not previously had a
1N/AC</g> match applied to it is the same as using the C<\A> assertion to match
1N/Athe beginning of the string. Note also that, currently, C<\G> is only
1N/Aproperly supported when anchored at the very beginning of the pattern.
1N/A
1N/AExamples:
1N/A
1N/A # list context
1N/A ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
1N/A
1N/A # scalar context
1N/A $/ = "";
1N/A while (defined($paragraph = <>)) {
1N/A while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
1N/A $sentences++;
1N/A }
1N/A }
1N/A print "$sentences\n";
1N/A
1N/A # using m//gc with \G
1N/A $_ = "ppooqppqq";
1N/A while ($i++ < 2) {
1N/A print "1: '";
1N/A print $1 while /(o)/gc; print "', pos=", pos, "\n";
1N/A print "2: '";
1N/A print $1 if /\G(q)/gc; print "', pos=", pos, "\n";
1N/A print "3: '";
1N/A print $1 while /(p)/gc; print "', pos=", pos, "\n";
1N/A }
1N/A print "Final: '$1', pos=",pos,"\n" if /\G(.)/;
1N/A
1N/AThe last example should print:
1N/A
1N/A 1: 'oo', pos=4
1N/A 2: 'q', pos=5
1N/A 3: 'pp', pos=7
1N/A 1: '', pos=7
1N/A 2: 'q', pos=8
1N/A 3: '', pos=8
1N/A Final: 'q', pos=8
1N/A
1N/ANotice that the final match matched C<q> instead of C<p>, which a match
1N/Awithout the C<\G> anchor would have done. Also note that the final match
1N/Adid not update C<pos> -- C<pos> is only updated on a C</g> match. If the
1N/Afinal match did indeed match C<p>, it's a good bet that you're running an
1N/Aolder (pre-5.6.0) Perl.
1N/A
1N/AA useful idiom for C<lex>-like scanners is C</\G.../gc>. You can
1N/Acombine several regexps like this to process a string part-by-part,
1N/Adoing different actions depending on which regexp matched. Each
1N/Aregexp tries to match where the previous one leaves off.
1N/A
1N/A $_ = <<'EOL';
1N/A $url = new URI::URL "http://www/"; die if $url eq "xXx";
1N/A EOL
1N/A LOOP:
1N/A {
1N/A print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc;
1N/A print(" lowercase"), redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
1N/A print(" UPPERCASE"), redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
1N/A print(" Capitalized"), redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
1N/A print(" MiXeD"), redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
1N/A print(" alphanumeric"), redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
1N/A print(" line-noise"), redo LOOP if /\G[^A-Za-z0-9]+/gc;
1N/A print ". That's all!\n";
1N/A }
1N/A
1N/AHere is the output (split into several lines):
1N/A
1N/A line-noise lowercase line-noise lowercase UPPERCASE line-noise
1N/A UPPERCASE line-noise lowercase line-noise lowercase line-noise
1N/A lowercase lowercase line-noise lowercase lowercase line-noise
1N/A MiXeD line-noise. That's all!
1N/A
1N/A=item q/STRING/
1N/A
1N/A=item C<'STRING'>
1N/A
1N/AA single-quoted, literal string. A backslash represents a backslash
1N/Aunless followed by the delimiter or another backslash, in which case
1N/Athe delimiter or backslash is interpolated.
1N/A
1N/A $foo = q!I said, "You said, 'She said it.'"!;
1N/A $bar = q('This is it.');
1N/A $baz = '\n'; # a two-character string
1N/A
1N/A=item qq/STRING/
1N/A
1N/A=item "STRING"
1N/A
1N/AA double-quoted, interpolated string.
1N/A
1N/A $_ .= qq
1N/A (*** The previous line contains the naughty word "$1".\n)
1N/A if /\b(tcl|java|python)\b/i; # :-)
1N/A $baz = "\n"; # a one-character string
1N/A
1N/A=item qr/STRING/imosx
1N/A
1N/AThis operator quotes (and possibly compiles) its I<STRING> as a regular
1N/Aexpression. I<STRING> is interpolated the same way as I<PATTERN>
1N/Ain C<m/PATTERN/>. If "'" is used as the delimiter, no interpolation
1N/Ais done. Returns a Perl value which may be used instead of the
1N/Acorresponding C</STRING/imosx> expression.
1N/A
1N/AFor example,
1N/A
1N/A $rex = qr/my.STRING/is;
1N/A s/$rex/foo/;
1N/A
1N/Ais equivalent to
1N/A
1N/A s/my.STRING/foo/is;
1N/A
1N/AThe result may be used as a subpattern in a match:
1N/A
1N/A $re = qr/$pattern/;
1N/A $string =~ /foo${re}bar/; # can be interpolated in other patterns
1N/A $string =~ $re; # or used standalone
1N/A $string =~ /$re/; # or this way
1N/A
1N/ASince Perl may compile the pattern at the moment of execution of qr()
1N/Aoperator, using qr() may have speed advantages in some situations,
1N/Anotably if the result of qr() is used standalone:
1N/A
1N/A sub match {
1N/A my $patterns = shift;
1N/A my @compiled = map qr/$_/i, @$patterns;
1N/A grep {
1N/A my $success = 0;
1N/A foreach my $pat (@compiled) {
1N/A $success = 1, last if /$pat/;
1N/A }
1N/A $success;
1N/A } @_;
1N/A }
1N/A
1N/APrecompilation of the pattern into an internal representation at
1N/Athe moment of qr() avoids a need to recompile the pattern every
1N/Atime a match C</$pat/> is attempted. (Perl has many other internal
1N/Aoptimizations, but none would be triggered in the above example if
1N/Awe did not use qr() operator.)
1N/A
1N/AOptions are:
1N/A
1N/A i Do case-insensitive pattern matching.
1N/A m Treat string as multiple lines.
1N/A o Compile pattern only once.
1N/A s Treat string as single line.
1N/A x Use extended regular expressions.
1N/A
1N/ASee L<perlre> for additional information on valid syntax for STRING, and
1N/Afor a detailed look at the semantics of regular expressions.
1N/A
1N/A=item qx/STRING/
1N/A
1N/A=item `STRING`
1N/A
1N/AA string which is (possibly) interpolated and then executed as a
1N/Asystem command with C</bin/sh> or its equivalent. Shell wildcards,
1N/Apipes, and redirections will be honored. The collected standard
1N/Aoutput of the command is returned; standard error is unaffected. In
1N/Ascalar context, it comes back as a single (potentially multi-line)
1N/Astring, or undef if the command failed. In list context, returns a
1N/Alist of lines (however you've defined lines with $/ or
1N/A$INPUT_RECORD_SEPARATOR), or an empty list if the command failed.
1N/A
1N/ABecause backticks do not affect standard error, use shell file descriptor
1N/Asyntax (assuming the shell supports this) if you care to address this.
1N/ATo capture a command's STDERR and STDOUT together:
1N/A
1N/A $output = `cmd 2>&1`;
1N/A
1N/ATo capture a command's STDOUT but discard its STDERR:
1N/A
1N/A $output = `cmd 2>/dev/null`;
1N/A
1N/ATo capture a command's STDERR but discard its STDOUT (ordering is
1N/Aimportant here):
1N/A
1N/A $output = `cmd 2>&1 1>/dev/null`;
1N/A
1N/ATo exchange a command's STDOUT and STDERR in order to capture the STDERR
1N/Abut leave its STDOUT to come out the old STDERR:
1N/A
1N/A $output = `cmd 3>&1 1>&2 2>&3 3>&-`;
1N/A
1N/ATo read both a command's STDOUT and its STDERR separately, it's easiest
1N/Ato redirect them separately to files, and then read from those files
1N/Awhen the program is done:
1N/A
1N/A system("program args 1>program.stdout 2>program.stderr");
1N/A
1N/AUsing single-quote as a delimiter protects the command from Perl's
1N/Adouble-quote interpolation, passing it on to the shell instead:
1N/A
1N/A $perl_info = qx(ps $$); # that's Perl's $$
1N/A $shell_info = qx'ps $$'; # that's the new shell's $$
1N/A
1N/AHow that string gets evaluated is entirely subject to the command
1N/Ainterpreter on your system. On most platforms, you will have to protect
1N/Ashell metacharacters if you want them treated literally. This is in
1N/Apractice difficult to do, as it's unclear how to escape which characters.
1N/ASee L<perlsec> for a clean and safe example of a manual fork() and exec()
1N/Ato emulate backticks safely.
1N/A
1N/AOn some platforms (notably DOS-like ones), the shell may not be
1N/Acapable of dealing with multiline commands, so putting newlines in
1N/Athe string may not get you what you want. You may be able to evaluate
1N/Amultiple commands in a single line by separating them with the command
1N/Aseparator character, if your shell supports that (e.g. C<;> on many Unix
1N/Ashells; C<&> on the Windows NT C<cmd> shell).
1N/A
1N/ABeginning with v5.6.0, Perl will attempt to flush all files opened for
1N/Aoutput before starting the child process, but this may not be supported
1N/Aon some platforms (see L<perlport>). To be safe, you may need to set
1N/AC<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of
1N/AC<IO::Handle> on any open handles.
1N/A
1N/ABeware that some command shells may place restrictions on the length
1N/Aof the command line. You must ensure your strings don't exceed this
1N/Alimit after any necessary interpolations. See the platform-specific
1N/Arelease notes for more details about your particular environment.
1N/A
1N/AUsing this operator can lead to programs that are difficult to port,
1N/Abecause the shell commands called vary between systems, and may in
1N/Afact not be present at all. As one example, the C<type> command under
1N/Athe POSIX shell is very different from the C<type> command under DOS.
1N/AThat doesn't mean you should go out of your way to avoid backticks
1N/Awhen they're the right way to get something done. Perl was made to be
1N/Aa glue language, and one of the things it glues together is commands.
1N/AJust understand what you're getting yourself into.
1N/A
1N/ASee L<"I/O Operators"> for more discussion.
1N/A
1N/A=item qw/STRING/
1N/A
1N/AEvaluates to a list of the words extracted out of STRING, using embedded
1N/Awhitespace as the word delimiters. It can be understood as being roughly
1N/Aequivalent to:
1N/A
1N/A split(' ', q/STRING/);
1N/A
1N/Athe differences being that it generates a real list at compile time, and
1N/Ain scalar context it returns the last element in the list. So
1N/Athis expression:
1N/A
1N/A qw(foo bar baz)
1N/A
1N/Ais semantically equivalent to the list:
1N/A
1N/A 'foo', 'bar', 'baz'
1N/A
1N/ASome frequently seen examples:
1N/A
1N/A use POSIX qw( setlocale localeconv )
1N/A @EXPORT = qw( foo bar baz );
1N/A
1N/AA common mistake is to try to separate the words with comma or to
1N/Aput comments into a multi-line C<qw>-string. For this reason, the
1N/AC<use warnings> pragma and the B<-w> switch (that is, the C<$^W> variable)
1N/Aproduces warnings if the STRING contains the "," or the "#" character.
1N/A
1N/A=item s/PATTERN/REPLACEMENT/egimosx
1N/A
1N/ASearches a string for a pattern, and if found, replaces that pattern
1N/Awith the replacement text and returns the number of substitutions
1N/Amade. Otherwise it returns false (specifically, the empty string).
1N/A
1N/AIf no string is specified via the C<=~> or C<!~> operator, the C<$_>
1N/Avariable is searched and modified. (The string specified with C<=~> must
1N/Abe scalar variable, an array element, a hash element, or an assignment
1N/Ato one of those, i.e., an lvalue.)
1N/A
1N/AIf the delimiter chosen is a single quote, no interpolation is
1N/Adone on either the PATTERN or the REPLACEMENT. Otherwise, if the
1N/APATTERN contains a $ that looks like a variable rather than an
1N/Aend-of-string test, the variable will be interpolated into the pattern
1N/Aat run-time. If you want the pattern compiled only once the first time
1N/Athe variable is interpolated, use the C</o> option. If the pattern
1N/Aevaluates to the empty string, the last successfully executed regular
1N/Aexpression is used instead. See L<perlre> for further explanation on these.
1N/ASee L<perllocale> for discussion of additional considerations that apply
1N/Awhen C<use locale> is in effect.
1N/A
1N/AOptions are:
1N/A
1N/A e Evaluate the right side as an expression.
1N/A g Replace globally, i.e., all occurrences.
1N/A i Do case-insensitive pattern matching.
1N/A m Treat string as multiple lines.
1N/A o Compile pattern only once.
1N/A s Treat string as single line.
1N/A x Use extended regular expressions.
1N/A
1N/AAny non-alphanumeric, non-whitespace delimiter may replace the
1N/Aslashes. If single quotes are used, no interpretation is done on the
1N/Areplacement string (the C</e> modifier overrides this, however). Unlike
1N/APerl 4, Perl 5 treats backticks as normal delimiters; the replacement
1N/Atext is not evaluated as a command. If the
1N/APATTERN is delimited by bracketing quotes, the REPLACEMENT has its own
1N/Apair of quotes, which may or may not be bracketing quotes, e.g.,
1N/AC<s(foo)(bar)> or C<< s<foo>/bar/ >>. A C</e> will cause the
1N/Areplacement portion to be treated as a full-fledged Perl expression
1N/Aand evaluated right then and there. It is, however, syntax checked at
1N/Acompile-time. A second C<e> modifier will cause the replacement portion
1N/Ato be C<eval>ed before being run as a Perl expression.
1N/A
1N/AExamples:
1N/A
1N/A s/\bgreen\b/mauve/g; # don't change wintergreen
1N/A
1N/A $path =~ s|/usr/bin|/usr/local/bin|;
1N/A
1N/A s/Login: $foo/Login: $bar/; # run-time pattern
1N/A
1N/A ($foo = $bar) =~ s/this/that/; # copy first, then change
1N/A
1N/A $count = ($paragraph =~ s/Mister\b/Mr./g); # get change-count
1N/A
1N/A $_ = 'abc123xyz';
1N/A s/\d+/$&*2/e; # yields 'abc246xyz'
1N/A s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz'
1N/A s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz'
1N/A
1N/A s/%(.)/$percent{$1}/g; # change percent escapes; no /e
1N/A s/%(.)/$percent{$1} || $&/ge; # expr now, so /e
1N/A s/^=(\w+)/&pod($1)/ge; # use function call
1N/A
1N/A # expand variables in $_, but dynamics only, using
1N/A # symbolic dereferencing
1N/A s/\$(\w+)/${$1}/g;
1N/A
1N/A # Add one to the value of any numbers in the string
1N/A s/(\d+)/1 + $1/eg;
1N/A
1N/A # This will expand any embedded scalar variable
1N/A # (including lexicals) in $_ : First $1 is interpolated
1N/A # to the variable name, and then evaluated
1N/A s/(\$\w+)/$1/eeg;
1N/A
1N/A # Delete (most) C comments.
1N/A $program =~ s {
1N/A /\* # Match the opening delimiter.
1N/A .*? # Match a minimal number of characters.
1N/A \*/ # Match the closing delimiter.
1N/A } []gsx;
1N/A
1N/A s/^\s*(.*?)\s*$/$1/; # trim white space in $_, expensively
1N/A
1N/A for ($variable) { # trim white space in $variable, cheap
1N/A s/^\s+//;
1N/A s/\s+$//;
1N/A }
1N/A
1N/A s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields
1N/A
1N/ANote the use of $ instead of \ in the last example. Unlike
1N/AB<sed>, we use the \<I<digit>> form in only the left hand side.
1N/AAnywhere else it's $<I<digit>>.
1N/A
1N/AOccasionally, you can't use just a C</g> to get all the changes
1N/Ato occur that you might want. Here are two common cases:
1N/A
1N/A # put commas in the right places in an integer
1N/A 1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;
1N/A
1N/A # expand tabs to 8-column spacing
1N/A 1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
1N/A
1N/A=item tr/SEARCHLIST/REPLACEMENTLIST/cds
1N/A
1N/A=item y/SEARCHLIST/REPLACEMENTLIST/cds
1N/A
1N/ATransliterates all occurrences of the characters found in the search list
1N/Awith the corresponding character in the replacement list. It returns
1N/Athe number of characters replaced or deleted. If no string is
1N/Aspecified via the =~ or !~ operator, the $_ string is transliterated. (The
1N/Astring specified with =~ must be a scalar variable, an array element, a
1N/Ahash element, or an assignment to one of those, i.e., an lvalue.)
1N/A
1N/AA character range may be specified with a hyphen, so C<tr/A-J/0-9/>
1N/Adoes the same replacement as C<tr/ACEGIBDFHJ/0246813579/>.
1N/AFor B<sed> devotees, C<y> is provided as a synonym for C<tr>. If the
1N/ASEARCHLIST is delimited by bracketing quotes, the REPLACEMENTLIST has
1N/Aits own pair of quotes, which may or may not be bracketing quotes,
1N/Ae.g., C<tr[A-Z][a-z]> or C<tr(+\-*/)/ABCD/>.
1N/A
1N/ANote that C<tr> does B<not> do regular expression character classes
1N/Asuch as C<\d> or C<[:lower:]>. The <tr> operator is not equivalent to
1N/Athe tr(1) utility. If you want to map strings between lower/upper
1N/Acases, see L<perlfunc/lc> and L<perlfunc/uc>, and in general consider
1N/Ausing the C<s> operator if you need regular expressions.
1N/A
1N/ANote also that the whole range idea is rather unportable between
1N/Acharacter sets--and even within character sets they may cause results
1N/Ayou probably didn't expect. A sound principle is to use only ranges
1N/Athat begin from and end at either alphabets of equal case (a-e, A-E),
1N/Aor digits (0-4). Anything else is unsafe. If in doubt, spell out the
1N/Acharacter sets in full.
1N/A
1N/AOptions:
1N/A
1N/A c Complement the SEARCHLIST.
1N/A d Delete found but unreplaced characters.
1N/A s Squash duplicate replaced characters.
1N/A
1N/AIf the C</c> modifier is specified, the SEARCHLIST character set
1N/Ais complemented. If the C</d> modifier is specified, any characters
1N/Aspecified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
1N/A(Note that this is slightly more flexible than the behavior of some
1N/AB<tr> programs, which delete anything they find in the SEARCHLIST,
1N/Aperiod.) If the C</s> modifier is specified, sequences of characters
1N/Athat were transliterated to the same character are squashed down
1N/Ato a single instance of the character.
1N/A
1N/AIf the C</d> modifier is used, the REPLACEMENTLIST is always interpreted
1N/Aexactly as specified. Otherwise, if the REPLACEMENTLIST is shorter
1N/Athan the SEARCHLIST, the final character is replicated till it is long
1N/Aenough. If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated.
1N/AThis latter is useful for counting characters in a class or for
1N/Asquashing character sequences in a class.
1N/A
1N/AExamples:
1N/A
1N/A $ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case
1N/A
1N/A $cnt = tr/*/*/; # count the stars in $_
1N/A
1N/A $cnt = $sky =~ tr/*/*/; # count the stars in $sky
1N/A
1N/A $cnt = tr/0-9//; # count the digits in $_
1N/A
1N/A tr/a-zA-Z//s; # bookkeeper -> bokeper
1N/A
1N/A ($HOST = $host) =~ tr/a-z/A-Z/;
1N/A
1N/A tr/a-zA-Z/ /cs; # change non-alphas to single space
1N/A
1N/A tr [\200-\377]
1N/A [\000-\177]; # delete 8th bit
1N/A
1N/AIf multiple transliterations are given for a character, only the
1N/Afirst one is used:
1N/A
1N/A tr/AAA/XYZ/
1N/A
1N/Awill transliterate any A to X.
1N/A
1N/ABecause the transliteration table is built at compile time, neither
1N/Athe SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote
1N/Ainterpolation. That means that if you want to use variables, you
1N/Amust use an eval():
1N/A
1N/A eval "tr/$oldlist/$newlist/";
1N/A die $@ if $@;
1N/A
1N/A eval "tr/$oldlist/$newlist/, 1" or die $@;
1N/A
1N/A=item <<EOF
1N/A
1N/AA line-oriented form of quoting is based on the shell "here-document"
1N/Asyntax. Following a C<< << >> you specify a string to terminate
1N/Athe quoted material, and all lines following the current line down to
1N/Athe terminating string are the value of the item. The terminating
1N/Astring may be either an identifier (a word), or some quoted text. If
1N/Aquoted, the type of quotes you use determines the treatment of the
1N/Atext, just as in regular quoting. An unquoted identifier works like
1N/Adouble quotes. There must be no space between the C<< << >> and
1N/Athe identifier, unless the identifier is quoted. (If you put a space it
1N/Awill be treated as a null identifier, which is valid, and matches the first
1N/Aempty line.) The terminating string must appear by itself (unquoted and
1N/Awith no surrounding whitespace) on the terminating line.
1N/A
1N/A print <<EOF;
1N/A The price is $Price.
1N/A EOF
1N/A
1N/A print << "EOF"; # same as above
1N/A The price is $Price.
1N/A EOF
1N/A
1N/A print << `EOC`; # execute commands
1N/A echo hi there
1N/A echo lo there
1N/A EOC
1N/A
1N/A print <<"foo", <<"bar"; # you can stack them
1N/A I said foo.
1N/A foo
1N/A I said bar.
1N/A bar
1N/A
1N/A myfunc(<< "THIS", 23, <<'THAT');
1N/A Here's a line
1N/A or two.
1N/A THIS
1N/A and here's another.
1N/A THAT
1N/A
1N/AJust don't forget that you have to put a semicolon on the end
1N/Ato finish the statement, as Perl doesn't know you're not going to
1N/Atry to do this:
1N/A
1N/A print <<ABC
1N/A 179231
1N/A ABC
1N/A + 20;
1N/A
1N/AIf you want your here-docs to be indented with the
1N/Arest of the code, you'll need to remove leading whitespace
1N/Afrom each line manually:
1N/A
1N/A ($quote = <<'FINIS') =~ s/^\s+//gm;
1N/A The Road goes ever on and on,
1N/A down from the door where it began.
1N/A FINIS
1N/A
1N/AIf you use a here-doc within a delimited construct, such as in C<s///eg>,
1N/Athe quoted material must come on the lines following the final delimiter.
1N/ASo instead of
1N/A
1N/A s/this/<<E . 'that'
1N/A the other
1N/A E
1N/A . 'more '/eg;
1N/A
1N/Ayou have to write
1N/A
1N/A s/this/<<E . 'that'
1N/A . 'more '/eg;
1N/A the other
1N/A E
1N/A
1N/AIf the terminating identifier is on the last line of the program, you
1N/Amust be sure there is a newline after it; otherwise, Perl will give the
1N/Awarning B<Can't find string terminator "END" anywhere before EOF...>.
1N/A
1N/AAdditionally, the quoting rules for the identifier are not related to
1N/APerl's quoting rules -- C<q()>, C<qq()>, and the like are not supported
1N/Ain place of C<''> and C<"">, and the only interpolation is for backslashing
1N/Athe quoting character:
1N/A
1N/A print << "abc\"def";
1N/A testing...
1N/A abc"def
1N/A
1N/AFinally, quoted strings cannot span multiple lines. The general rule is
1N/Athat the identifier must be a string literal. Stick with that, and you
1N/Ashould be safe.
1N/A
1N/A=back
1N/A
1N/A=head2 Gory details of parsing quoted constructs
1N/A
1N/AWhen presented with something that might have several different
1N/Ainterpretations, Perl uses the B<DWIM> (that's "Do What I Mean")
1N/Aprinciple to pick the most probable interpretation. This strategy
1N/Ais so successful that Perl programmers often do not suspect the
1N/Aambivalence of what they write. But from time to time, Perl's
1N/Anotions differ substantially from what the author honestly meant.
1N/A
1N/AThis section hopes to clarify how Perl handles quoted constructs.
1N/AAlthough the most common reason to learn this is to unravel labyrinthine
1N/Aregular expressions, because the initial steps of parsing are the
1N/Asame for all quoting operators, they are all discussed together.
1N/A
1N/AThe most important Perl parsing rule is the first one discussed
1N/Abelow: when processing a quoted construct, Perl first finds the end
1N/Aof that construct, then interprets its contents. If you understand
1N/Athis rule, you may skip the rest of this section on the first
1N/Areading. The other rules are likely to contradict the user's
1N/Aexpectations much less frequently than this first one.
1N/A
1N/ASome passes discussed below are performed concurrently, but because
1N/Atheir results are the same, we consider them individually. For different
1N/Aquoting constructs, Perl performs different numbers of passes, from
1N/Aone to five, but these passes are always performed in the same order.
1N/A
1N/A=over 4
1N/A
1N/A=item Finding the end
1N/A
1N/AThe first pass is finding the end of the quoted construct, whether
1N/Ait be a multicharacter delimiter C<"\nEOF\n"> in the C<<<EOF>
1N/Aconstruct, a C</> that terminates a C<qq//> construct, a C<]> which
1N/Aterminates C<qq[]> construct, or a C<< > >> which terminates a
1N/Afileglob started with C<< < >>.
1N/A
1N/AWhen searching for single-character non-pairing delimiters, such
1N/Aas C</>, combinations of C<\\> and C<\/> are skipped. However,
1N/Awhen searching for single-character pairing delimiter like C<[>,
1N/Acombinations of C<\\>, C<\]>, and C<\[> are all skipped, and nested
1N/AC<[>, C<]> are skipped as well. When searching for multicharacter
1N/Adelimiters, nothing is skipped.
1N/A
1N/AFor constructs with three-part delimiters (C<s///>, C<y///>, and
1N/AC<tr///>), the search is repeated once more.
1N/A
1N/ADuring this search no attention is paid to the semantics of the construct.
1N/AThus:
1N/A
1N/A "$hash{"$foo/$bar"}"
1N/A
1N/Aor:
1N/A
1N/A m/
1N/A bar # NOT a comment, this slash / terminated m//!
1N/A /x
1N/A
1N/Ado not form legal quoted expressions. The quoted part ends on the
1N/Afirst C<"> and C</>, and the rest happens to be a syntax error.
1N/ABecause the slash that terminated C<m//> was followed by a C<SPACE>,
1N/Athe example above is not C<m//x>, but rather C<m//> with no C</x>
1N/Amodifier. So the embedded C<#> is interpreted as a literal C<#>.
1N/A
1N/A=item Removal of backslashes before delimiters
1N/A
1N/ADuring the second pass, text between the starting and ending
1N/Adelimiters is copied to a safe location, and the C<\> is removed
1N/Afrom combinations consisting of C<\> and delimiter--or delimiters,
1N/Ameaning both starting and ending delimiters will should these differ.
1N/AThis removal does not happen for multi-character delimiters.
1N/ANote that the combination C<\\> is left intact, just as it was.
1N/A
1N/AStarting from this step no information about the delimiters is
1N/Aused in parsing.
1N/A
1N/A=item Interpolation
1N/A
1N/AThe next step is interpolation in the text obtained, which is now
1N/Adelimiter-independent. There are four different cases.
1N/A
1N/A=over 4
1N/A
1N/A=item C<<<'EOF'>, C<m''>, C<s'''>, C<tr///>, C<y///>
1N/A
1N/ANo interpolation is performed.
1N/A
1N/A=item C<''>, C<q//>
1N/A
1N/AThe only interpolation is removal of C<\> from pairs C<\\>.
1N/A
1N/A=item C<"">, C<``>, C<qq//>, C<qx//>, C<< <file*glob> >>
1N/A
1N/AC<\Q>, C<\U>, C<\u>, C<\L>, C<\l> (possibly paired with C<\E>) are
1N/Aconverted to corresponding Perl constructs. Thus, C<"$foo\Qbaz$bar">
1N/Ais converted to C<$foo . (quotemeta("baz" . $bar))> internally.
1N/AThe other combinations are replaced with appropriate expansions.
1N/A
1N/ALet it be stressed that I<whatever falls between C<\Q> and C<\E>>
1N/Ais interpolated in the usual way. Something like C<"\Q\\E"> has
1N/Ano C<\E> inside. instead, it has C<\Q>, C<\\>, and C<E>, so the
1N/Aresult is the same as for C<"\\\\E">. As a general rule, backslashes
1N/Abetween C<\Q> and C<\E> may lead to counterintuitive results. So,
1N/AC<"\Q\t\E"> is converted to C<quotemeta("\t")>, which is the same
1N/Aas C<"\\\t"> (since TAB is not alphanumeric). Note also that:
1N/A
1N/A $str = '\t';
1N/A return "\Q$str";
1N/A
1N/Amay be closer to the conjectural I<intention> of the writer of C<"\Q\t\E">.
1N/A
1N/AInterpolated scalars and arrays are converted internally to the C<join> and
1N/AC<.> catenation operations. Thus, C<"$foo XXX '@arr'"> becomes:
1N/A
1N/A $foo . " XXX '" . (join $", @arr) . "'";
1N/A
1N/AAll operations above are performed simultaneously, left to right.
1N/A
1N/ABecause the result of C<"\Q STRING \E"> has all metacharacters
1N/Aquoted, there is no way to insert a literal C<$> or C<@> inside a
1N/AC<\Q\E> pair. If protected by C<\>, C<$> will be quoted to became
1N/AC<"\\\$">; if not, it is interpreted as the start of an interpolated
1N/Ascalar.
1N/A
1N/ANote also that the interpolation code needs to make a decision on
1N/Awhere the interpolated scalar ends. For instance, whether
1N/AC<< "a $b -> {c}" >> really means:
1N/A
1N/A "a " . $b . " -> {c}";
1N/A
1N/Aor:
1N/A
1N/A "a " . $b -> {c};
1N/A
1N/AMost of the time, the longest possible text that does not include
1N/Aspaces between components and which contains matching braces or
1N/Abrackets. because the outcome may be determined by voting based
1N/Aon heuristic estimators, the result is not strictly predictable.
1N/AFortunately, it's usually correct for ambiguous cases.
1N/A
1N/A=item C<?RE?>, C</RE/>, C<m/RE/>, C<s/RE/foo/>,
1N/A
1N/AProcessing of C<\Q>, C<\U>, C<\u>, C<\L>, C<\l>, and interpolation
1N/Ahappens (almost) as with C<qq//> constructs, but the substitution
1N/Aof C<\> followed by RE-special chars (including C<\>) is not
1N/Aperformed. Moreover, inside C<(?{BLOCK})>, C<(?# comment )>, and
1N/Aa C<#>-comment in a C<//x>-regular expression, no processing is
1N/Aperformed whatsoever. This is the first step at which the presence
1N/Aof the C<//x> modifier is relevant.
1N/A
1N/AInterpolation has several quirks: C<$|>, C<$(>, and C<$)> are not
1N/Ainterpolated, and constructs C<$var[SOMETHING]> are voted (by several
1N/Adifferent estimators) to be either an array element or C<$var>
1N/Afollowed by an RE alternative. This is where the notation
1N/AC<${arr[$bar]}> comes handy: C</${arr[0-9]}/> is interpreted as
1N/Aarray element C<-9>, not as a regular expression from the variable
1N/AC<$arr> followed by a digit, which would be the interpretation of
1N/AC</$arr[0-9]/>. Since voting among different estimators may occur,
1N/Athe result is not predictable.
1N/A
1N/AIt is at this step that C<\1> is begrudgingly converted to C<$1> in
1N/Athe replacement text of C<s///> to correct the incorrigible
1N/AI<sed> hackers who haven't picked up the saner idiom yet. A warning
1N/Ais emitted if the C<use warnings> pragma or the B<-w> command-line flag
1N/A(that is, the C<$^W> variable) was set.
1N/A
1N/AThe lack of processing of C<\\> creates specific restrictions on
1N/Athe post-processed text. If the delimiter is C</>, one cannot get
1N/Athe combination C<\/> into the result of this step. C</> will
1N/Afinish the regular expression, C<\/> will be stripped to C</> on
1N/Athe previous step, and C<\\/> will be left as is. Because C</> is
1N/Aequivalent to C<\/> inside a regular expression, this does not
1N/Amatter unless the delimiter happens to be character special to the
1N/ARE engine, such as in C<s*foo*bar*>, C<m[foo]>, or C<?foo?>; or an
1N/Aalphanumeric char, as in:
1N/A
1N/A m m ^ a \s* b mmx;
1N/A
1N/AIn the RE above, which is intentionally obfuscated for illustration, the
1N/Adelimiter is C<m>, the modifier is C<mx>, and after backslash-removal the
1N/ARE is the same as for C<m/ ^ a \s* b /mx>. There's more than one
1N/Areason you're encouraged to restrict your delimiters to non-alphanumeric,
1N/Anon-whitespace choices.
1N/A
1N/A=back
1N/A
1N/AThis step is the last one for all constructs except regular expressions,
1N/Awhich are processed further.
1N/A
1N/A=item Interpolation of regular expressions
1N/A
1N/APrevious steps were performed during the compilation of Perl code,
1N/Abut this one happens at run time--although it may be optimized to
1N/Abe calculated at compile time if appropriate. After preprocessing
1N/Adescribed above, and possibly after evaluation if catenation,
1N/Ajoining, casing translation, or metaquoting are involved, the
1N/Aresulting I<string> is passed to the RE engine for compilation.
1N/A
1N/AWhatever happens in the RE engine might be better discussed in L<perlre>,
1N/Abut for the sake of continuity, we shall do so here.
1N/A
1N/AThis is another step where the presence of the C<//x> modifier is
1N/Arelevant. The RE engine scans the string from left to right and
1N/Aconverts it to a finite automaton.
1N/A
1N/ABackslashed characters are either replaced with corresponding
1N/Aliteral strings (as with C<\{>), or else they generate special nodes
1N/Ain the finite automaton (as with C<\b>). Characters special to the
1N/ARE engine (such as C<|>) generate corresponding nodes or groups of
1N/Anodes. C<(?#...)> comments are ignored. All the rest is either
1N/Aconverted to literal strings to match, or else is ignored (as is
1N/Awhitespace and C<#>-style comments if C<//x> is present).
1N/A
1N/AParsing of the bracketed character class construct, C<[...]>, is
1N/Arather different than the rule used for the rest of the pattern.
1N/AThe terminator of this construct is found using the same rules as
1N/Afor finding the terminator of a C<{}>-delimited construct, the only
1N/Aexception being that C<]> immediately following C<[> is treated as
1N/Athough preceded by a backslash. Similarly, the terminator of
1N/AC<(?{...})> is found using the same rules as for finding the
1N/Aterminator of a C<{}>-delimited construct.
1N/A
1N/AIt is possible to inspect both the string given to RE engine and the
1N/Aresulting finite automaton. See the arguments C<debug>/C<debugcolor>
1N/Ain the C<use L<re>> pragma, as well as Perl's B<-Dr> command-line
1N/Aswitch documented in L<perlrun/"Command Switches">.
1N/A
1N/A=item Optimization of regular expressions
1N/A
1N/AThis step is listed for completeness only. Since it does not change
1N/Asemantics, details of this step are not documented and are subject
1N/Ato change without notice. This step is performed over the finite
1N/Aautomaton that was generated during the previous pass.
1N/A
1N/AIt is at this stage that C<split()> silently optimizes C</^/> to
1N/Amean C</^/m>.
1N/A
1N/A=back
1N/A
1N/A=head2 I/O Operators
1N/A
1N/AThere are several I/O operators you should know about.
1N/A
1N/AA string enclosed by backticks (grave accents) first undergoes
1N/Adouble-quote interpolation. It is then interpreted as an external
1N/Acommand, and the output of that command is the value of the
1N/Abacktick string, like in a shell. In scalar context, a single string
1N/Aconsisting of all output is returned. In list context, a list of
1N/Avalues is returned, one per line of output. (You can set C<$/> to use
1N/Aa different line terminator.) The command is executed each time the
1N/Apseudo-literal is evaluated. The status value of the command is
1N/Areturned in C<$?> (see L<perlvar> for the interpretation of C<$?>).
1N/AUnlike in B<csh>, no translation is done on the return data--newlines
1N/Aremain newlines. Unlike in any of the shells, single quotes do not
1N/Ahide variable names in the command from interpretation. To pass a
1N/Aliteral dollar-sign through to the shell you need to hide it with a
1N/Abackslash. The generalized form of backticks is C<qx//>. (Because
1N/Abackticks always undergo shell expansion as well, see L<perlsec> for
1N/Asecurity concerns.)
1N/A
1N/AIn scalar context, evaluating a filehandle in angle brackets yields
1N/Athe next line from that file (the newline, if any, included), or
1N/AC<undef> at end-of-file or on error. When C<$/> is set to C<undef>
1N/A(sometimes known as file-slurp mode) and the file is empty, it
1N/Areturns C<''> the first time, followed by C<undef> subsequently.
1N/A
1N/AOrdinarily you must assign the returned value to a variable, but
1N/Athere is one situation where an automatic assignment happens. If
1N/Aand only if the input symbol is the only thing inside the conditional
1N/Aof a C<while> statement (even if disguised as a C<for(;;)> loop),
1N/Athe value is automatically assigned to the global variable $_,
1N/Adestroying whatever was there previously. (This may seem like an
1N/Aodd thing to you, but you'll use the construct in almost every Perl
1N/Ascript you write.) The $_ variable is not implicitly localized.
1N/AYou'll have to put a C<local $_;> before the loop if you want that
1N/Ato happen.
1N/A
1N/AThe following lines are equivalent:
1N/A
1N/A while (defined($_ = <STDIN>)) { print; }
1N/A while ($_ = <STDIN>) { print; }
1N/A while (<STDIN>) { print; }
1N/A for (;<STDIN>;) { print; }
1N/A print while defined($_ = <STDIN>);
1N/A print while ($_ = <STDIN>);
1N/A print while <STDIN>;
1N/A
1N/AThis also behaves similarly, but avoids $_ :
1N/A
1N/A while (my $line = <STDIN>) { print $line }
1N/A
1N/AIn these loop constructs, the assigned value (whether assignment
1N/Ais automatic or explicit) is then tested to see whether it is
1N/Adefined. The defined test avoids problems where line has a string
1N/Avalue that would be treated as false by Perl, for example a "" or
1N/Aa "0" with no trailing newline. If you really mean for such values
1N/Ato terminate the loop, they should be tested for explicitly:
1N/A
1N/A while (($_ = <STDIN>) ne '0') { ... }
1N/A while (<STDIN>) { last unless $_; ... }
1N/A
1N/AIn other boolean contexts, C<< <I<filehandle>> >> without an
1N/Aexplicit C<defined> test or comparison elicit a warning if the
1N/AC<use warnings> pragma or the B<-w>
1N/Acommand-line switch (the C<$^W> variable) is in effect.
1N/A
1N/AThe filehandles STDIN, STDOUT, and STDERR are predefined. (The
1N/Afilehandles C<stdin>, C<stdout>, and C<stderr> will also work except
1N/Ain packages, where they would be interpreted as local identifiers
1N/Arather than global.) Additional filehandles may be created with
1N/Athe open() function, amongst others. See L<perlopentut> and
1N/AL<perlfunc/open> for details on this.
1N/A
1N/AIf a <FILEHANDLE> is used in a context that is looking for
1N/Aa list, a list comprising all input lines is returned, one line per
1N/Alist element. It's easy to grow to a rather large data space this
1N/Away, so use with care.
1N/A
1N/A<FILEHANDLE> may also be spelled C<readline(*FILEHANDLE)>.
1N/ASee L<perlfunc/readline>.
1N/A
1N/AThe null filehandle <> is special: it can be used to emulate the
1N/Abehavior of B<sed> and B<awk>. Input from <> comes either from
1N/Astandard input, or from each file listed on the command line. Here's
1N/Ahow it works: the first time <> is evaluated, the @ARGV array is
1N/Achecked, and if it is empty, C<$ARGV[0]> is set to "-", which when opened
1N/Agives you standard input. The @ARGV array is then processed as a list
1N/Aof filenames. The loop
1N/A
1N/A while (<>) {
1N/A ... # code for each line
1N/A }
1N/A
1N/Ais equivalent to the following Perl-like pseudo code:
1N/A
1N/A unshift(@ARGV, '-') unless @ARGV;
1N/A while ($ARGV = shift) {
1N/A open(ARGV, $ARGV);
1N/A while (<ARGV>) {
1N/A ... # code for each line
1N/A }
1N/A }
1N/A
1N/Aexcept that it isn't so cumbersome to say, and will actually work.
1N/AIt really does shift the @ARGV array and put the current filename
1N/Ainto the $ARGV variable. It also uses filehandle I<ARGV>
1N/Ainternally--<> is just a synonym for <ARGV>, which
1N/Ais magical. (The pseudo code above doesn't work because it treats
1N/A<ARGV> as non-magical.)
1N/A
1N/AYou can modify @ARGV before the first <> as long as the array ends up
1N/Acontaining the list of filenames you really want. Line numbers (C<$.>)
1N/Acontinue as though the input were one big happy file. See the example
1N/Ain L<perlfunc/eof> for how to reset line numbers on each file.
1N/A
1N/AIf you want to set @ARGV to your own list of files, go right ahead.
1N/AThis sets @ARGV to all plain text files if no @ARGV was given:
1N/A
1N/A @ARGV = grep { -f && -T } glob('*') unless @ARGV;
1N/A
1N/AYou can even set them to pipe commands. For example, this automatically
1N/Afilters compressed arguments through B<gzip>:
1N/A
1N/A @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;
1N/A
1N/AIf you want to pass switches into your script, you can use one of the
1N/AGetopts modules or put a loop on the front like this:
1N/A
1N/A while ($_ = $ARGV[0], /^-/) {
1N/A shift;
1N/A last if /^--$/;
1N/A if (/^-D(.*)/) { $debug = $1 }
1N/A if (/^-v/) { $verbose++ }
1N/A # ... # other switches
1N/A }
1N/A
1N/A while (<>) {
1N/A # ... # code for each line
1N/A }
1N/A
1N/AThe <> symbol will return C<undef> for end-of-file only once.
1N/AIf you call it again after this, it will assume you are processing another
1N/A@ARGV list, and if you haven't set @ARGV, will read input from STDIN.
1N/A
1N/AIf what the angle brackets contain is a simple scalar variable (e.g.,
1N/A<$foo>), then that variable contains the name of the
1N/Afilehandle to input from, or its typeglob, or a reference to the
1N/Asame. For example:
1N/A
1N/A $fh = \*STDIN;
1N/A $line = <$fh>;
1N/A
1N/AIf what's within the angle brackets is neither a filehandle nor a simple
1N/Ascalar variable containing a filehandle name, typeglob, or typeglob
1N/Areference, it is interpreted as a filename pattern to be globbed, and
1N/Aeither a list of filenames or the next filename in the list is returned,
1N/Adepending on context. This distinction is determined on syntactic
1N/Agrounds alone. That means C<< <$x> >> is always a readline() from
1N/Aan indirect handle, but C<< <$hash{key}> >> is always a glob().
1N/AThat's because $x is a simple scalar variable, but C<$hash{key}> is
1N/Anot--it's a hash element.
1N/A
1N/AOne level of double-quote interpretation is done first, but you can't
1N/Asay C<< <$foo> >> because that's an indirect filehandle as explained
1N/Ain the previous paragraph. (In older versions of Perl, programmers
1N/Awould insert curly brackets to force interpretation as a filename glob:
1N/AC<< <${foo}> >>. These days, it's considered cleaner to call the
1N/Ainternal function directly as C<glob($foo)>, which is probably the right
1N/Away to have done it in the first place.) For example:
1N/A
1N/A while (<*.c>) {
1N/A chmod 0644, $_;
1N/A }
1N/A
1N/Ais roughly equivalent to:
1N/A
1N/A open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
1N/A while (<FOO>) {
1N/A chomp;
1N/A chmod 0644, $_;
1N/A }
1N/A
1N/Aexcept that the globbing is actually done internally using the standard
1N/AC<File::Glob> extension. Of course, the shortest way to do the above is:
1N/A
1N/A chmod 0644, <*.c>;
1N/A
1N/AA (file)glob evaluates its (embedded) argument only when it is
1N/Astarting a new list. All values must be read before it will start
1N/Aover. In list context, this isn't important because you automatically
1N/Aget them all anyway. However, in scalar context the operator returns
1N/Athe next value each time it's called, or C<undef> when the list has
1N/Arun out. As with filehandle reads, an automatic C<defined> is
1N/Agenerated when the glob occurs in the test part of a C<while>,
1N/Abecause legal glob returns (e.g. a file called F<0>) would otherwise
1N/Aterminate the loop. Again, C<undef> is returned only once. So if
1N/Ayou're expecting a single value from a glob, it is much better to
1N/Asay
1N/A
1N/A ($file) = <blurch*>;
1N/A
1N/Athan
1N/A
1N/A $file = <blurch*>;
1N/A
1N/Abecause the latter will alternate between returning a filename and
1N/Areturning false.
1N/A
1N/AIf you're trying to do variable interpolation, it's definitely better
1N/Ato use the glob() function, because the older notation can cause people
1N/Ato become confused with the indirect filehandle notation.
1N/A
1N/A @files = glob("$dir/*.[ch]");
1N/A @files = glob($files[$i]);
1N/A
1N/A=head2 Constant Folding
1N/A
1N/ALike C, Perl does a certain amount of expression evaluation at
1N/Acompile time whenever it determines that all arguments to an
1N/Aoperator are static and have no side effects. In particular, string
1N/Aconcatenation happens at compile time between literals that don't do
1N/Avariable substitution. Backslash interpolation also happens at
1N/Acompile time. You can say
1N/A
1N/A 'Now is the time for all' . "\n" .
1N/A 'good men to come to.'
1N/A
1N/Aand this all reduces to one string internally. Likewise, if
1N/Ayou say
1N/A
1N/A foreach $file (@filenames) {
1N/A if (-s $file > 5 + 100 * 2**16) { }
1N/A }
1N/A
1N/Athe compiler will precompute the number which that expression
1N/Arepresents so that the interpreter won't have to.
1N/A
1N/A=head2 Bitwise String Operators
1N/A
1N/ABitstrings of any size may be manipulated by the bitwise operators
1N/A(C<~ | & ^>).
1N/A
1N/AIf the operands to a binary bitwise op are strings of different
1N/Asizes, B<|> and B<^> ops act as though the shorter operand had
1N/Aadditional zero bits on the right, while the B<&> op acts as though
1N/Athe longer operand were truncated to the length of the shorter.
1N/AThe granularity for such extension or truncation is one or more
1N/Abytes.
1N/A
1N/A # ASCII-based examples
1N/A print "j p \n" ^ " a h"; # prints "JAPH\n"
1N/A print "JA" | " ph\n"; # prints "japh\n"
1N/A print "japh\nJunk" & '_____'; # prints "JAPH\n";
1N/A print 'p N$' ^ " E<H\n"; # prints "Perl\n";
1N/A
1N/AIf you are intending to manipulate bitstrings, be certain that
1N/Ayou're supplying bitstrings: If an operand is a number, that will imply
1N/Aa B<numeric> bitwise operation. You may explicitly show which type of
1N/Aoperation you intend by using C<""> or C<0+>, as in the examples below.
1N/A
1N/A $foo = 150 | 105 ; # yields 255 (0x96 | 0x69 is 0xFF)
1N/A $foo = '150' | 105 ; # yields 255
1N/A $foo = 150 | '105'; # yields 255
1N/A $foo = '150' | '105'; # yields string '155' (under ASCII)
1N/A
1N/A $baz = 0+$foo & 0+$bar; # both ops explicitly numeric
1N/A $biz = "$foo" ^ "$bar"; # both ops explicitly stringy
1N/A
1N/ASee L<perlfunc/vec> for information on how to manipulate individual bits
1N/Ain a bit vector.
1N/A
1N/A=head2 Integer Arithmetic
1N/A
1N/ABy default, Perl assumes that it must do most of its arithmetic in
1N/Afloating point. But by saying
1N/A
1N/A use integer;
1N/A
1N/Ayou may tell the compiler that it's okay to use integer operations
1N/A(if it feels like it) from here to the end of the enclosing BLOCK.
1N/AAn inner BLOCK may countermand this by saying
1N/A
1N/A no integer;
1N/A
1N/Awhich lasts until the end of that BLOCK. Note that this doesn't
1N/Amean everything is only an integer, merely that Perl may use integer
1N/Aoperations if it is so inclined. For example, even under C<use
1N/Ainteger>, if you take the C<sqrt(2)>, you'll still get C<1.4142135623731>
1N/Aor so.
1N/A
1N/AUsed on numbers, the bitwise operators ("&", "|", "^", "~", "<<",
1N/Aand ">>") always produce integral results. (But see also
1N/AL<Bitwise String Operators>.) However, C<use integer> still has meaning for
1N/Athem. By default, their results are interpreted as unsigned integers, but
1N/Aif C<use integer> is in effect, their results are interpreted
1N/Aas signed integers. For example, C<~0> usually evaluates to a large
1N/Aintegral value. However, C<use integer; ~0> is C<-1> on twos-complement
1N/Amachines.
1N/A
1N/A=head2 Floating-point Arithmetic
1N/A
1N/AWhile C<use integer> provides integer-only arithmetic, there is no
1N/Aanalogous mechanism to provide automatic rounding or truncation to a
1N/Acertain number of decimal places. For rounding to a certain number
1N/Aof digits, sprintf() or printf() is usually the easiest route.
1N/ASee L<perlfaq4>.
1N/A
1N/AFloating-point numbers are only approximations to what a mathematician
1N/Awould call real numbers. There are infinitely more reals than floats,
1N/Aso some corners must be cut. For example:
1N/A
1N/A printf "%.20g\n", 123456789123456789;
1N/A # produces 123456789123456784
1N/A
1N/ATesting for exact equality of floating-point equality or inequality is
1N/Anot a good idea. Here's a (relatively expensive) work-around to compare
1N/Awhether two floating-point numbers are equal to a particular number of
1N/Adecimal places. See Knuth, volume II, for a more robust treatment of
1N/Athis topic.
1N/A
1N/A sub fp_equal {
1N/A my ($X, $Y, $POINTS) = @_;
1N/A my ($tX, $tY);
1N/A $tX = sprintf("%.${POINTS}g", $X);
1N/A $tY = sprintf("%.${POINTS}g", $Y);
1N/A return $tX eq $tY;
1N/A }
1N/A
1N/AThe POSIX module (part of the standard perl distribution) implements
1N/Aceil(), floor(), and other mathematical and trigonometric functions.
1N/AThe Math::Complex module (part of the standard perl distribution)
1N/Adefines mathematical functions that work on both the reals and the
1N/Aimaginary numbers. Math::Complex not as efficient as POSIX, but
1N/APOSIX can't work with complex numbers.
1N/A
1N/ARounding in financial applications can have serious implications, and
1N/Athe rounding method used should be specified precisely. In these
1N/Acases, it probably pays not to trust whichever system rounding is
1N/Abeing used by Perl, but to instead implement the rounding function you
1N/Aneed yourself.
1N/A
1N/A=head2 Bigger Numbers
1N/A
1N/AThe standard Math::BigInt and Math::BigFloat modules provide
1N/Avariable-precision arithmetic and overloaded operators, although
1N/Athey're currently pretty slow. At the cost of some space and
1N/Aconsiderable speed, they avoid the normal pitfalls associated with
1N/Alimited-precision representations.
1N/A
1N/A use Math::BigInt;
1N/A $x = Math::BigInt->new('123456789123456789');
1N/A print $x * $x;
1N/A
1N/A # prints +15241578780673678515622620750190521
1N/A
1N/AThere are several modules that let you calculate with (bound only by
1N/Amemory and cpu-time) unlimited or fixed precision. There are also
1N/Asome non-standard modules that provide faster implementations via
1N/Aexternal C libraries.
1N/A
1N/AHere is a short, but incomplete summary:
1N/A
1N/A Math::Fraction big, unlimited fractions like 9973 / 12967
1N/A Math::String treat string sequences like numbers
1N/A Math::FixedPrecision calculate with a fixed precision
1N/A Math::Currency for currency calculations
1N/A Bit::Vector manipulate bit vectors fast (uses C)
1N/A Math::BigIntFast Bit::Vector wrapper for big numbers
1N/A Math::Pari provides access to the Pari C library
1N/A Math::BigInteger uses an external C library
1N/A Math::Cephes uses external Cephes C library (no big numbers)
1N/A Math::Cephes::Fraction fractions via the Cephes library
1N/A Math::GMP another one using an external C library
1N/A
1N/AChoose wisely.
1N/A
1N/A=cut