perlman
gods
<HR>
<P>
<H1><A NAME="NAME">NAME</A></H1>
<P>
perlop - Perl operators and precedence
<P>
<HR>
<H1><A NAME="SYNOPSIS">SYNOPSIS</A></H1>
<P>
Perl operators have the following associativity and precedence, listed from highest precedence to lowest. Note that all operators borrowed from
<FONT SIZE=-1>C</FONT> keep the same precedence relationship with each other, even where C's precedence is slightly screwy. (This makes learning Perl easier for
<FONT SIZE=-1>C</FONT> folks.) With very few exceptions, these all operate on scalar values only, not array values.
<P>
<PRE> 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
</PRE>
<P>
In the following sections, these operators are covered in precedence order.
<P>
Many operators can be overloaded for objects. See <U>the overload manpage</U><!--../lib/overload.html-->.
<P>
<HR>
<H1><A NAME="DESCRIPTION">DESCRIPTION</A></H1>
<P>
<HR>
<H2><A NAME="Terms_and_List_Operators_Leftwa">Terms and List Operators (Leftward)</A></H2>
<P>
<FONT SIZE=-1>A</FONT>
<FONT SIZE=-1>TERM</FONT> has the highest precedence in Perl. They includes 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
[perlman:perlfunc|the perlfunc manpage].
<P>
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.
<P>
In the absence of parentheses, the precedence of list operators such as
[perlfunc:print|print], [perlfunc:sort|sort], or [perlfunc:chmod|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
<P>
<PRE> @ary = (1, 3, sort 4, 2);
print @ary; # prints 1324
</PRE>
<P>
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
<FONT SIZE=-1>TERM</FONT> with regard to the preceding expression. Note that you have to be careful with parentheses:
<P>
<PRE> # These evaluate exit before doing the print:
print($foo, exit); # Obviously not what you want.
print $foo, exit; # Nor is this.
</PRE>
<P>
<PRE> # 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.
</PRE>
<P>
Also note that
<P>
<PRE> print ($foo & 255) + 1, "\n";
</PRE>
<P>
probably doesn't do what you expect at first glance. See
<A HREF="#Named_Unary_Operators">Named Unary Operators</A> for more discussion of this.
<P>
Also parsed as terms are the [perlfunc:do] and [perlfunc:eval] constructs, as well as subroutine and method calls, and the anonymous
constructors <CODE>[]</CODE> and <CODE>{}</CODE>.
<P>
See also <A HREF="#Quote_and_Quote_like_Operators">Quote and Quote-like Operators</A> toward the end of this section, as well as <A HREF="#I_O_Operators">I/O Operators</A>.
<P>
<HR>
<H2><A NAME="The_Arrow_Operator">The Arrow Operator</A></H2>
<P>
Just as in
<FONT SIZE=-1>C</FONT> and
<FONT SIZE=-1>C++,</FONT> ``<CODE>-></CODE>'' is an infix dereference operator. If the right side is either a <CODE>[...]</CODE> or <CODE>{...}</CODE> 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 [perlman:perlref|the perlref manpage].
<P>
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 [perlman:perlobj|the perlobj manpage].
<P>
<HR>
<H2><A NAME="Auto_increment_and_Auto_decremen">Auto-increment and Auto-decrement</A></H2>
<P>
``++'' and ``--'' work as in
<FONT SIZE=-1>C.</FONT> 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.
<P>
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
<CODE>/^[a-zA-Z]*[0-9]*$/</CODE>, the increment is done as a string, preserving each character within its
range, with carry:
<P>
<PRE> print ++($foo = '99'); # prints '100'
print ++($foo = 'a0'); # prints 'a1'
print ++($foo = 'Az'); # prints 'Ba'
print ++($foo = 'zz'); # prints 'aaa'
</PRE>
<P>
The auto-decrement operator is not magical.
<P>
<HR>
<H2><A NAME="Exponentiation">Exponentiation</A></H2>
<P>
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
<CODE>pow(3)</CODE> function, which actually works on doubles internally.)
<P>
<HR>
<H2><A NAME="Symbolic_Unary_Operators">Symbolic Unary Operators</A></H2>
<P>
Unary ``!'' performs logical negation, i.e., ``not''. See also <CODE>not</CODE> for a lower precedence version of this.
<P>
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 <CODE>-bareword</CODE> is equivalent to <CODE>"-bareword"</CODE>.
<P>
Unary ``~'' performs bitwise negation, i.e., 1's complement. For example,
<CODE>0666 &~ 027</CODE> is 0640. (See also <A HREF="#Integer_Arithmetic">Integer Arithmetic</A> and <A HREF="#Bitwise_String_Operators">Bitwise String Operators</A>.)
<P>
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 <A HREF="#Terms_and_List_Operators_Leftwa">Terms and List Operators (Leftward)</A>.)
<P>
Unary ``\'' creates a reference to whatever follows it. See [perlman:perlref|the perlref manpage]. 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.
<P>
<HR>
<H2><A NAME="Binding_Operators">Binding Operators</A></H2>
<P>
Binary ``=~'' binds a scalar expression to a pattern match. Certain
operations search or modify the string <CODE>$_</CODE> 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.
<P>
Binary ``!~'' is just like ``=~'' except the return value is negated in the
logical sense.
<P>
<HR>
<H2><A NAME="Multiplicative_Operators">Multiplicative Operators</A></H2>
<P>
Binary ``*'' multiplies two numbers.
<P>
Binary ``/'' divides two numbers.
<P>
Binary ``%'' computes the modulus of two numbers. Given integer operands <CODE>$a</CODE> and <CODE>$b</CODE>: If <CODE>$b</CODE> is positive, then <CODE>$a % $b</CODE> is
<CODE>$a</CODE> minus the largest multiple of <CODE>$b</CODE> that is not greater than
<CODE>$a</CODE>. If <CODE>$b</CODE> is negative, then <CODE>$a % $b</CODE> is <CODE>$a</CODE> minus the smallest multiple of <CODE>$b</CODE> that is not less than <CODE>$a</CODE> (i.e. the result will be less than or equal to zero). Note than when <CODE>use integer</CODE> is in scope, ``%'' give you direct access to the modulus operator as implemented by your
<FONT SIZE=-1>C</FONT> compiler. This operator is not as well defined for negative operands, but it will execute faster.
<P>
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.
<P>
<PRE> print '-' x 80; # print row of dashes
</PRE>
<P>
<PRE> print "\t" x ($tab/8), ' ' x ($tab%8); # tab over
</PRE>
<P>
<PRE> @ones = (1) x 80; # a list of 80 1's
@ones = (5) x @ones; # set all elements to 5
</PRE>
<P>
<HR>
<H2><A NAME="Additive_Operators">Additive Operators</A></H2>
<P>
Binary ``+'' returns the sum of two numbers.
<P>
Binary ``-'' returns the difference of two numbers.
<P>
Binary ``.'' concatenates two strings.
<P>
<HR>
<H2><A NAME="Shift_Operators">Shift Operators</A></H2>
<P>
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 <A HREF="#Integer_Arithmetic">Integer Arithmetic</A>.)
<P>
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 <A HREF="#Integer_Arithmetic">Integer Arithmetic</A>.)
<P>
<HR>
<H2><A NAME="Named_Unary_Operators">Named Unary Operators</A></H2>
<P>
The various named unary operators are treated as functions with one
argument, with optional parentheses. These include the filetest operators,
like <CODE>-f</CODE>, <CODE>-M</CODE>, etc. See [perlman:perlfunc|the perlfunc manpage].
<P>
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:
<P>
<PRE> chdir $foo || die; # (chdir $foo) || die
chdir($foo) || die; # (chdir $foo) || die
chdir ($foo) || die; # (chdir $foo) || die
chdir +($foo) || die; # (chdir $foo) || die
</PRE>
<P>
but, because * is higher precedence than ||:
<P>
<PRE> chdir $foo * 20; # chdir ($foo * 20)
chdir($foo) * 20; # (chdir $foo) * 20
chdir ($foo) * 20; # (chdir $foo) * 20
chdir +($foo) * 20; # chdir ($foo * 20)
</PRE>
<P>
<PRE> rand 10 * 20; # rand (10 * 20)
rand(10) * 20; # (rand 10) * 20
rand (10) * 20; # (rand 10) * 20
rand +(10) * 20; # rand (10 * 20)
</PRE>
<P>
See also <A HREF="#Terms_and_List_Operators_Leftwa">Terms and List Operators (Leftward)</A>.
<P>
<HR>
<H2><A NAME="Relational_Operators">Relational Operators</A></H2>
<P>
Binary ``<'' returns true if the left argument is numerically less than
the right argument.
<P>
Binary ``>'' returns true if the left argument is numerically greater
than the right argument.
<P>
Binary ``<='' returns true if the left argument is numerically less
than or equal to the right argument.
<P>
Binary ``>='' returns true if the left argument is numerically greater
than or equal to the right argument.
<P>
Binary ``lt'' returns true if the left argument is stringwise less than the
right argument.
<P>
Binary ``gt'' returns true if the left argument is stringwise greater than
the right argument.
<P>
Binary ``le'' returns true if the left argument is stringwise less than or
equal to the right argument.
<P>
Binary ``ge'' returns true if the left argument is stringwise greater than
or equal to the right argument.
<P>
<HR>
<H2><A NAME="Equality_Operators">Equality Operators</A></H2>
<P>
Binary ``=='' returns true if the left argument is numerically equal to the
right argument.
<P>
Binary ``!='' returns true if the left argument is numerically not equal to
the right argument.
<P>
Binary ``<=>'' returns -1, 0, or 1 depending on whether the left
argument is numerically less than, equal to, or greater than the right
argument.
<P>
Binary ``eq'' returns true if the left argument is stringwise equal to the
right argument.
<P>
Binary ``ne'' returns true if the left argument is stringwise not equal to
the right argument.
<P>
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.
<P>
``lt'', ``le'', ``ge'', ``gt'' and ``cmp'' use the collation (sort) order
specified by the current locale if <CODE>use locale</CODE> is in effect. See [perlman:perllocale|the perllocale manpage].
<P>
<HR>
<H2><A NAME="Bitwise_And">Bitwise And</A></H2>
<P>
Binary ``&'' returns its operators ANDed together bit by bit. (See also <A HREF="#Integer_Arithmetic">Integer Arithmetic</A> and <A HREF="#Bitwise_String_Operators">Bitwise String Operators</A>.)
<P>
<HR>
<H2><A NAME="Bitwise_Or_and_Exclusive_Or">Bitwise Or and Exclusive Or</A></H2>
<P>
Binary ``|'' returns its operators ORed together bit by bit. (See also <A HREF="#Integer_Arithmetic">Integer Arithmetic</A> and <A HREF="#Bitwise_String_Operators">Bitwise String Operators</A>.)
<P>
Binary ``^'' returns its operators XORed together bit by bit. (See also <A HREF="#Integer_Arithmetic">Integer Arithmetic</A> and <A HREF="#Bitwise_String_Operators">Bitwise String Operators</A>.)
<P>
<HR>
<H2><A NAME="C_style_Logical_And">C-style Logical And</A></H2>
<P>
Binary ``&&'' performs a short-circuit logical
<FONT SIZE=-1>AND</FONT> 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.
<P>
<HR>
<H2><A NAME="C_style_Logical_Or">C-style Logical Or</A></H2>
<P>
Binary ``||'' performs a short-circuit logical
<FONT SIZE=-1>OR</FONT> 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.
<P>
The <CODE>||</CODE> and <CODE>&&</CODE> 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:
<P>
<PRE> $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
(getpwuid($<))[7] || die "You're homeless!\n";
</PRE>
<P>
In particular, this means that you shouldn't use this for selecting between
two aggregates for assignment:
<P>
<PRE> @a = @b || @c; # this is wrong
@a = scalar(@b) || @c; # really meant this
@a = @b ? @b : @c; # this works fine, though
</PRE>
<P>
As more readable alternatives to <CODE>&&</CODE> and <CODE>||</CODE> when used for control flow, Perl provides <CODE>and</CODE> and <CODE>or</CODE> 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:
<P>
<PRE> unlink "alpha", "beta", "gamma"
or gripe(), next LINE;
</PRE>
<P>
With the C-style operators that would have been written like this:
<P>
<PRE> unlink("alpha", "beta", "gamma")
|| (gripe(), next LINE);
</PRE>
<P>
Use ``or'' for assignment is unlikely to do what you want; see below.
<P>
<HR>
<H2><A NAME="Range_Operators">Range Operators</A></H2>
<P>
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 <CODE>foreach (1..10)</CODE> 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 <CODE>foreach</CODE> loops, but older versions of Perl might burn a lot of memory when you write
something like this:
<P>
<PRE> for (1 .. 1_000_000) {
# code
}
</PRE>
<P>
In scalar context, ``..'' returns a boolean value. The operator is
bistable, like a flip-flop, and emulates the line-range (comma) operator of <STRONG>sed</STRONG>, <STRONG>awk</STRONG>, 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, <EM>AFTER</EM> 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 <STRONG>awk</STRONG>), but it still returns true once. If you don't want it to test the right
operand till the next evaluation (as in <STRONG>sed</STRONG>), 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
<FONT SIZE=-1>``E0''</FONT> 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
<CODE>$.</CODE> variable, the current line number. Examples:
<P>
As a scalar operator:
<P>
<PRE> if (101 .. 200) { print; } # print 2nd hundred lines
next line if (1 .. /^$/); # skip header lines
s/^/> / if (/^$/ .. eof()); # quote body
</PRE>
<P>
<PRE> # parse mail messages
while (<>) {
$in_header = 1 .. /^$/;
$in_body = /^$/ .. eof();
# do something based on those
} continue {
close ARGV if eof; # reset $. each file
}
</PRE>
<P>
As a list operator:
<P>
<PRE> for (101 .. 200) { print; } # print $_ 100 times
@foo = @foo[0 .. $#foo]; # an expensive no-op
@foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
</PRE>
<P>
The range operator (in list context) makes use of the magical
auto-increment algorithm if the operands are strings. You can say
<P>
<PRE> @alphabet = ('A' .. 'Z');
</PRE>
<P>
to get all the letters of the alphabet, or
<P>
<PRE> $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
</PRE>
<P>
to get a hexadecimal digit, or
<P>
<PRE> @z2 = ('01' .. '31'); print $z2[$mday];
</PRE>
<P>
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.
<P>
<HR>
<H2><A NAME="Conditional_Operator">Conditional Operator</A></H2>
<P>
Ternary ``?:'' is the conditional operator, just as in
<FONT SIZE=-1>C.</FONT> 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:
<P>
<PRE> printf "I have %d dog%s.\n", $n,
($n == 1) ? '' : "s";
</PRE>
<P>
Scalar or list context propagates downward into the 2nd or 3rd argument,
whichever is selected.
<P>
<PRE> $a = $ok ? $b : $c; # get a scalar
@a = $ok ? @b : @c; # get an array
$a = $ok ? @b : @c; # oops, that's just a count!
</PRE>
<P>
The operator may be assigned to if both the 2nd and 3rd arguments are legal
lvalues (meaning that you can assign to them):
<P>
<PRE> ($a_or_b ? $a : $b) = $c;
</PRE>
<P>
This is not necessarily guaranteed to contribute to the readability of your
program.
<P>
Because this operator produces an assignable result, using assignments
without parentheses will get you in trouble. For example, this:
<P>
<PRE> $a % 2 ? $a += 10 : $a += 2
</PRE>
<P>
Really means this:
<P>
<PRE> (($a % 2) ? ($a += 10) : $a) += 2
</PRE>
<P>
Rather than this:
<P>
<PRE> ($a % 2) ? ($a += 10) : ($a += 2)
</PRE>
<P>
<HR>
<H2><A NAME="Assignment_Operators">Assignment Operators</A></H2>
<P>
``='' is the ordinary assignment operator.
<P>
Assignment operators work as in
<FONT SIZE=-1>C.</FONT> That is,
<P>
<PRE> $a += 2;
</PRE>
<P>
is equivalent to
<P>
<PRE> $a = $a + 2;
</PRE>
<P>
although without duplicating any side effects that dereferencing the lvalue might trigger, such as from
<CODE>tie().</CODE> Other assignment operators work similarly. The following are recognized:
<P>
<PRE> **= += *= &= <<= &&=
-= /= |= >>= ||=
.= %= ^=
x=
</PRE>
<P>
Note that while these are grouped by family, they all have the precedence
of assignment.
<P>
Unlike in
<FONT SIZE=-1>C,</FONT> 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:
<P>
<PRE> ($tmp = $global) =~ tr [A-Z] [a-z];
</PRE>
<P>
Likewise,
<P>
<PRE> ($a += 2) *= 3;
</PRE>
<P>
is equivalent to
<P>
<PRE> $a += 2;
$a *= 3;
</PRE>
<P>
<HR>
<H2><A NAME="Comma_Operator">Comma Operator</A></H2>
<P>
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.
<P>
In list context, it's just the list argument separator, and inserts both
its arguments into the list.
<P>
The => 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.
<P>
<HR>
<H2><A NAME="List_Operators_Rightward_">List Operators (Rightward)</A></H2>
<P>
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:
<P>
<PRE> open HANDLE, "filename"
or die "Can't open: $!\n";
</PRE>
<P>
See also discussion of list operators in <A HREF="#Terms_and_List_Operators_Leftwa">Terms and List Operators (Leftward)</A>.
<P>
<HR>
<H2><A NAME="Logical_Not">Logical Not</A></H2>
<P>
Unary ``not'' returns the logical negation of the expression to its right.
It's the equivalent of ``!'' except for the very low precedence.
<P>
<HR>
<H2><A NAME="Logical_And">Logical And</A></H2>
<P>
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.
<P>
<HR>
<H2><A NAME="Logical_or_and_Exclusive_Or">Logical or and Exclusive Or</A></H2>
<P>
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
<P>
<PRE> print FH $data or die "Can't write to FH: $!";
</PRE>
<P>
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.
<P>
<PRE> $a = $b or $c; # bug: this is wrong
($a = $b) or $c; # really means this
$a = $b || $c; # better written this way
</PRE>
<P>
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.
<P>
<PRE> @info = stat($file) || die; # oops, scalar sense of stat!
@info = stat($file) or die; # better, now @info gets its due
</PRE>
<P>
Then again, you could always use parentheses.
<P>
Binary ``xor'' returns the exclusive-OR of the two surrounding expressions.
It cannot short circuit, of course.
<P>
<HR>
<H2><A NAME="C_Operators_Missing_From_Perl">C Operators Missing From Perl</A></H2>
<P>
Here is what
<FONT SIZE=-1>C</FONT> has that Perl doesn't:
<DL>
<DT><STRONG><A NAME="item_unary">unary &</A></STRONG><P>
<DD>
Address-of operator. (But see the ``\'' operator for taking a reference.)
<P><DT><STRONG>unary *</STRONG><P>
<DD>
Dereference-address operator. (Perl's prefix dereferencing operators are
typed: $, @, %, and &.)
<P><DT><STRONG><A NAME="item__TYPE_">(TYPE)</A></STRONG><P>
<DD>
Type casting operator.
</DL>
<P>
<HR>
<H2><A NAME="Quote_and_Quote_like_Operators">Quote and Quote-like Operators</A></H2>
<P>
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 <CODE>{}</CODE> 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.
<P>
<PRE> Customary Generic Meaning Interpolates
'' q{} Literal no
"" qq{} Literal yes
`` qx{} Command yes (unless '' is delimiter)
qw{} Word list no
// m{} Pattern match yes
qr{} Pattern yes
s{}{} Substitution yes
tr{}{} Transliteration no (but see below)
</PRE>
<P>
Note that there can be whitespace between the operator and the quoting
characters, except when <CODE>#</CODE> is being used as the quoting character.
<CODE>q#foo#</CODE> is parsed as being the string <CODE>foo</CODE>, while <CODE>q #foo#</CODE> is the operator [perlman:perlop] followed by a comment. Its argument will be taken from the next line. This
allows you to write:
<P>
<PRE> s {foo} # Replace foo
{bar} # with bar.
</PRE>
<P>
For constructs that do interpolation, variables beginning with ``<CODE>$</CODE>'' or ``<CODE>@</CODE>'' are interpolated, as are the following sequences. Within a
transliteration, the first ten of these sequences may be used.
<P>
<PRE> \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
\x1b hex char
\c[ control char
</PRE>
<P>
<PRE> \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
</PRE>
<P>
If <CODE>use locale</CODE> is in effect, the case map used by <CODE>\l</CODE>, <CODE>\L</CODE>, <CODE>\u</CODE>
and <CODE>\U</CODE> is taken from the current locale. See [perlman:perllocale|the perllocale manpage].
<P>
All systems use the virtual <CODE>"\n"</CODE> 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,
<FONT SIZE=-1>C</FONT> libraries, and Perl all conspire to preserve. Not all systems read
<CODE>"\r"</CODE> as
<FONT SIZE=-1>ASCII</FONT>
<FONT SIZE=-1>CR</FONT> and <CODE>"\n"</CODE> as
<FONT SIZE=-1>ASCII</FONT>
<FONT SIZE=-1>LF.</FONT> For example, on a Mac, these are reversed, and on systems without line terminator, printing
<CODE>"\n"</CODE> may emit no actual data. In general, use <CODE>"\n"</CODE> when you mean a ``newline'' for your system, but use the literal
<FONT SIZE=-1>ASCII</FONT> when you need an exact character. For example, most networking protocols expect and prefer a
<FONT SIZE=-1>CR+LF</FONT> (
<CODE>"\012\015"</CODE> or <CODE>"\cJ\cM"</CODE>) for line terminators, and although they often accept just <CODE>"\012"</CODE>, they seldom tolerate just
<CODE>"\015"</CODE>. If you get in the habit of using <CODE>"\n"</CODE> for networking, you may be burned some day.
<P>
You cannot include a literal <CODE>$</CODE> or <CODE>@</CODE> within a <CODE>\Q</CODE> sequence. An unescaped <CODE>$</CODE> or <CODE>@</CODE> interpolates the corresponding variable, while escaping will cause the
literal string <CODE>\$</CODE> to be inserted. You'll need to write something like <CODE>m/\Quser\E\@\Qhost/</CODE>.
<P>
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 <CODE>\Q</CODE> to interpolate a variable literally.
<P>
Apart from the above, there are no multiple levels of interpolation. In
particular, contrary to the expectations of shell programmers, back-quotes
do <EM>NOT</EM> interpolate within double quotes, nor do single quotes impede evaluation of
variables when used within double quotes.
<P>
<HR>
<H2><A NAME="Regexp_Quote_Like_Operators">Regexp Quote-Like Operators</A></H2>
<P>
Here are the quote-like operators that apply to pattern matching and
related activities.
<P>
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
<FONT SIZE=-1>RE</FONT> (regular expression) engine to match,
<FONT SIZE=-1>RE</FONT> engine finds (or does not find) the match, and Perl uses the findings of
<FONT SIZE=-1>RE</FONT> engine for its operation, possibly asking the engine for other matches.
<P>
<FONT SIZE=-1>RE</FONT> 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
<FONT SIZE=-1>RE</FONT> 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
[perlman:perlre|the perlre manpage].
<DL>
<DT><STRONG><A NAME="item__PATTERN_">?PATTERN?</A></STRONG><P>
<DD>
This is just like the <CODE>/pattern/</CODE> search, except that it matches only once between calls to the
<CODE>reset()</CODE> 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 <CODE>??</CODE>
patterns local to the current package are reset.
<P>
<PRE> while (<>) {
if (?^$?) {
# blank line between header and body
}
} continue {
reset if eof; # clear ?? status for next file
}
</PRE>
<P>
This usage is vaguely deprecated, and may be removed in some future version
of Perl.
<P><DT><STRONG><A NAME="item_m">m/PATTERN/cgimosx</A></STRONG><DD>
<DT><STRONG><A NAME="item__PATTERN_cgimosx">/PATTERN/cgimosx</A></STRONG><P>
<DD>
Searches a string for a pattern match, and in scalar context returns true
(1) or false (''). If no string is specified via the <CODE>=~</CODE> or
<CODE>!~</CODE> operator, the <CODE>$_</CODE> string is searched. (The string specified
with
<CODE>=~</CODE> need not be an lvalue--it may be the result of an expression evaluation,
but remember the <CODE>=~</CODE> binds rather tightly.) See also
[perlman:perlre|the perlre manpage]. See [perlman:perllocale|the perllocale manpage] for discussion of additional considerations that apply when <CODE>use locale</CODE> is in effect.
<P>
Options are:
<P>
<PRE> c Do not reset search position on a failed match when /g is in effect.
g Match globally, i.e., find all occurrences.
i Do case-insensitive pattern matching.
m Treat string as multiple lines.
o Compile pattern only once.
s Treat string as single line.
x Use extended regular expressions.
</PRE>
<P>
If ``/'' is the delimiter then the initial [perlman:perlop] is optional. With the [perlman:perlop]
you can use any pair of non-alphanumeric, non-whitespace characters as delimiters (if single quotes are used, no interpretation is done on the replacement string. Unlike Perl 4, Perl 5 treats backticks as normal delimiters; the replacement text is not evaluated as a command). This is particularly useful for matching Unix path names that contain ``/'', to avoid
<FONT SIZE=-1>LTS</FONT> (leaning toothpick syndrome). If ``?'' is the delimiter, then the match-only-once rule of
<CODE>?PATTERN?</CODE> applies.
<P>
<FONT SIZE=-1>PATTERN</FONT> may contain variables, which will be
interpolated (and the pattern recompiled) every time the pattern search is
evaluated. (Note that <CODE>$)</CODE> and <CODE>$|</CODE> might not be interpolated because they look like end-of-string tests.) If
you want such a pattern to be compiled only once, add a <CODE>/o</CODE> after the trailing delimiter. This avoids expensive run-time
recompilations, and is useful when the value you are interpolating won't
change over the life of the script. However, mentioning
<CODE>/o</CODE> constitutes a promise that you won't change the variables in the pattern.
If you change them, Perl won't even notice.
<P>
If the
<FONT SIZE=-1>PATTERN</FONT> evaluates to the empty string, the last
<EM>successfully</EM> matched regular expression is used instead.
<P>
If the <CODE>/g</CODE> option is not used, [perlman:perlop] in a list context returns a list consisting of the subexpressions matched
by the parentheses in the pattern, i.e., (<CODE>$1</CODE>, <CODE>$2</CODE>, <CODE>$3</CODE>...). (Note that here <CODE>$1</CODE> etc. are also set, and that this differs from Perl 4's behavior.) When
there are no parentheses in the pattern, the return value is the list <CODE>(1)</CODE> for success. With or without parentheses, an empty list is returned upon
failure.
<P>
Examples:
<P>
<PRE> open(TTY, '/dev/tty');
<TTY> =~ /^y/i && foo(); # do foo if desired
</PRE>
<P>
<PRE> if (/Version: *([0-9.]*)/) { $version = $1; }
</PRE>
<P>
<PRE> next if m#^/usr/spool/uucp#;
</PRE>
<P>
<PRE> # poor man's grep
$arg = shift;
while (<>) {
print if /$arg/o; # compile only once
}
</PRE>
<P>
<PRE> if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
</PRE>
<P>
This last example splits <CODE>$foo</CODE> into the first two words and the remainder of the line, and assigns those three fields to
<FONT SIZE=-1>$F1,</FONT>
<FONT SIZE=-1>$F2,</FONT> and $Etc. The conditional is true if any variables were assigned, i.e., if the pattern matched.
<P>
The <CODE>/g</CODE> modifier specifies global pattern matching--that is, matching as many times
as possible within the string. How it behaves depends on the context. In
list context, it returns a list of all the substrings matched by all the
parentheses in the regular expression. If there are no parentheses, it
returns a list of all the matched strings, as if there were parentheses
around the whole pattern.
<P>
In scalar context, each execution of <CODE>m//g</CODE> finds the next match, returning
<FONT SIZE=-1>TRUE</FONT> if it matches, and
<FONT SIZE=-1>FALSE</FONT> if there is no further match. The position after the last match can be read or set using the
<CODE>pos()</CODE> function; see
[perlfunc:pos|pos].
<FONT SIZE=-1>A</FONT> failed match normally resets the search position to
the beginning of the string, but you can avoid that by adding the <CODE>/c</CODE> modifier (e.g. <CODE>m//gc</CODE>). Modifying the target string also resets the search position.
<P>
You can intermix <CODE>m//g</CODE> matches with <CODE>m/\G.../g</CODE>, where <CODE>\G</CODE> is a zero-width assertion that matches the exact position where the
previous
<CODE>m//g</CODE>, if any, left off. The <CODE>\G</CODE> assertion is not supported without the <CODE>/g</CODE> modifier; currently, without <CODE>/g</CODE>, <CODE>\G</CODE> behaves just like
<CODE>\A</CODE>, but that's accidental and may change in the future.
<P>
Examples:
<P>
<PRE> # list context
($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
</PRE>
<P>
<PRE> # scalar context
$/ = ""; $* = 1; # $* deprecated in modern perls
while (defined($paragraph = <>)) {
while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
$sentences++;
}
}
print "$sentences\n";
</PRE>
<P>
<PRE> # using m//gc with \G
$_ = "ppooqppqq";
while ($i++ < 2) {
print "1: '";
print $1 while /(o)/gc; print "', pos=", pos, "\n";
print "2: '";
print $1 if /\G(q)/gc; print "', pos=", pos, "\n";
print "3: '";
print $1 while /(p)/gc; print "', pos=", pos, "\n";
}
</PRE>
<P>
The last example should print:
<P>
<PRE> 1: 'oo', pos=4
2: 'q', pos=5
3: 'pp', pos=7
1: '', pos=7
2: 'q', pos=8
3: '', pos=8
</PRE>
<P>
<FONT SIZE=-1>A</FONT> useful idiom for <CODE>lex</CODE>-like scanners is <CODE>/\G.../gc</CODE>. You can combine several regexps like this to process a string
part-by-part, doing different actions depending on which regexp matched.
Each regexp tries to match where the previous one leaves off.
<P>
<PRE> $_ = <<'EOL';
$url = new URI::URL "<A HREF="http://www/"">http://www/"</A>;; die if $url eq "xXx";
EOL
LOOP:
{
print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc;
print(" lowercase"), redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
print(" UPPERCASE"), redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
print(" Capitalized"), redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
print(" MiXeD"), redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
print(" alphanumeric"), redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
print(" line-noise"), redo LOOP if /\G[^A-Za-z0-9]+/gc;
print ". That's all!\n";
}
</PRE>
<P>
Here is the output (split into several lines):
<P>
<PRE> line-noise lowercase line-noise lowercase UPPERCASE line-noise
UPPERCASE line-noise lowercase line-noise lowercase line-noise
lowercase lowercase line-noise lowercase lowercase line-noise
MiXeD line-noise. That's all!
</PRE>
<DT><STRONG><A NAME="item_q">q/STRING/</A></STRONG><DD>
<DT><STRONG><A NAME="item__STRING_">'STRING'</A></STRONG><P>
<DD>
<FONT SIZE=-1>A</FONT> single-quoted, literal string.
<FONT SIZE=-1>A</FONT> backslash represents a backslash unless followed by the delimiter or another backslash, in which case the delimiter or backslash is interpolated.
<P>
<PRE> $foo = q!I said, "You said, 'She said it.'"!;
$bar = q('This is it.');
$baz = '\n'; # a two-character string
</PRE>
<DT><STRONG><A NAME="item_qq">qq/STRING/</A></STRONG><DD>
<DT><STRONG><A NAME="item__STRING_">"STRING"</A></STRONG><P>
<DD>
<FONT SIZE=-1>A</FONT> double-quoted, interpolated string.
<P>
<PRE> $_ .= qq
(*** The previous line contains the naughty word "$1".\n)
if /(tcl|rexx|python)/; # :-)
$baz = "\n"; # a one-character string
</PRE>
<DT><STRONG><A NAME="item_qr">qr/STRING/imosx</A></STRONG><P>
<DD>
<FONT SIZE=-1>A</FONT> string which is (possibly) interpolated and then
compiled as a regular expression. The result may be used as a pattern in a
match
<P>
<PRE> $re = qr/$pattern/;
$string =~ /foo${re}bar/; # can be interpolated in other patterns
$string =~ $re; # or used standalone
</PRE>
<P>
Options are:
<P>
<PRE> i Do case-insensitive pattern matching.
m Treat string as multiple lines.
o Compile pattern only once.
s Treat string as single line.
x Use extended regular expressions.
</PRE>
<P>
The benefit from this is that the pattern is precompiled into an internal
representation, and does not need to be recompiled every time a match is
attempted. This makes it very efficient to do something like:
<P>
<PRE> foreach $pattern (@pattern_list) {
my $re = qr/$pattern/;
foreach $line (@lines) {
if($line =~ /$re/) {
do_something($line);
}
}
}
</PRE>
<P>
See [perlman:perlre|the perlre manpage] for additional information on valid syntax for
<FONT SIZE=-1>STRING,</FONT> and for a detailed look at the semantics of
regular expressions.
<P><DT><STRONG><A NAME="item_qx">qx/STRING/</A></STRONG><DD>
<DT><STRONG><A NAME="item__STRING_">`STRING`</A></STRONG><P>
<DD>
<FONT SIZE=-1>A</FONT> string which is (possibly) interpolated and then
executed as a system command with <CODE>/bin/sh</CODE> or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected. In scalar context, it comes back as a single (potentially multi-line) string. In list context, returns a list of lines (however you've defined lines with $/ or
<FONT SIZE=-1>$INPUT_RECORD_SEPARATOR).</FONT>
<P>
Because backticks do not affect standard error, use shell file descriptor syntax (assuming the shell supports this) if you care to address this. To capture a command's
<FONT SIZE=-1>STDERR</FONT> and
<FONT SIZE=-1>STDOUT</FONT> together:
<P>
<PRE> $output = `cmd 2>&1`;
</PRE>
<P>
To capture a command's
<FONT SIZE=-1>STDOUT</FONT> but discard its
<FONT SIZE=-1>STDERR:</FONT>
<P>
<PRE> $output = `cmd 2>/dev/null`;
</PRE>
<P>
To capture a command's
<FONT SIZE=-1>STDERR</FONT> but discard its
<FONT SIZE=-1>STDOUT</FONT> (ordering is important here):
<P>
<PRE> $output = `cmd 2>&1 1>/dev/null`;
</PRE>
<P>
To exchange a command's
<FONT SIZE=-1>STDOUT</FONT> and
<FONT SIZE=-1>STDERR</FONT> in order to capture the
<FONT SIZE=-1>STDERR</FONT> but leave its
<FONT SIZE=-1>STDOUT</FONT> to come out the old
<FONT SIZE=-1>STDERR:</FONT>
<P>
<PRE> $output = `cmd 3>&1 1>&2 2>&3 3>&-`;
</PRE>
<P>
To read both a command's
<FONT SIZE=-1>STDOUT</FONT> and its
<FONT SIZE=-1>STDERR</FONT> separately, it's easiest and safest to redirect them separately to files, and then read from those files when the program is done:
<P>
<PRE> system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");
</PRE>
<P>
Using single-quote as a delimiter protects the command from Perl's
double-quote interpolation, passing it on to the shell instead:
<P>
<PRE> $perl_info = qx(ps $$); # that's Perl's $$
$shell_info = qx'ps $$'; # that's the new shell's $$
</PRE>
<P>
Note that how the string gets evaluated is entirely subject to the command
interpreter on your system. On most platforms, you will have to protect
shell metacharacters if you want them treated literally. This is in
practice difficult to do, as it's unclear how to escape which characters.
See [perlman:perlsec|the perlsec manpage] for a clean and safe example of a manual
<CODE>fork()</CODE> and
<CODE>exec()</CODE> to emulate backticks safely.
<P>
On some platforms (notably DOS-like ones), the shell may not be capable of
dealing with multiline commands, so putting newlines in the string may not
get you what you want. You may be able to evaluate multiple commands in a
single line by separating them with the command separator character, if
your shell supports that (e.g. <CODE>;</CODE> on many Unix shells; <CODE>&</CODE> on the Windows
<FONT SIZE=-1>NT</FONT> <CODE>cmd</CODE> shell).
<P>
Beware that some command shells may place restrictions on the length of the
command line. You must ensure your strings don't exceed this limit after
any necessary interpolations. See the platform-specific release notes for
more details about your particular environment.
<P>
Using this operator can lead to programs that are difficult to port,
because the shell commands called vary between systems, and may in fact not
be present at all. As one example, the <CODE>type</CODE> command under the
<FONT SIZE=-1>POSIX</FONT> shell is very different from the <CODE>type</CODE> command under
<FONT SIZE=-1>DOS.</FONT> That doesn't mean you should go out of your way
to avoid backticks when they're the right way to get something done. Perl
was made to be a glue language, and one of the things it glues together is
commands. Just understand what you're getting yourself into.
<P>
See <A HREF="#I_O_Operators">I/O Operators</A> for more discussion.
<P><DT><STRONG><A NAME="item_qw">qw/STRING/</A></STRONG><P>
<DD>
Returns a list of the words extracted out of
<FONT SIZE=-1>STRING,</FONT> using embedded whitespace as the word
delimiters. It is exactly equivalent to
<P>
<PRE> split(' ', q/STRING/);
</PRE>
<P>
This equivalency means that if used in scalar context, you'll get split's
(unfortunate) scalar context behavior, complete with mysterious warnings.
<P>
Some frequently seen examples:
<P>
<PRE> use POSIX qw( setlocale localeconv )
@EXPORT = qw( foo bar baz );
</PRE>
<P>
<FONT SIZE=-1>A</FONT> common mistake is to try to separate the words with
comma or to put comments into a multi-line [perlman:perlop]-string. For this reason the <CODE>-w</CODE>
switch produce warnings if the
<FONT SIZE=-1>STRING</FONT> contains the ``,'' or the ``#'' character.
<P><DT><STRONG><A NAME="item_s">s/PATTERN/REPLACEMENT/egimosx</A></STRONG><P>
<DD>
Searches a string for a pattern, and if found, replaces that pattern with
the replacement text and returns the number of substitutions made.
Otherwise it returns false (specifically, the empty string).
<P>
If no string is specified via the <CODE>=~</CODE> or <CODE>!~</CODE> operator, the <CODE>$_</CODE>
variable is searched and modified. (The string specified with <CODE>=~</CODE> must be scalar variable, an array element, a hash element, or an assignment
to one of those, i.e., an lvalue.)
<P>
If the delimiter chosen is single quote, no variable interpolation is done on either the
<FONT SIZE=-1>PATTERN</FONT> or the
<FONT SIZE=-1>REPLACEMENT.</FONT> Otherwise, if the
<FONT SIZE=-1>PATTERN</FONT> contains a $ that looks like a variable rather than an end-of-string test, the variable will be interpolated into the pattern at run-time. If you want the pattern compiled only once the first time the variable is interpolated, use the
<CODE>/o</CODE> option. If the pattern evaluates to the empty string, the last successfully
executed regular expression is used instead. See [perlman:perlre|the perlre manpage] for further explanation on these. See [perlman:perllocale|the perllocale manpage] for discussion of additional considerations that apply when <CODE>use locale</CODE> is in effect.
<P>
Options are:
<P>
<PRE> e Evaluate the right side as an expression.
g Replace globally, i.e., all occurrences.
i Do case-insensitive pattern matching.
m Treat string as multiple lines.
o Compile pattern only once.
s Treat string as single line.
x Use extended regular expressions.
</PRE>
<P>
Any non-alphanumeric, non-whitespace delimiter may replace the slashes. If
single quotes are used, no interpretation is done on the replacement string
(the <CODE>/e</CODE> modifier overrides this, however). Unlike Perl 4, Perl 5 treats backticks as normal delimiters; the replacement text is not evaluated as a command. If the
<FONT SIZE=-1>PATTERN</FONT> is delimited by bracketing quotes, the
<FONT SIZE=-1>REPLACEMENT</FONT> has its own pair of quotes, which may or may not be bracketing quotes, e.g.,
[perlman:perlop] or <CODE>s<foo>/bar/</CODE>.
<FONT SIZE=-1>A</FONT> <CODE>/e</CODE> will cause the replacement portion to be interpreted as a full-fledged Perl expression and
<CODE>eval()ed</CODE> right then and there. It is, however, syntax checked at compile-time.
<P>
Examples:
<P>
<PRE> s/\bgreen\b/mauve/g; # don't change wintergreen
</PRE>
<P>
<PRE> $path =~ s|/usr/bin|/usr/local/bin|;
</PRE>
<P>
<PRE> s/Login: $foo/Login: $bar/; # run-time pattern
</PRE>
<P>
<PRE> ($foo = $bar) =~ s/this/that/; # copy first, then change
</PRE>
<P>
<PRE> $count = ($paragraph =~ s/Mister\b/Mr./g); # get change-count
</PRE>
<P>
<PRE> $_ = 'abc123xyz';
s/\d+/$&*2/e; # yields 'abc246xyz'
s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz'
s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz'
</PRE>
<P>
<PRE> s/%(.)/$percent{$1}/g; # change percent escapes; no /e
s/%(.)/$percent{$1} || $&/ge; # expr now, so /e
s/^=(\w+)/&pod($1)/ge; # use function call
</PRE>
<P>
<PRE> # expand variables in $_, but dynamics only, using
# symbolic dereferencing
s/\$(\w+)/${$1}/g;
</PRE>
<P>
<PRE> # /e's can even nest; this will expand
# any embedded scalar variable (including lexicals) in $_
s/(\$\w+)/$1/eeg;
</PRE>
<P>
<PRE> # Delete (most) C comments.
$program =~ s {
/\* # Match the opening delimiter.
.*? # Match a minimal number of characters.
\*/ # Match the closing delimiter.
} []gsx;
</PRE>
<P>
<PRE> s/^\s*(.*?)\s*$/$1/; # trim white space in $_, expensively
</PRE>
<P>
<PRE> for ($variable) { # trim white space in $variable, cheap
s/^\s+//;
s/\s+$//;
}
</PRE>
<P>
<PRE> s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields
</PRE>
<P>
Note the use of $ instead of \ in the last example. Unlike
<STRONG>sed</STRONG>, we use the \<<EM>digit</EM>> form in only the left hand side. Anywhere else it's $<<EM>digit</EM>>.
<P>
Occasionally, you can't use just a <CODE>/g</CODE> to get all the changes to occur. Here are two common cases:
<P>
<PRE> # put commas in the right places in an integer
1 while s/(.*\d)(\d\d\d)/$1,$2/g; # perl4
1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g; # perl5
</PRE>
<P>
<PRE> # expand tabs to 8-column spacing
1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
</PRE>
<DT><STRONG><A NAME="item_tr">tr/SEARCHLIST/REPLACEMENTLIST/cds</A></STRONG><DD>
<DT><STRONG><A NAME="item_y">y/SEARCHLIST/REPLACEMENTLIST/cds</A></STRONG><P>
<DD>
Transliterates all occurrences of the characters found in the search list with the corresponding character in the replacement list. It returns the number of characters replaced or deleted. If no string is specified via the =~ or !~ operator, the <CODE>$_</CODE> string is transliterated. (The string specified with =~ must be a scalar variable, an array element, a hash element, or an assignment to one of those, i.e., an lvalue.)
<FONT SIZE=-1>A</FONT> character range may be specified with a hyphen, so
<CODE>tr/A-J/0-9/</CODE>
does the same replacement as <CODE>tr/ACEGIBDFHJ/0246813579/</CODE>. For <STRONG>sed</STRONG> devotees, [perlman:perlop] is provided as a synonym for [perlman:perlop]. If the
<FONT SIZE=-1>SEARCHLIST</FONT> is delimited by bracketing quotes, the
<FONT SIZE=-1>REPLACEMENTLIST</FONT> has its own pair of quotes, which may or may not be bracketing quotes, e.g.,
<CODE>tr[A-Z][a-z]</CODE> or <CODE>tr(+\-*/)/ABCD/</CODE>.
<P>
Options:
<P>
<PRE> c Complement the SEARCHLIST.
d Delete found but unreplaced characters.
s Squash duplicate replaced characters.
</PRE>
<P>
If the <CODE>/c</CODE> modifier is specified, the
<FONT SIZE=-1>SEARCHLIST</FONT> character set is complemented. If the <CODE>/d</CODE> modifier is specified, any characters specified by
<FONT SIZE=-1>SEARCHLIST</FONT> not found in
<FONT SIZE=-1>REPLACEMENTLIST</FONT> are deleted. (Note that this is slightly more flexible than the behavior of some
<STRONG>tr</STRONG>
programs, which delete anything they find in the
<FONT SIZE=-1>SEARCHLIST,</FONT> period.) If the [perlman:perlop] modifier is specified, sequences of characters that were transliterated to
the same character are squashed down to a single instance of the character.
<P>
If the <CODE>/d</CODE> modifier is used, the
<FONT SIZE=-1>REPLACEMENTLIST</FONT> is always interpreted exactly as specified. Otherwise, if the
<FONT SIZE=-1>REPLACEMENTLIST</FONT> is shorter than the
<FONT SIZE=-1>SEARCHLIST,</FONT> the final character is replicated till it is long enough. If the
<FONT SIZE=-1>REPLACEMENTLIST</FONT> is empty, the
<FONT SIZE=-1>SEARCHLIST</FONT> is replicated. This latter is useful for counting characters in a class or for squashing character sequences in a class.
<P>
Examples:
<P>
<PRE> $ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case
</PRE>
<P>
<PRE> $cnt = tr/*/*/; # count the stars in $_
</PRE>
<P>
<PRE> $cnt = $sky =~ tr/*/*/; # count the stars in $sky
</PRE>
<P>
<PRE> $cnt = tr/0-9//; # count the digits in $_
</PRE>
<P>
<PRE> tr/a-zA-Z//s; # bookkeeper -> bokeper
</PRE>
<P>
<PRE> ($HOST = $host) =~ tr/a-z/A-Z/;
</PRE>
<P>
<PRE> tr/a-zA-Z/ /cs; # change non-alphas to single space
</PRE>
<P>
<PRE> tr [\200-\377]
[\000-\177]; # delete 8th bit
</PRE>
<P>
If multiple transliterations are given for a character, only the first one
is used:
<P>
<PRE> tr/AAA/XYZ/
</PRE>
<P>
will transliterate any
<FONT SIZE=-1>A</FONT> to
<FONT SIZE=-1>X.</FONT>
<P>
Note that because the transliteration table is built at compile time, neither the
<FONT SIZE=-1>SEARCHLIST</FONT> nor the
<FONT SIZE=-1>REPLACEMENTLIST</FONT> are subjected to double quote interpolation. That means that if you want to use variables, you must use an
<CODE>eval():</CODE>
<P>
<PRE> eval "tr/$oldlist/$newlist/";
die $@ if $@;
</PRE>
<P>
<PRE> eval "tr/$oldlist/$newlist/, 1" or die $@;
</PRE>
</DL>
<P>
[perlman:perlop2|More...]<BR>
Return to the [Library]