home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlop.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  48.4 KB  |  1,226 lines

  1. NAME
  2.        perlop - Perl operators and precedence
  3.  
  4. SYNOPSIS
  5.        Perl operators have the following associativity and
  6.        precedence, listed from highest precedence to lowest.
  7.        Note that all operators borrowed from C keep the same
  8.        precedence relationship with each other, even where C's
  9.        precedence is slightly screwy.  (This makes learning Perl
  10.        easier for C folks.)  With very few exceptions, these all
  11.        operate on scalar values only, not array values.
  12.  
  13.            left        terms and list operators (leftward)
  14.            left        ->
  15.            nonassoc    ++ --
  16.            right       **
  17.            right       ! ~ \ and unary + and -
  18.            left        =~ !~
  19.            left        * / % x
  20.            left        + - .
  21.            left        << >>
  22.            nonassoc    named unary operators
  23.            nonassoc    < > <= >= lt gt le ge
  24.            nonassoc    == != <=> eq ne cmp
  25.            left        &
  26.            left        | ^
  27.            left        &&
  28.            left        ||
  29.            nonassoc    ..
  30.            right       ?:
  31.            right       = += -= *= etc.
  32.            left        , =>
  33.            nonassoc    list operators (rightward)
  34.            right       not
  35.            left        and
  36.            left        or xor
  37.  
  38.        In the following sections, these operators are covered in
  39.        precedence order.
  40.  
  41. DESCRIPTION
  42.        Terms and List Operators (Leftward)
  43.  
  44.        Any TERM is of highest precedence of Perl.  These includes
  45.        variables, quote and quotelike operators, any expression
  46.        in parentheses, and any function whose arguments are
  47.        parenthesized.  Actually, there aren't really functions in
  48.        this sense, just list operators and unary operators
  49.        behaving as functions because you put parentheses around
  50.        the arguments.  These are all documented in the perlfunc
  51.        manpage.
  52.  
  53.        If any list operator (print(), etc.) or any unary operator
  54.        (chdir(), etc.)  is followed by a left parenthesis as the
  55.        next token, the operator and arguments within parentheses
  56.        are taken to be of highest precedence, just like a normal
  57.        function call.
  58.  
  59.        In the absence of parentheses, the precedence of list
  60.        operators such as print, sort, or chmod is either very
  61.        high or very low depending on whether you look at the left
  62.        side of operator or the right side of it.  For example, in
  63.  
  64.            @ary = (1, 3, sort 4, 2);
  65.            print @ary;         # prints 1324
  66.  
  67.        the commas on the right of the sort are evaluated before
  68.        the sort, but the commas on the left are evaluated after.
  69.        In other words, list operators tend to gobble up all the
  70.        arguments that follow them, and then act like a simple
  71.        TERM with regard to the preceding expression.  Note that
  72.        you have to be careful with parens:
  73.  
  74.            # These evaluate exit before doing the print:
  75.            print($foo, exit);  # Obviously not what you want.
  76.            print $foo, exit;   # Nor is this.
  77.  
  78.            # These do the print before evaluating exit:
  79.            (print $foo), exit; # This is what you want.
  80.            print($foo), exit;  # Or this.
  81.            print ($foo), exit; # Or even this.
  82.  
  83.        Also note that
  84.  
  85.            print ($foo & 255) + 1, "\n";
  86.  
  87.        probably doesn't do what you expect at first glance.  See
  88.        the section on Named Unary Operators for more discussion
  89.        of this.
  90.  
  91.        Also parsed as terms are the do {} and eval {} constructs,
  92.        as well as subroutine and method calls, and the anonymous
  93.        constructors [] and {}.
  94.  
  95.        See also the section on Quote and Quotelike Operators
  96.        toward the end of this section, as well as the section on
  97.        I/O Operators.
  98.  
  99.        The Arrow Operator
  100.  
  101.        Just as in C and C++, "->" is an infix dereference
  102.        operator.  If the right side is either a [...] or {...}
  103.        subscript, then the left side must be either a hard or
  104.        symbolic reference to an array or hash (or a location
  105.        capable of holding a hard reference, if it's an lvalue
  106.        (assignable)).  See the perlref manpage.
  107.  
  108.        Otherwise, the right side is a method name or a simple
  109.        scalar variable containing the method name, and the left
  110.        side must either be an object (a blessed reference) or a
  111.        class name (that is, a package name).  See the perlobj
  112.        manpage.
  113.  
  114.        Autoincrement and Autodecrement
  115.  
  116.        "++" and "--" work as in C.  That is, if placed before a
  117.        variable, they increment or decrement the variable before
  118.        returning the value, and if placed after, increment or
  119.        decrement the variable after returning the value.
  120.  
  121.        The autoincrement operator has a little extra built-in
  122.        magic to it.  If you increment a variable that is numeric,
  123.        or that has ever been used in a numeric context, you get a
  124.        normal increment.  If, however, the variable has only been
  125.        used in string contexts since it was set, and has a value
  126.        that is not null and matches the pattern /^[a-zA-
  127.        Z]*[0-9]*$/, the increment is done as a string, preserving
  128.        each character within its range, with carry:
  129.  
  130.            print ++($foo = '99');      # prints '100'
  131.            print ++($foo = 'a0');      # prints 'a1'
  132.            print ++($foo = 'Az');      # prints 'Ba'
  133.            print ++($foo = 'zz');      # prints 'aaa'
  134.  
  135.        The autodecrement operator is not magical.
  136.  
  137.        Exponentiation
  138.  
  139.        Binary "**" is the exponentiation operator.  Note that it
  140.        binds even more tightly than unary minus, so -2**4 is
  141.        -(2**4), not (-2)**4. (This is implemented using C's
  142.        pow(3) function, which actually works on doubles
  143.        internally.)
  144.  
  145.        Symbolic Unary Operators
  146.  
  147.        Unary "!" performs logical negation, i.e. "not".  See also
  148.        not for a lower precedence version of this.
  149.  
  150.        Unary "-" performs arithmetic negation if the operand is
  151.        numeric.  If the operand is an identifier, a string
  152.        consisting of a minus sign concatenated with the
  153.        identifier is returned.  Otherwise, if the string starts
  154.        with a plus or minus, a string starting with the opposite
  155.        sign is returned.  One effect of these rules is that
  156.        -bareword is equivalent to "-bareword".
  157.  
  158.        Unary "~" performs bitwise negation, i.e. 1's complement.
  159.  
  160.        Unary "+" has no effect whatsoever, even on strings.  It
  161.        is useful syntactically for separating a function name
  162.        from a parenthesized expression that would otherwise be
  163.        interpreted as the complete list of function arguments.
  164.        (See examples above under the section on List Operators.)
  165.  
  166.        Unary "\" creates a reference to whatever follows it.  See
  167.        the perlref manpage.  Do not confuse this behavior with
  168.        the behavior of backslash within a string, although both
  169.        forms do convey the notion of protecting the next thing
  170.        from interpretation.
  171.  
  172.        Binding Operators
  173.  
  174.        Binary "=~" binds a scalar expression to a pattern match.
  175.        Certain operations search or modify the string $_ by
  176.        default.  This operator makes that kind of operation work
  177.        on some other string.  The right argument is a search
  178.        pattern, substitution, or translation.  The left argument
  179.        is what is supposed to be searched, substituted, or
  180.        translated instead of the default $_.  The return value
  181.        indicates the success of the operation.  (If the right
  182.        argument is an expression rather than a search pattern,
  183.        substitution, or translation, it is interpreted as a
  184.        search pattern at run time.  This is less efficient than
  185.        an explicit search, since the pattern must be compiled
  186.        every time the expression is evaluated--unless you've used
  187.        /o.)
  188.  
  189.        Binary "!~" is just like "=~" except the return value is
  190.        negated in the logical sense.
  191.  
  192.        Multiplicative Operators
  193.  
  194.        Binary "*" multiplies two numbers.
  195.  
  196.        Binary "/" divides two numbers.
  197.  
  198.        Binary "%" computes the modulus of the two numbers.
  199.  
  200.        Binary "x" is the repetition operator.  In a scalar
  201.        context, it returns a string consisting of the left
  202.        operand repeated the number of times specified by the
  203.        right operand.  In a list context, if the left operand is
  204.        a list in parens, it repeats the list.
  205.  
  206.            print '-' x 80;             # print row of dashes
  207.  
  208.            print "\t" x ($tab/8), ' ' x ($tab%8);      # tab over
  209.  
  210.            @ones = (1) x 80;           # a list of 80 1's
  211.            @ones = (5) x @ones;        # set all elements to 5
  212.  
  213.  
  214.  
  215.  
  216.  
  217.        Additive Operators
  218.  
  219.        Binary "+" returns the sum of two numbers.
  220.  
  221.        Binary "-" returns the difference of two numbers.
  222.  
  223.        Binary "." concatenates two strings.
  224.  
  225.        Shift Operators
  226.  
  227.        Binary "<<" returns the value of its left argument shifted
  228.        left by the number of bits specified by the right
  229.        argument.  Arguments should be integers.
  230.  
  231.        Binary ">>" returns the value of its left argument shifted
  232.        right by the number of bits specified by the right
  233.        argument.  Arguments should be integers.
  234.  
  235.        Named Unary Operators
  236.  
  237.        The various named unary operators are treated as functions
  238.        with one argument, with optional parentheses.  These
  239.        include the filetest operators, like -f, -M, etc.  See the
  240.        perlfunc manpage.
  241.  
  242.        If any list operator (print(), etc.) or any unary operator
  243.        (chdir(), etc.)  is followed by a left parenthesis as the
  244.        next token, the operator and arguments within parentheses
  245.        are taken to be of highest precedence, just like a normal
  246.        function call.  Examples:
  247.  
  248.            chdir $foo    || die;       # (chdir $foo) || die
  249.            chdir($foo)   || die;       # (chdir $foo) || die
  250.            chdir ($foo)  || die;       # (chdir $foo) || die
  251.            chdir +($foo) || die;       # (chdir $foo) || die
  252.  
  253.        but, because * is higher precedence than ||:
  254.  
  255.            chdir $foo * 20;    # chdir ($foo * 20)
  256.            chdir($foo) * 20;   # (chdir $foo) * 20
  257.            chdir ($foo) * 20;  # (chdir $foo) * 20
  258.            chdir +($foo) * 20; # chdir ($foo * 20)
  259.  
  260.            rand 10 * 20;       # rand (10 * 20)
  261.            rand(10) * 20;      # (rand 10) * 20
  262.            rand (10) * 20;     # (rand 10) * 20
  263.            rand +(10) * 20;    # rand (10 * 20)
  264.  
  265.        See also the section on List Operators.
  266.  
  267.        Relational Operators
  268.  
  269.        Binary "<" returns true if the left argument is
  270.        numerically less than the right argument.
  271.        Binary ">" returns true if the left argument is
  272.        numerically greater than the right argument.
  273.  
  274.        Binary "<=" returns true if the left argument is
  275.        numerically less than or equal to the right argument.
  276.  
  277.        Binary ">=" returns true if the left argument is
  278.        numerically greater than or equal to the right argument.
  279.  
  280.        Binary "lt" returns true if the left argument is
  281.        stringwise less than the right argument.
  282.  
  283.        Binary "gt" returns true if the left argument is
  284.        stringwise greater than the right argument.
  285.  
  286.        Binary "le" returns true if the left argument is
  287.        stringwise less than or equal to the right argument.
  288.  
  289.        Binary "ge" returns true if the left argument is
  290.        stringwise greater than or equal to the right argument.
  291.  
  292.        Equality Operators
  293.  
  294.        Binary "==" returns true if the left argument is
  295.        numerically equal to the right argument.
  296.  
  297.        Binary "!=" returns true if the left argument is
  298.        numerically not equal to the right argument.
  299.  
  300.        Binary "<=>" returns -1, 0, or 1 depending on whether the
  301.        left argument is numerically less than, equal to, or
  302.        greater than the right argument.
  303.  
  304.        Binary "eq" returns true if the left argument is
  305.        stringwise equal to the right argument.
  306.  
  307.        Binary "ne" returns true if the left argument is
  308.        stringwise not equal to the right argument.
  309.  
  310.        Binary "cmp" returns -1, 0, or 1 depending on whether the
  311.        left argument is stringwise less than, equal to, or
  312.        greater than the right argument.
  313.  
  314.        Bitwise And
  315.  
  316.        Binary "&" returns its operators ANDed together bit by
  317.        bit.
  318.  
  319.        Bitwise Or and Exclusive Or
  320.  
  321.        Binary "|" returns its operators ORed together bit by bit.
  322.  
  323.        Binary "^" returns its operators XORed together bit by
  324.        bit.
  325.        C-style Logical And
  326.  
  327.        Binary "&&" performs a short-circuit logical AND
  328.        operation.  That is, if the left operand is false, the
  329.        right operand is not even evaluated.  Scalar or list
  330.        context propagates down to the right operand if it is
  331.        evaluated.
  332.  
  333.        C-style Logical Or
  334.  
  335.        Binary "||" performs a short-circuit logical OR operation.
  336.        That is, if the left operand is true, the right operand is
  337.        not even evaluated.  Scalar or list context propagates
  338.        down to the right operand if it is evaluated.
  339.  
  340.        The || and && operators differ from C's in that, rather
  341.        than returning 0 or 1, they return the last value
  342.        evaluated.  Thus, a reasonably portable way to find out
  343.        the home directory (assuming it's not "0") might be:
  344.  
  345.            $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  346.                (getpwuid($<))[7] || die "You're homeless!\n";
  347.  
  348.        As more readable alternatives to && and ||, Perl provides
  349.        "and" and "or" operators (see below).  The short-circuit
  350.        behavior is identical.  The precedence of "and" and "or"
  351.        is much lower, however, so that you can safely use them
  352.        after a list operator without the need for parentheses:
  353.  
  354.            unlink "alpha", "beta", "gamma"
  355.                    or gripe(), next LINE;
  356.  
  357.        With the C-style operators that would have been written
  358.        like this:
  359.  
  360.            unlink("alpha", "beta", "gamma")
  361.                    || (gripe(), next LINE);
  362.  
  363.  
  364.        Range Operator
  365.  
  366.        Binary ".." is the range operator, which is really two
  367.        different operators depending on the context.  In a list
  368.        context, it returns an array of values counting (by ones)
  369.        from the left value to the right value.  This is useful
  370.        for writing for (1..10) loops and for doing slice
  371.        operations on arrays.  Be aware that under the current
  372.        implementation, a temporary array is created, so you'll
  373.        burn a lot of memory if you write something like this:
  374.  
  375.            for (1 .. 1_000_000) {
  376.                # code
  377.            }
  378.  
  379.        In a scalar context, ".." returns a boolean value.  The
  380.        operator is bistable, like a flip-flop, and emulates the
  381.        line-range (comma) operator of sed, awk, and various
  382.        editors.  Each ".." operator maintains its own boolean
  383.        state.  It is false as long as its left operand is false.
  384.        Once the left operand is true, the range operator stays
  385.        true until the right operand is true, AFTER which the
  386.        range operator becomes false again.  (It doesn't become
  387.        false till the next time the range operator is evaluated.
  388.        It can test the right operand and become false on the same
  389.        evaluation it became true (as in awk), but it still
  390.        returns true once.  If you don't want it to test the right
  391.        operand till the next evaluation (as in sed), use three
  392.        dots ("...") instead of two.)  The right operand is not
  393.        evaluated while the operator is in the "false" state, and
  394.        the left operand is not evaluated while the operator is in
  395.        the "true" state.  The precedence is a little lower than
  396.        || and &&.  The value returned is either the null string
  397.        for false, or a sequence number (beginning with 1) for
  398.        true.  The sequence number is reset for each range
  399.        encountered.  The final sequence number in a range has the
  400.        string "E0" appended to it, which doesn't affect its
  401.        numeric value, but gives you something to search for if
  402.        you want to exclude the endpoint.  You can exclude the
  403.        beginning point by waiting for the sequence number to be
  404.        greater than 1.  If either operand of scalar ".." is a
  405.        numeric literal, that operand is implicitly compared to
  406.        the $. variable, the current line number.  Examples:
  407.  
  408.        As a scalar operator:
  409.  
  410.            if (101 .. 200) { print; }  # print 2nd hundred lines
  411.            next line if (1 .. /^$/);   # skip header lines
  412.            s/^/> / if (/^$/ .. eof()); # quote body
  413.  
  414.        As a list operator:
  415.  
  416.            for (101 .. 200) { print; } # print $_ 100 times
  417.            @foo = @foo[$[ .. $#foo];   # an expensive no-op
  418.            @foo = @foo[$#foo-4 .. $#foo];      # slice last 5 items
  419.  
  420.        The range operator (in a list context) makes use of the
  421.        magical autoincrement algorithm if the operands are
  422.        strings.  You can say
  423.  
  424.            @alphabet = ('A' .. 'Z');
  425.  
  426.        to get all the letters of the alphabet, or
  427.  
  428.            $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  429.  
  430.        to get a hexadecimal digit, or
  431.  
  432.            @z2 = ('01' .. '31');  print $z2[$mday];
  433.        to get dates with leading zeros.  If the final value
  434.        specified is not in the sequence that the magical
  435.        increment would produce, the sequence goes until the next
  436.        value would be longer than the final value specified.
  437.  
  438.        Conditional Operator
  439.  
  440.        Ternary "?:" is the conditional operator, just as in C.
  441.        It works much like an if-then-else.  If the argument
  442.        before the ? is true, the argument before the : is
  443.        returned, otherwise the argument after the : is returned.
  444.        For example:
  445.  
  446.            printf "I have %d dog%s.\n", $n,
  447.                    ($n == 1) ? '' : "s";
  448.  
  449.        Scalar or list context propagates downward into the 2nd or
  450.        3rd argument, whichever is selected.
  451.  
  452.            $a = $ok ? $b : $c;  # get a scalar
  453.            @a = $ok ? @b : @c;  # get an array
  454.            $a = $ok ? @b : @c;  # oops, that's just a count!
  455.  
  456.        The operator may be assigned to if both the 2nd and 3rd
  457.        arguments are legal lvalues (meaning that you can assign
  458.        to them):
  459.  
  460.            ($a_or_b ? $a : $b) = $c;
  461.  
  462.        This is not necessarily guaranteed to contribute to the
  463.        readability of your program.
  464.  
  465.        Assignment Operators
  466.  
  467.        "=" is the ordinary assignment operator.
  468.  
  469.        Assignment operators work as in C.  That is,
  470.  
  471.            $a += 2;
  472.  
  473.        is equivalent to
  474.  
  475.            $a = $a + 2;
  476.  
  477.        although without duplicating any side effects that
  478.        dereferencing the lvalue might trigger, such as from
  479.        tie().  Other assignment operators work similarly.  The
  480.        following are recognized:
  481.  
  482.            **=    +=    *=    &=    <<=    &&=
  483.                   -=    /=    |=    >>=    ||=
  484.                   .=    %=    ^=
  485.                         x=
  486.  
  487.        Note that while these are grouped by family, they all have
  488.        the precedence of assignment.
  489.  
  490.        Unlike in C, the assignment operator produces a valid
  491.        lvalue.  Modifying an assignment is equivalent to doing
  492.        the assignment and then modifying the variable that was
  493.        assigned to.  This is useful for modifying a copy of
  494.        something, like this:
  495.  
  496.            ($tmp = $global) =~ tr [A-Z] [a-z];
  497.  
  498.        Likewise,
  499.  
  500.            ($a += 2) *= 3;
  501.  
  502.        is equivalent to
  503.  
  504.            $a += 2;
  505.            $a *= 3;
  506.  
  507.  
  508.        Comma Operator
  509.  
  510.        Binary "," is the comma operator.  In a scalar context it
  511.        evaluates its left argument, throws that value away, then
  512.        evaluates its right argument and returns that value.  This
  513.        is just like C's comma operator.
  514.  
  515.        In a list context, it's just the list argument separator,
  516.        and inserts both its arguments into the list.
  517.  
  518.        The => digraph is mostly just a synonym for the comma
  519.        operator.  It's useful for documenting arguments that come
  520.        in pairs.  As of release 5.001, it also forces any word to
  521.        the left of it to be interpreted as a string.
  522.  
  523.        List Operators (Rightward)
  524.  
  525.        On the right side of a list operator, it has very low
  526.        precedence, such that it controls all comma-separated
  527.        expressions found there.  The only operators with lower
  528.        precedence are the logical operators "and", "or", and
  529.        "not", which may be used to evaluate calls to list
  530.        operators without the need for extra parentheses:
  531.  
  532.            open HANDLE, "filename"
  533.                or die "Can't open: $!\n";
  534.  
  535.        See also discussion of list operators in the section on
  536.        List Operators (Leftward).
  537.  
  538.  
  539.  
  540.  
  541.        Logical Not
  542.  
  543.        Unary "not" returns the logical negation of the expression
  544.        to its right.  It's the equivalent of "!" except for the
  545.        very low precedence.
  546.  
  547.        Logical And
  548.  
  549.        Binary "and" returns the logical conjunction of the two
  550.        surrounding expressions.  It's equivalent to && except for
  551.        the very low precedence.  This means that it short-
  552.        circuits: i.e. the right expression is evaluated only if
  553.        the left expression is true.
  554.  
  555.        Logical or and Exclusive Or
  556.  
  557.        Binary "or" returns the logical disjunction of the two
  558.        surrounding expressions.  It's equivalent to || except for
  559.        the very low precedence.  This means that it short-
  560.        circuits: i.e. the right expression is evaluated only if
  561.        the left expression is false.
  562.  
  563.        Binary "xor" returns the exclusive-OR of the two
  564.        surrounding expressions.  It cannot short circuit, of
  565.        course.
  566.  
  567.        C Operators Missing From Perl
  568.  
  569.        Here is what C has that Perl doesn't:
  570.  
  571.        unary & Address-of operator.  (But see the "\" operator
  572.                for taking a reference.)
  573.  
  574.        unary * Dereference-address operator. (Perl's prefix
  575.                dereferencing operators are typed: $, @, %, and
  576.                &.)
  577.  
  578.        (TYPE)  Type casting operator.
  579.  
  580.        Quote and Quotelike Operators
  581.  
  582.        While we usually think of quotes as literal values, in
  583.        Perl they function as operators, providing various kinds
  584.        of interpolating and pattern matching capabilities.  Perl
  585.        provides customary quote characters for these behaviors,
  586.        but also provides a way for you to choose your quote
  587.        character for any of them.  In the following table, a {}
  588.        represents any pair of delimiters you choose.  Non-
  589.        bracketing delimiters use the same character fore and aft,
  590.        but the 4 sorts of brackets (round, angle, square, curly)
  591.        will all nest.
  592.  
  593.  
  594.  
  595.            Customary  Generic     Meaning    Interpolates
  596.                ''       q{}       Literal         no
  597.                ""      qq{}       Literal         yes
  598.                ``      qx{}       Command         yes
  599.                        qw{}      Word list        no
  600.                //       m{}    Pattern match      yes
  601.                         s{}{}   Substitution      yes
  602.                        tr{}{}   Translation       no
  603.  
  604.        For constructs that do interpolation, variables beginning
  605.        with "$" or "@" are interpolated, as are the following
  606.        sequences:
  607.  
  608.            \t          tab
  609.            \n          newline
  610.            \r          return
  611.            \f          form feed
  612.            \b          backspace
  613.            \a          alarm (bell)
  614.            \e          escape
  615.            \033        octal char
  616.            \x1b        hex char
  617.            \c[         control char
  618.            \l          lowercase next char
  619.            \u          uppercase next char
  620.            \L          lowercase till \E
  621.            \U          uppercase till \E
  622.            \E          end case modification
  623.            \Q          quote regexp metacharacters till \E
  624.  
  625.        Patterns are subject to an additional level of
  626.        interpretation as a regular expression.  This is done as a
  627.        second pass, after variables are interpolated, so that
  628.        regular expressions may be incorporated into the pattern
  629.        from the variables.  If this is not what you want, use \Q
  630.        to interpolate a variable literally.
  631.  
  632.        Apart from the above, there are no multiple levels of
  633.        interpolation.  In particular, contrary to the
  634.        expectations of shell programmers, backquotes do NOT
  635.        interpolate within double quotes, nor do single quotes
  636.        impede evaluation of variables when used within double
  637.        quotes.
  638.  
  639.        Regexp Quotelike Operators
  640.  
  641.        Here are the quotelike operators that apply to pattern
  642.        matching and related activities.
  643.  
  644.        ?PATTERN?
  645.                This is just like the /pattern/ search, except
  646.                that it matches only once between calls to the
  647.                reset() operator.  This is a useful optimization
  648.                when you only want to see the first occurrence of
  649.                something in each file of a set of files, for
  650.                instance.  Only ??  patterns local to the current
  651.                package are reset.
  652.  
  653.                This usage is vaguely deprecated, and may be
  654.                removed in some future version of Perl.
  655.  
  656.        m/PATTERN/gimosx
  657.  
  658.        /PATTERN/gimosx
  659.                Searches a string for a pattern match, and in a
  660.                scalar context returns true (1) or false ('').  If
  661.                no string is specified via the =~ or !~ operator,
  662.                the $_ string is searched.  (The string specified
  663.                with =~ need not be an lvalue--it may be the
  664.                result of an expression evaluation, but remember
  665.                the =~ binds rather tightly.)  See also the perlre
  666.                manpage.
  667.  
  668.                Options are:
  669.  
  670.                    g   Match globally, i.e. find all occurrences.
  671.                    i   Do case-insensitive pattern matching.
  672.                    m   Treat string as multiple lines.
  673.                    o   Only compile pattern once.
  674.                    s   Treat string as single line.
  675.                    x   Use extended regular expressions.
  676.  
  677.                If "/" is the delimiter then the initial m is
  678.                optional.  With the m you can use any pair of non-
  679.                alphanumeric, non-whitespace characters as
  680.                delimiters.  This is particularly useful for
  681.                matching Unix path names that contain "/", to
  682.                avoid LTS (leaning toothpick syndrome).
  683.  
  684.                PATTERN may contain variables, which will be
  685.                interpolated (and the pattern recompiled) every
  686.                time the pattern search is evaluated.  (Note that
  687.                $) and $| might not be interpolated because they
  688.                look like end-of-string tests.)  If you want such
  689.                a pattern to be compiled only once, add a /o after
  690.                the trailing delimiter.  This avoids expensive
  691.                run-time recompilations, and is useful when the
  692.                value you are interpolating won't change over the
  693.                life of the script.  However, mentioning /o
  694.                constitutes a promise that you won't change the
  695.                variables in the pattern.  If you change them,
  696.                Perl won't even notice.
  697.  
  698.                If the PATTERN evaluates to a null string, the
  699.                last successfully executed regular expression is
  700.                used instead.
  701.  
  702.                If used in a context that requires a list value, a
  703.                pattern match returns a list consisting of the
  704.                subexpressions matched by the parentheses in the
  705.                pattern, i.e. ($1, $2, $3...).  (Note that here $1
  706.                etc. are also set, and that this differs from Perl
  707.                4's behavior.)  If the match fails, a null array
  708.                is returned.  If the match succeeds, but there
  709.                were no parentheses, a list value of (1) is
  710.                returned.
  711.  
  712.                Examples:
  713.  
  714.                    open(TTY, '/dev/tty');
  715.                    <TTY> =~ /^y/i && foo();    # do foo if desired
  716.  
  717.                    if (/Version: *([0-9.]*)/) { $version = $1; }
  718.  
  719.                    next if m#^/usr/spool/uucp#;
  720.  
  721.                    # poor man's grep
  722.                    $arg = shift;
  723.                    while (<>) {
  724.                        print if /$arg/o;       # compile only once
  725.                    }
  726.  
  727.                    if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  728.  
  729.                This last example splits $foo into the first two
  730.                words and the remainder of the line, and assigns
  731.                those three fields to $F1, $F2 and $Etc.  The
  732.                conditional is true if any variables were
  733.                assigned, i.e. if the pattern matched.
  734.  
  735.                The /g modifier specifies global pattern
  736.                matching--that is, matching as many times as
  737.                possible within the string.  How it behaves
  738.                depends on the context.  In a list context, it
  739.                returns a list of all the substrings matched by
  740.                all the parentheses in the regular expression.  If
  741.                there are no parentheses, it returns a list of all
  742.                the matched strings, as if there were parentheses
  743.                around the whole pattern.
  744.  
  745.                In a scalar context, m//g iterates through the
  746.                string, returning TRUE each time it matches, and
  747.                FALSE when it eventually runs out of matches.  (In
  748.                other words, it remembers where it left off last
  749.                time and restarts the search at that point.  You
  750.                can actually find the current match position of a
  751.                string using the pos() function--see the perlfunc
  752.                manpage.)  If you modify the string in any way,
  753.                the match position is reset to the beginning.
  754.                Examples:
  755.  
  756.  
  757.                    # list context
  758.                    ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
  759.  
  760.                    # scalar context
  761.                    $/ = ""; $* = 1;  # $* deprecated in Perl 5
  762.                    while ($paragraph = <>) {
  763.                        while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  764.                            $sentences++;
  765.                        }
  766.                    }
  767.                    print "$sentences\n";
  768.  
  769.  
  770.        q/STRING/
  771.  
  772.        'STRING'
  773.                A single-quoted, literal string.  Backslashes are
  774.                ignored, unless followed by the delimiter or
  775.                another backslash, in which case the delimiter or
  776.                backslash is interpolated.
  777.  
  778.                    $foo = q!I said, "You said, 'She said it.'"!;
  779.                    $bar = q('This is it.');
  780.  
  781.  
  782.        qq/STRING/
  783.  
  784.        "STRING"
  785.                A double-quoted, interpolated string.
  786.  
  787.                    $_ .= qq
  788.                     (*** The previous line contains the naughty word "$1".\n)
  789.                                if /(tcl|rexx|python)/;      # :-)
  790.  
  791.  
  792.        qx/STRING/
  793.  
  794.        `STRING`
  795.                A string which is interpolated and then executed
  796.                as a system command.  The collected standard
  797.                output of the command is returned.  In scalar
  798.                context, it comes back as a single (potentially
  799.                multi-line) string.  In list context, returns a
  800.                list of lines (however you've defined lines with
  801.                $/ or $INPUT_RECORD_SEPARATOR).
  802.  
  803.                    $today = qx{ date };
  804.  
  805.                See the section on I/O Operators for more
  806.                discussion.
  807.  
  808.        qw/STRING/
  809.                Returns a list of the words extracted out of
  810.                STRING, using embedded whitespace as the word
  811.                delimiters.  It is exactly equivalent to
  812.  
  813.                    split(' ', q/STRING/);
  814.  
  815.                Some frequently seen examples:
  816.  
  817.                    use POSIX qw( setlocale localeconv )
  818.                    @EXPORT = qw( foo bar baz );
  819.  
  820.  
  821.        s/PATTERN/REPLACEMENT/egimosx
  822.                Searches a string for a pattern, and if found,
  823.                replaces that pattern with the replacement text
  824.                and returns the number of substitutions made.
  825.                Otherwise it returns false (0).
  826.  
  827.                If no string is specified via the =~ or !~
  828.                operator, the $_ variable is searched and
  829.                modified.  (The string specified with =~ must be a
  830.                scalar variable, an array element, a hash element,
  831.                or an assignment to one of those, i.e. an lvalue.)
  832.  
  833.                If the delimiter chosen is single quote, no
  834.                variable interpolation is done on either the
  835.                PATTERN or the REPLACEMENT.  Otherwise, if the
  836.                PATTERN contains a $ that looks like a variable
  837.                rather than an end-of-string test, the variable
  838.                will be interpolated into the pattern at run-time.
  839.                If you only want the pattern compiled once the
  840.                first time the variable is interpolated, use the
  841.                /o option.  If the pattern evaluates to a null
  842.                string, the last successfully executed regular
  843.                expression is used instead.  See the perlre
  844.                manpage for further explanation on these.
  845.  
  846.                Options are:
  847.  
  848.                    e   Evaluate the right side as an expression.
  849.                    g   Replace globally, i.e. all occurrences.
  850.                    i   Do case-insensitive pattern matching.
  851.                    m   Treat string as multiple lines.
  852.                    o   Only compile pattern once.
  853.                    s   Treat string as single line.
  854.                    x   Use extended regular expressions.
  855.  
  856.                Any non-alphanumeric, non-whitespace delimiter may
  857.                replace the slashes.  If single quotes are used,
  858.                no interpretation is done on the replacement
  859.                string (the /e modifier overrides this, however).
  860.                If backquotes are used, the replacement string is
  861.                a command to execute whose output will be used as
  862.                the actual replacement text.  If the PATTERN is
  863.                delimited by bracketing quotes, the REPLACEMENT
  864.                has its own pair of quotes, which may or may not
  865.                be bracketing quotes, e.g.  s(foo)(bar) or
  866.                s<foo>/bar/.  A /e will cause the replacement
  867.                portion to be interpreter as a full-fledged Perl
  868.                expression and eval()ed right then and there.  It
  869.                is, however, syntax checked at compile-time.
  870.  
  871.                Examples:
  872.  
  873.                    s/\bgreen\b/mauve/g;                # don't change wintergreen
  874.  
  875.                    $path =~ s|/usr/bin|/usr/local/bin|;
  876.  
  877.                    s/Login: $foo/Login: $bar/; # run-time pattern
  878.  
  879.                    ($foo = $bar) =~ s/this/that/;
  880.  
  881.                    $count = ($paragraph =~ s/Mister\b/Mr./g);
  882.  
  883.                    $_ = 'abc123xyz';
  884.                    s/\d+/$&*2/e;               # yields 'abc246xyz'
  885.                    s/\d+/sprintf("%5d",$&)/e;  # yields 'abc  246xyz'
  886.                    s/\w/$& x 2/eg;             # yields 'aabbcc  224466xxyyzz'
  887.  
  888.                    s/%(.)/$percent{$1}/g;      # change percent escapes; no /e
  889.                    s/%(.)/$percent{$1} || $&/ge;       # expr now, so /e
  890.                    s/^=(\w+)/&pod($1)/ge;      # use function call
  891.  
  892.                    # /e's can even nest;  this will expand
  893.                    # simple embedded variables in $_
  894.                    s/(\$\w+)/$1/eeg;
  895.  
  896.                    # Delete C comments.
  897.                    $program =~ s {
  898.                        /\*     # Match the opening delimiter.
  899.                        .*?     # Match a minimal number of characters.
  900.                        \*/     # Match the closing delimiter.
  901.                    } []gsx;
  902.  
  903.                    s/^\s*(.*?)\s*$/$1/;        # trim white space
  904.  
  905.                    s/([^ ]*) *([^ ]*)/$2 $1/;  # reverse 1st two fields
  906.  
  907.                Note the use of $ instead of \ in the last
  908.                example.  Unlike sed, we only use the \<digit>
  909.                form in the left hand side.  Anywhere else it's
  910.                $<digit>.
  911.  
  912.                Occasionally, you can't just use a /g to get all
  913.                the changes to occur.  Here are two common cases:
  914.  
  915.                    # put commas in the right places in an integer
  916.                    1 while s/(.*\d)(\d\d\d)/$1,$2/g;      # perl4
  917.                    1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;  # perl5
  918.  
  919.                    # expand tabs to 8-column spacing
  920.                    1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
  921.  
  922.  
  923.        tr/SEARCHLIST/REPLACEMENTLIST/cds
  924.  
  925.        y/SEARCHLIST/REPLACEMENTLIST/cds
  926.                Translates all occurrences of the characters found
  927.                in the search list with the corresponding
  928.                character in the replacement list.  It returns the
  929.                number of characters replaced or deleted.  If no
  930.                string is specified via the =~ or !~ operator, the
  931.                $_ string is translated.  (The string specified
  932.                with =~ must be a scalar variable, an array
  933.                element, or an assignment to one of those, i.e. an
  934.                lvalue.)  For sed devotees, y is provided as a
  935.                synonym for tr.  If the SEARCHLIST is delimited by
  936.                bracketing quotes, the REPLACEMENTLIST has its own
  937.                pair of quotes, which may or may not be bracketing
  938.                quotes, e.g. tr[A-Z][a-z] or tr(+-*/)/ABCD/.
  939.  
  940.                Options:
  941.  
  942.                    c   Complement the SEARCHLIST.
  943.                    d   Delete found but unreplaced characters.
  944.                    s   Squash duplicate replaced characters.
  945.  
  946.                If the /c modifier is specified, the SEARCHLIST
  947.                character set is complemented.  If the /d modifier
  948.                is specified, any characters specified by
  949.                SEARCHLIST not found in REPLACEMENTLIST are
  950.                deleted.  (Note that this is slightly more
  951.                flexible than the behavior of some tr programs,
  952.                which delete anything they find in the SEARCHLIST,
  953.                period.)  If the /s modifier is specified,
  954.                sequences of characters that were translated to
  955.                the same character are squashed down to a single
  956.                instance of the character.
  957.  
  958.                If the /d modifier is used, the REPLACEMENTLIST is
  959.                always interpreted exactly as specified.
  960.                Otherwise, if the REPLACEMENTLIST is shorter than
  961.                the SEARCHLIST, the final character is replicated
  962.                till it is long enough.  If the REPLACEMENTLIST is
  963.                null, the SEARCHLIST is replicated.  This latter
  964.                is useful for counting characters in a class or
  965.                for squashing character sequences in a class.
  966.  
  967.                Examples:
  968.  
  969.                    $ARGV[1] =~ tr/A-Z/a-z/;    # canonicalize to lower case
  970.  
  971.                    $cnt = tr/*/*/;             # count the stars in $_
  972.  
  973.                    $cnt = $sky =~ tr/*/*/;     # count the stars in $sky
  974.  
  975.                    $cnt = tr/0-9//;            # count the digits in $_
  976.  
  977.                    tr/a-zA-Z//s;               # bookkeeper -> bokeper
  978.  
  979.                    ($HOST = $host) =~ tr/a-z/A-Z/;
  980.  
  981.                    tr/a-zA-Z/ /cs;             # change non-alphas to single space
  982.  
  983.                    tr [\200-\377]
  984.                       [\000-\177];             # delete 8th bit
  985.  
  986.                If multiple translations are given for a
  987.                character, only the first one is used:
  988.  
  989.                    tr/AAA/XYZ/
  990.  
  991.                will translate any A to X.
  992.  
  993.                Note that because the translation table is built
  994.                at compile time, neither the SEARCHLIST nor the
  995.                REPLACEMENTLIST are subjected to double quote
  996.                interpolation.  That means that if you want to use
  997.                variables, you must use an eval():
  998.  
  999.                    eval "tr/$oldlist/$newlist/";
  1000.                    die $@ if $@;
  1001.  
  1002.                    eval "tr/$oldlist/$newlist/, 1" or die $@;
  1003.  
  1004.  
  1005.        I/O Operators
  1006.  
  1007.        There are several I/O operators you should know about.  A
  1008.        string is enclosed by backticks (grave accents) first
  1009.        undergoes variable substitution just like a double quoted
  1010.        string.  It is then interpreted as a command, and the
  1011.        output of that command is the value of the pseudo-literal,
  1012.        like in a shell.  In a scalar context, a single string
  1013.        consisting of all the output is returned.  In a list
  1014.        context, a list of values is returned, one for each line
  1015.        of output.  (You can set $/ to use a different line
  1016.        terminator.)  The command is executed each time the
  1017.        pseudo-literal is evaluated.  The status value of the
  1018.        command is returned in $? (see the perlvar manpage for the
  1019.        interpretation of $?).  Unlike in csh, no translation is
  1020.        done on the return data--newlines remain newlines.  Unlike
  1021.        in any of the shells, single quotes do not hide variable
  1022.        names in the command from interpretation.  To pass a $
  1023.        through to the shell you need to hide it with a backslash.
  1024.        The generalized form of backticks is qx//.  (Because
  1025.        backticks always undergo shell expansion as well, see the
  1026.        perlsec manpage for security concerns.)
  1027.        Evaluating a filehandle in angle brackets yields the next
  1028.        line from that file (newline included, so it's never false
  1029.        until end of file, at which time an undefined value is
  1030.        returned).  Ordinarily you must assign that value to a
  1031.        variable, but there is one situation where an automatic
  1032.        assignment happens.  If and ONLY if the input symbol is
  1033.        the only thing inside the conditional of a while loop, the
  1034.        value is automatically assigned to the variable $_.  The
  1035.        assigned value is then tested to see if it is defined.
  1036.        (This may seem like an odd thing to you, but you'll use
  1037.        the construct in almost every Perl script you write.)
  1038.        Anyway, the following lines are equivalent to each other:
  1039.  
  1040.            while (defined($_ = <STDIN>)) { print; }
  1041.            while (<STDIN>) { print; }
  1042.            for (;<STDIN>;) { print; }
  1043.            print while defined($_ = <STDIN>);
  1044.            print while <STDIN>;
  1045.  
  1046.        The filehandles STDIN, STDOUT and STDERR are predefined.
  1047.        (The filehandles stdin, stdout and stderr will also work
  1048.        except in packages, where they would be interpreted as
  1049.        local identifiers rather than global.)  Additional
  1050.        filehandles may be created with the open() function.  See
  1051.        the open() entry in the perlfunc manpage for details on
  1052.        this.
  1053.  
  1054.        If a <FILEHANDLE> is used in a context that is looking for
  1055.        a list, a list consisting of all the input lines is
  1056.        returned, one line per list element.  It's easy to make a
  1057.        LARGE data space this way, so use with care.
  1058.  
  1059.        The null filehandle <> is special and can be used to
  1060.        emulate the behavior of sed and awk.  Input from <> comes
  1061.        either from standard input, or from each file listed on
  1062.        the command line.  Here's how it works: the first time <>
  1063.        is evaluated, the @ARGV array is checked, and if it is
  1064.        null, $ARGV[0] is set to "-", which when opened gives you
  1065.        standard input.  The @ARGV array is then processed as a
  1066.        list of filenames.  The loop
  1067.  
  1068.            while (<>) {
  1069.                ...                     # code for each line
  1070.            }
  1071.  
  1072.        is equivalent to the following Perl-like pseudo code:
  1073.  
  1074.            unshift(@ARGV, '-') if $#ARGV < $[;
  1075.            while ($ARGV = shift) {
  1076.                open(ARGV, $ARGV);
  1077.                while (<ARGV>) {
  1078.                    ...         # code for each line
  1079.                }
  1080.            }
  1081.        except that it isn't so cumbersome to say, and will
  1082.        actually work.  It really does shift array @ARGV and put
  1083.        the current filename into variable $ARGV.  It also uses
  1084.        filehandle ARGV internally--<> is just a synonym for
  1085.        <ARGV>, which is magical.  (The pseudo code above doesn't
  1086.        work because it treats <ARGV> as non-magical.)
  1087.  
  1088.        You can modify @ARGV before the first <> as long as the
  1089.        array ends up containing the list of filenames you really
  1090.        want.  Line numbers ($.)  continue as if the input were
  1091.        one big happy file.  (But see example under eof() for how
  1092.        to reset line numbers on each file.)
  1093.  
  1094.        If you want to set @ARGV to your own list of files, go
  1095.        right ahead.  If you want to pass switches into your
  1096.        script, you can use one of the Getopts modules or put a
  1097.        loop on the front like this:
  1098.  
  1099.            while ($_ = $ARGV[0], /^-/) {
  1100.                shift;
  1101.                last if /^--$/;
  1102.                if (/^-D(.*)/) { $debug = $1 }
  1103.                if (/^-v/)     { $verbose++  }
  1104.                ...             # other switches
  1105.            }
  1106.            while (<>) {
  1107.                ...             # code for each line
  1108.            }
  1109.  
  1110.        The <> symbol will return FALSE only once.  If you call it
  1111.        again after this it will assume you are processing another
  1112.        @ARGV list, and if you haven't set @ARGV, will input from
  1113.        STDIN.
  1114.  
  1115.        If the string inside the angle brackets is a reference to
  1116.        a scalar variable (e.g. <$foo>), then that variable
  1117.        contains the name of the filehandle to input from, or a
  1118.        reference to the same.  For example:
  1119.  
  1120.            $fh = \*STDIN;
  1121.            $line = <$fh>;
  1122.  
  1123.        If the string inside angle brackets is not a filehandle or
  1124.        a scalar variable containing a filehandle name or
  1125.        reference, then it is interpreted as a filename pattern to
  1126.        be globbed, and either a list of filenames or the next
  1127.        filename in the list is returned, depending on context.
  1128.        One level of $ interpretation is done first, but you can't
  1129.        say <$foo> because that's an indirect filehandle as
  1130.        explained in the previous paragraph.  In older version of
  1131.        Perl, programmers would insert curly brackets to force
  1132.        interpretation as a filename glob: <${foo}>.  These days,
  1133.        it's considered cleaner to call the internal function
  1134.        directly as glob($foo), which is probably the right way to
  1135.        have done it in the first place.)  Example:
  1136.  
  1137.            while (<*.c>) {
  1138.                chmod 0644, $_;
  1139.            }
  1140.  
  1141.        is equivalent to
  1142.  
  1143.            open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  1144.            while (<FOO>) {
  1145.                chop;
  1146.                chmod 0644, $_;
  1147.            }
  1148.  
  1149.        In fact, it's currently implemented that way.  (Which
  1150.        means it will not work on filenames with spaces in them
  1151.        unless you have csh(1) on your machine.)  Of course, the
  1152.        shortest way to do the above is:
  1153.  
  1154.            chmod 0644, <*.c>;
  1155.  
  1156.        Because globbing invokes a shell, it's often faster to
  1157.        call readdir() yourself and just do your own grep() on the
  1158.        filenames.  Furthermore, due to its current implementation
  1159.        of using a shell, the glob() routine may get "Arg list too
  1160.        long" errors (unless you've installed tcsh(1L) as
  1161.        /bin/csh).
  1162.  
  1163.        A glob only evaluates its (embedded) argument when it is
  1164.        starting a new list.  All values must be read before it
  1165.        will start over.  In a list context this isn't important,
  1166.        because you automatically get them all anyway.  In a
  1167.        scalar context, however, the operator returns the next
  1168.        value each time it is called, or a FALSE value if you've
  1169.        just run out.  Again, FALSE is returned only once.  So if
  1170.        you're expecting a single value from a glob, it is much
  1171.        better to say
  1172.  
  1173.            ($file) = <blurch*>;
  1174.  
  1175.        than
  1176.  
  1177.            $file = <blurch*>;
  1178.  
  1179.        because the latter will alternate between returning a
  1180.        filename and returning FALSE.
  1181.  
  1182.        It you're trying to do variable interpolation, it's
  1183.        definitely better to use the glob() function, because the
  1184.        older notation can cause people to become confused with
  1185.        the indirect filehandle notatin.
  1186.  
  1187.            @files = glob("$dir/*.[ch]");
  1188.            @files = glob($files[$i]);
  1189.        Constant Folding
  1190.  
  1191.        Like C, Perl does a certain amount of expression
  1192.        evaluation at compile time, whenever it determines that
  1193.        all of the arguments to an operator are static and have no
  1194.        side effects.  In particular, string concatenation happens
  1195.        at compile time between literals that don't do variable
  1196.        substitution.  Backslash interpretation also happens at
  1197.        compile time.  You can say
  1198.  
  1199.            'Now is the time for all' . "\n" .
  1200.                'good men to come to.'
  1201.  
  1202.        and this all reduces to one string internally.  Likewise,
  1203.        if you say
  1204.  
  1205.            foreach $file (@filenames) {
  1206.                if (-s $file > 5 + 100 * 2**16) { ... }
  1207.            }
  1208.  
  1209.        the compiler will pre-compute the number that expression
  1210.        represents so that the interpreter won't have to.
  1211.  
  1212.        Integer arithmetic
  1213.  
  1214.        By default Perl assumes that it must do most of its
  1215.        arithmetic in floating point.  But by saying
  1216.  
  1217.            use integer;
  1218.  
  1219.        you may tell the compiler that it's okay to use integer
  1220.        operations from here to the end of the enclosing BLOCK.
  1221.        An inner BLOCK may countermand this by saying
  1222.  
  1223.            no integer;
  1224.  
  1225.        which lasts until the end of that BLOCK.
  1226.