++ed by:

151 PAUSE users
128 non-PAUSE users.

Gurusamy Sarathy


perlop - Perl operators and precedence


Perl operators have the following associativity and precedence, listed from highest precedence to lowest. Note that all operators borrowed from C keep the same precedence relationship with each other, even where C's precedence is slightly screwy. (This makes learning Perl easier for C folks.) With very few exceptions, these all operate on scalar values only, not array values.

    left        terms and list operators (leftward)
    left        ->
    nonassoc    ++ --
    right       **
    right       ! ~ \ and unary + and -
    left        =~ !~
    left        * / % x
    left        + - .
    left        << >>
    nonassoc    named unary operators
    nonassoc    < > <= >= lt gt le ge
    nonassoc    == != <=> eq ne cmp
    left        &
    left        | ^
    left        &&
    left        ||
    nonassoc    ..  ...
    right       ?:
    right       = += -= *= etc.
    left        , =>
    nonassoc    list operators (rightward)
    right       not
    left        and
    left        or xor


Many operators can be overloaded for objects. See overload.


Terms and List Operators (Leftward)

A TERM 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 perlfunc.



    print @ary;         # prints 1324

the commas on the right of the sort are evaluated before the sort, but the commas on the left are evaluated after. In other words, list operators tend to gobble up all the arguments that follow them, and then act like a simple TERM with regard to the preceding expression. Note that you have to be careful with parentheses:

    # These evaluate exit before doing the print:
    print $foo, exit;   # Nor is this.

    # These do the print before evaluating exit:
    print($foo), exit;  # Or this.

Also note that





The Arrow Operator

Just as in C and C++, "->" is an infix dereference operator. If the right side is either a [...] or {...} 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 perlref.

Otherwise, the right side is a method name or a simple scalar variable containing the method name, and the left side must either be an object (a blessed reference) or a class name (that is, a package name). See perlobj.

Auto-increment and Auto-decrement




The auto-decrement operator is not magical.


Binary "**" is the exponentiation operator. Note that it binds even more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is implemented using C's pow(3) function, which actually works on doubles internally.)

Symbolic Unary Operators





Unary "\" creates a reference to whatever follows it. See perlref. Do not confuse this behavior with the behavior of backslash within a string, although both forms do convey the notion of protecting the next thing from interpretation.

Binding Operators

Binary "=~" binds a scalar expression to a pattern match. Certain operations search or modify the string $_ by default. This operator makes that kind of operation work on some other string. The right argument is a search pattern, substitution, or transliteration. The left argument is what is supposed to be searched, substituted, or transliterated instead of the default $_. The return value indicates the success of the operation. (If the right argument is an expression rather than a search pattern, substitution, or transliteration, it is interpreted as a search pattern at run time. This can be is less efficient than an explicit search, because the pattern must be compiled every time the expression is evaluated.


Multiplicative Operators

Binary "*" multiplies two numbers.

Binary "/" divides two numbers.


Binary "x" is the repetition operator. In scalar context, it returns a string consisting of the left operand repeated the number of times specified by the right operand. In list context, if the left operand is a list in parentheses, it repeats the list.

    print '-' x 80;             # print row of dashes



Additive Operators

Binary "+" returns the sum of two numbers.

Binary "-" returns the difference of two numbers.

Binary "." concatenates two strings.

Shift Operators



Named Unary Operators




but, because * is higher precedence than ||:


    rand 10 * 20;       # rand (10 * 20)

See also "Terms and List Operators (Leftward)".

Relational Operators









Equality Operators








Bitwise And


Bitwise Or and Exclusive Or



C-style Logical And


C-style Logical Or







    unlink "alpha", "beta", "gamma"
            or gripe(), next LINE;


            || (gripe(), next LINE);

Use "or" for assignment is unlikely to do what you want; see below.

Range Operators


    for (1 .. 1_000_000) {
        # code


As a scalar operator:


    # parse mail messages
    while (<>) {
        $in_header =   1  .. /^$/;
        # do something based on those
    } continue {
        close ARGV if eof;              # reset $. each file

As a list operator:




to get all the letters of the alphabet, or


to get a hexadecimal digit, or



Conditional Operator







This is not necessarily guaranteed to contribute to the readability of your program.



Really means this:


Rather than this:


Assignment Operators

"=" is the ordinary assignment operator.

Assignment operators work as in C. That is,

    $a += 2;

is equivalent to

    $a = $a + 2;


           -=    /=    |=    >>=    ||=
           .=    %=    ^=

Note that while these are grouped by family, they all have the precedence of assignment.




    ($a += 2) *= 3;

is equivalent to

    $a += 2;
    $a *= 3;

Comma Operator




List Operators (Rightward)


    open HANDLE, "filename"
        or die "Can't open: $!\n";


Logical Not


Logical And


Logical or and Exclusive Or





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.


Then again, you could always use parentheses.


C Operators Missing From Perl

Here is what C has that Perl doesn't:

unary &


unary *



Type casting operator.

Quote and Quote-like Operators

While we usually think of quotes as literal values, in Perl they function as operators, providing various kinds of interpolating and pattern matching capabilities. Perl provides customary quote characters for these behaviors, but also provides a way for you to choose your quote character for any of them. In the following table, a {} represents any pair of delimiters you choose. Non-bracketing delimiters use the same character fore and aft, but the 4 sorts of brackets (round, angle, square, curly) will all nest.

    Customary  Generic        Meaning        Interpolates
        ''       q{}          Literal             no
        ""      qq{}          Literal             yes
                qw{}         Word list            no
        //       m{}       Pattern match          yes
                qr{}          Pattern             yes
                 s{}{}      Substitution          yes
                tr{}{}    Transliteration         no (but see below)

Note that there can be whitespace between the operator and the quoting characters, except when # is being used as the quoting character. q#foo# is parsed as being the string foo, while q #foo# is the operator q followed by a comment. Its argument will be taken from the next line. This allows you to write:

    s {foo}  # Replace foo
      {bar}  # with bar.

For constructs that do interpolation, variables beginning with "$" or "@" are interpolated, as are the following sequences. Within a transliteration, the first eleven of these sequences may be used.

    \t          tab             (HT, TAB)
    \n          newline         (NL)
    \r          return          (CR)
    \f          form feed       (FF)
    \b          backspace       (BS)
    \a          alarm (bell)    (BEL)
    \e          escape          (ESC)
    \033        octal char      (ESC)
    \x1b        hex char        (ESC)
    \x{263a}    wide hex char   (SMILEY)
    \c[         control char

    \l          lowercase next char
    \u          uppercase next char
    \L          lowercase till \E
    \U          uppercase till \E
    \E          end case modification
    \Q          quote non-word characters till \E





Apart from the above, there are no multiple levels of interpolation. In particular, contrary to the expectations of shell programmers, back-quotes do NOT interpolate within double quotes, nor do single quotes impede evaluation of variables when used within double quotes.

Regexp Quote-Like Operators


Most of this section is related to use of regular expressions from Perl. Such a use may be considered from two points of view: Perl handles a a string and a "pattern" to RE (regular expression) engine to match, RE engine finds (or does not find) the match, and Perl uses the findings of RE engine for its operation, possibly asking the engine for other matches.

RE engine has no idea what Perl is going to do with what it finds, similarly, the rest of Perl has no idea what a particular regular expression means to RE engine. This creates a clean separation, and in this section we discuss matching from Perl point of view only. The other point of view may be found in perlre.



    while (<>) {
        if (?^$?) {
                            # blank line between header and body
    } continue {
        reset if eof;       # clear ?? status for next file

This usage is vaguely deprecated, and may be removed in some future version of Perl.


Searches a string for a pattern match, and in scalar context returns true (1) or false (''). If no string is specified via the =~ or !~ operator, the $_ string is searched. (The string specified with =~ need not be an lvalue--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.) See also perlre. See perllocale for discussion of additional considerations that apply when use locale is in effect.

Options are:

    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.

If "/" is the delimiter then the initial m is optional. With the m 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 LTS (leaning toothpick syndrome). If "?" is the delimiter, then the match-only-once rule of ?PATTERN? applies.

PATTERN may contain variables, which will be interpolated (and the pattern recompiled) every time the pattern search is evaluated. (Note that $) and $| 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 /o 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 /o constitutes a promise that you won't change the variables in the pattern. If you change them, Perl won't even notice.




    open(TTY, '/dev/tty');



    # poor man's grep
    $arg = shift;
    while (<>) {
        print if /$arg/o;       # compile only once



The /g 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.

In scalar context, each execution of m//g finds the next match, returning TRUE if it matches, and FALSE if there is no further match. The position after the last match can be read or set using the pos() function; see "pos" in perlfunc. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the /c modifier (e.g. m//gc). Modifying the target string also resets the search position.



    # list context

    # scalar context
    while (defined($paragraph = <>)) {
    print "$sentences\n";

    # using m//gc with \G
    $_ = "ppooqppqq";
    while ($i++ < 2) {
        print "1: '";
        print "2: '";
        print "3: '";

The last example should print:

    1: 'oo', pos=4
    2: 'q', pos=5
    3: 'pp', pos=7
    1: '', pos=7
    2: 'q', pos=8
    3: '', pos=8


 $_ = <<'EOL';
      print ". That's all!\n";

Here is the output (split into several lines):

 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!



A double-quoted, interpolated string.

    $_ .= qq
                if /(tcl|rexx|python)/;      # :-)

Quote-as-a-regular-expression operator. STRING is interpolated the same way as PATTERN in m/PATTERN/. Returns a Perl value which may be used instead of the corresponding /STRING/imosx expression.

For example,

    $rex = qr/my.STRING/is;

is equivalent to


The result may be used as a subpattern in a match:

    $re = qr/$pattern/;
    $string =~ $re;             # or used standalone


    sub match {
        my $patterns = shift;
        grep {
            my $success = 0;
            foreach my $pat @compiled {
                $success = 1, last if /$pat/;
        } @_;

Precompilation of the pattern into an internal representation at the moment of qr() avoids a need to recompile the pattern every time a match /$pat/ is attempted. (Note that Perl has many other internal optimizations, but none would be triggered in the above example if we did not use qr() operator.)

Options are:

    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.





    $output = `cmd 2>&1`;

To capture a command's STDOUT but discard its STDERR:
















Returns a list of the words extracted out of STRING, using embedded whitespace as the word delimiters. It is exactly equivalent to

    split(' ', q/STRING/);

This equivalency means that if used in scalar context, you'll get split's (unfortunate) scalar context behavior, complete with mysterious warnings.

Some frequently seen examples:

    use POSIX qw( setlocale localeconv )
    @EXPORT = qw( foo bar baz );

A common mistake is to try to separate the words with comma or to put comments into a multi-line qw-string. For this reason the -w switch produce warnings if the STRING contains the "," or the "#" character.





Options are:

    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.

Any non-alphanumeric, non-whitespace delimiter may replace the slashes. If single quotes are used, no interpretation is done on the replacement string (the /e 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 PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own pair of quotes, which may or may not be bracketing quotes, e.g., s(foo)(bar) or s<foo>/bar/. A /e will cause the replacement portion to be interpreted as a full-fledged Perl expression and eval()ed right then and there. It is, however, syntax checked at compile-time.







    $_ = 'abc123xyz';


    # expand variables in $_, but dynamics only, using
    # symbolic dereferencing

    # /e's can even nest;  this will expand
    # any embedded scalar variable (including lexicals) in $_

    # Delete (most) C comments.
    $program =~ s {
        /\*     # Match the opening delimiter.
        .*?     # Match a minimal number of characters.
        \*/     # Match the closing delimiter.
    } []gsx;





Occasionally, you can't use just a /g to get all the changes to occur. Here are two common cases:

    # put commas in the right places in an integer

    # expand tabs to 8-column spacing





    c   Complement the SEARCHLIST.
    d   Delete found but unreplaced characters.
    s   Squash duplicate replaced characters.
    U   Translate to/from UTF-8.












    tr [\200-\377]
       [\000-\177];             # delete 8th bit

    tr/\0-\xFF//CU;             # translate Latin-1 to Unicode
    tr/\0-\x{FF}//UC;           # translate Unicode to Latin-1



will transliterate any A to X.


    eval "tr/$oldlist/$newlist/";
    die $@ if $@;


Gory details of parsing quoted constructs

When presented with something which may have several different interpretations, Perl uses the principle DWIM (expanded to Do What I Mean - not what I wrote) to pick up the most probable interpretation of the source. This strategy is so successful that Perl users usually do not suspect ambivalence of what they write. However, time to time Perl's ideas differ from what the author meant.

The target of this section is to clarify the Perl's way of interpreting quoted constructs. The most frequent reason one may have to want to know the details discussed in this section is hairy regular expressions. However, the first steps of parsing are the same for all Perl quoting operators, so here they are discussed together.

Some of the passes discussed below are performed concurrently, but as far as results are the same, we consider them one-by-one. For different quoting constructs Perl performs different number of passes, from one to five, but they are always performed in the same order.

Finding the end

First pass is finding the end of the quoted construct, be it multichar ender "\nEOF\n" of <<EOF construct, / which terminates qq/ construct, ] which terminates qq[ construct, or > which terminates a fileglob started with <.

When searching for multichar construct no skipping is performed. When searching for one-char non-matching delimiter, such as /, combinations \\ and \/ are skipped. When searching for one-char matching delimiter, such as ], combinations \\, \] and \[ are skipped, and nested [, ] are skipped as well.

For 3-parts constructs, s/// etc. the search is repeated once more.

During this search no attention is paid to the semantic of the construct, thus



      bar       #  This is not a comment, this slash / terminated m//!

do not form legal quoted expressions. Note that since the slash which terminated m// was followed by a SPACE, this is not m//x, thus # was interpreted as a literal #.

Removal of backslashes before delimiters

During the second pass the text between the starting delimiter and the ending delimiter is copied to a safe location, and the \ is removed from combinations consisting of \ and delimiter(s) (both starting and ending delimiter if they differ).

The removal does not happen for multi-char delimiters.

Note that the combination \\ is left as it was!

Starting from this step no information about the delimiter(s) is used in the parsing.


Next step is interpolation in the obtained delimiter-independent text. There are four different cases.


No interpolation is performed.

'', q//

The only interpolation is removal of \ from pairs \\.


\Q, \U, \u, \L, \l (possibly paired with \E) are converted to corresponding Perl constructs, thus "$foo\Qbaz$bar" is converted to

   $foo . (quotemeta("baz" . $bar));

Other combinations of \ with following chars are substituted with appropriate expansions.

Interpolated scalars and arrays are converted to join and . Perl constructs, thus "'@arr'" becomes

  "'" . (join $", @arr) . "'";

Since all three above steps are performed simultaneously left-to-right, the is no way to insert a literal $ or @ inside \Q\E pair: it cannot be protected by \, since any \ (except in \E) is interpreted as a literal inside \Q\E, and any $ is interpreted as starting an interpolated scalar.

Note also that the interpolating code needs to make decision where the interpolated scalar ends, say, whether "a $b -> {c}" means



  "a " . $b -> {c};

Most the time the decision is to take the longest possible text which does not include spaces between components and contains matching braces/brackets.


Processing of \Q, \U, \u, \L, \l and interpolation happens (almost) as with qq// constructs, but the substitution of \ followed by other chars is not performed! Moreover, inside (?{BLOCK}) no processing is performed at all.

Interpolation has several quirks: $|, $( and $) are not interpolated, and constructs $var[SOMETHING] are voted (by several different estimators) to be an array element or $var followed by a RE alternative. This is the place where the notation ${arr[$bar]} comes handy: /${arr[0-9]}/ is interpreted as an array element -9, not as a regular expression from variable $arr followed by a digit, which is the interpretation of /$arr[0-9]/.

Note that absence of processing of \\ creates specific restrictions on the post-processed text: if the delimiter is /, one cannot get the combination \/ into the result of this step: / will finish the regular expression, \/ will be stripped to / on the previous step, and \\/ will be left as is. Since / is equivalent to \/ inside a regular expression, this does not matter unless the delimiter is special character for the RE engine, as in s*foo*bar*, m[foo], or ?foo?.

This step is the last one for all the constructs except regular expressions, which are processed further.

Interpolation of regular expressions

All the previous steps were performed during the compilation of Perl code, this one happens in run time (though it may be optimized to be calculated at compile time if appropriate). After all the preprocessing performed above (and possibly after evaluation if catenation, joining, up/down-casing and quotemeta()ing are involved) the resulting string is passed to RE engine for compilation.

Whatever happens in the RE engine is better be discussed in perlre, but for the sake of continuity let us do it here.

This is the first step where presence of the //x switch is relevant. The RE engine scans the string left-to-right, and converts it to a finite automaton.

Backslashed chars are either substituted by corresponding literal strings, or generate special nodes of the finite automaton. Characters which are special to the RE engine generate corresponding nodes. (?#...) comments are ignored. All the rest is either converted to literal strings to match, or is ignored (as is whitespace and #-style comments if //x is present).

Note that the parsing of the construct [...] is performed using absolutely different rules than the rest of the regular expression. Similarly, the (?{...}) is only checked for matching braces.

Optimization of regular expressions


I/O Operators

There are several I/O operators you should know about. A string enclosed by backticks (grave accents) first undergoes variable substitution just like a double quoted string. It is then interpreted as a command, and the output of that command is the value of the pseudo-literal, like in a shell. In scalar context, a single string consisting of all the output is returned. In list context, a list of values is returned, one for each line of output. (You can set $/ to use a different line terminator.) The command is executed each time the pseudo-literal is evaluated. The status value of the command is returned in $? (see perlvar for the interpretation of $?). Unlike in csh, no translation is done on the return data--newlines remain newlines. Unlike in any of the shells, single quotes do not hide variable names in the command from interpretation. To pass a $ through to the shell you need to hide it with a backslash. The generalized form of backticks is qx//. (Because backticks always undergo shell expansion as well, see perlsec for security concerns.)

Evaluating a filehandle in angle brackets yields the next line from that file (newline, if any, included), or undef at end of file. Ordinarily you must assign that value to a variable, but there is one situation where an automatic assignment happens. If and ONLY if the input symbol is the only thing inside the conditional of a while or for(;;) loop, the value is automatically assigned to the variable $_. In these loop constructs, the assigned value (whether assignment is automatic or explicit) is then tested to see if it is defined. The defined test avoids problems where line has a string value that would be treated as false by perl e.g. "" or "0" with no trailing newline. (This may seem like an odd thing to you, but you'll use the construct in almost every Perl script you write.) Anyway, the following lines are equivalent to each other:

    while (<STDIN>) { print; }
    for (;<STDIN>;) { print; }
    print while defined($_ = <STDIN>);
    print while ($_ = <STDIN>);
    print while <STDIN>;

and this also behaves similarly, but avoids the use of $_ :


If you really mean such values to terminate the loop they should be tested for explicitly:


In other boolean contexts, <filehandle> without explicit defined test or comparison will solicit a warning if -w is in effect.

The filehandles STDIN, STDOUT, and STDERR are predefined. (The filehandles stdin, stdout, and stderr will also work except in packages, where they would be interpreted as local identifiers rather than global.) Additional filehandles may be created with the open() function. See "open()" in perlfunc for details on this.

If a <FILEHANDLE> is used in a context that is looking for a list, a list consisting of all the input lines is returned, one line per list element. It's easy to make a LARGE data space this way, so use with care.


    while (<>) {
        ...                     # code for each line

is equivalent to the following Perl-like pseudo code:

    while ($ARGV = shift) {
        open(ARGV, $ARGV);
        while (<ARGV>) {
            ...         # code for each line

except that it isn't so cumbersome to say, and will actually work. It really does shift array @ARGV and put the current filename into variable $ARGV. It also uses filehandle ARGV internally--<> is just a synonym for <ARGV>, which is magical. (The pseudo code above doesn't work because it treats <ARGV> as non-magical.)

You can modify @ARGV before the first <> as long as the array ends up containing the list of filenames you really want. Line numbers ($.) continue as if the input were one big happy file. (But see example under eof for how to reset line numbers on each file.)






        last if /^--$/;
        # ...           # other switches

    while (<>) {
        # ...           # code for each line

The <> symbol will return undef for end-of-file only once. If you call it again after this it will assume you are processing another @ARGV list, and if you haven't set @ARGV, will input from STDIN.

If the string inside the angle brackets is a reference to a scalar variable (e.g., <$foo>), then that variable contains the name of the filehandle to input from, or its typeglob, or a reference to the same. For example:

    $fh = \*STDIN;
    $line = <$fh>;

If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed, and either a list of filenames or the next filename in the list is returned, depending on context. This distinction is determined on syntactic grounds alone. That means <$x> is always a readline from an indirect handle, but <$hash{key}> is always a glob. That's because $x is a simple scalar variable, but $hash{key} is not--it's a hash element.


    while (<*.c>) {
        chmod 0644, $_;

is equivalent to

    while (<FOO>) {
        chmod 0644, $_;

In fact, it's currently implemented that way. (Which means it will not work on filenames with spaces in them unless you have csh(1) on your machine.) Of course, the shortest way to do the above is:

    chmod 0644, <*.c>;

Because globbing invokes a shell, it's often faster to call readdir() yourself and do your own grep() on the filenames. Furthermore, due to its current implementation of using a shell, the glob() routine may get "Arg list too long" errors (unless you've installed tcsh(1L) as /bin/csh).

A glob evaluates its (embedded) argument only when it is starting a new list. All values must be read before it will start over. In a list context this isn't important, because you automatically get them all anyway. In scalar context, however, the operator returns the next value each time it is called, or a undef value if you've just run out. As for filehandles an automatic defined is generated when the glob occurs in the test part of a while or for - because legal glob returns (e.g. a file called 0) would otherwise terminate the loop. Again, undef is returned only once. So if you're expecting a single value from a glob, it is much better to say

    ($file) = <blurch*>;


    $file = <blurch*>;

because the latter will alternate between returning a filename and returning FALSE.



Constant Folding


        'good men to come to.'


    foreach $file (@filenames) {

the compiler will precompute the number that expression represents so that the interpreter won't have to.

Bitwise String Operators


If the operands to a binary bitwise op are strings of different sizes, or and xor ops will act as if the shorter operand had additional zero bits on the right, while the and op will act as if the longer operand were truncated to the length of the shorter.

    # ASCII-based examples 

If you are intending to manipulate bitstrings, you should be certain that you're supplying bitstrings: If an operand is a number, that will imply a numeric bitwise operation. You may explicitly show which type of operation you intend by using "" or 0+, as in the examples below.

    $foo = '150' |  105 ;       # yields 255
    $foo =  150  | '105';       # yields 255


Integer Arithmetic

By default Perl assumes that it must do most of its arithmetic in floating point. But by saying

    use integer;

you may tell the compiler that it's okay to use integer operations from here to the end of the enclosing BLOCK. An inner BLOCK may countermand this by saying

    no integer;

which lasts until the end of that BLOCK.


Floating-point Arithmetic

While use integer provides integer-only arithmetic, there is no similar ways to provide rounding or truncation at a certain number of decimal places. For rounding to a certain number of digits, sprintf() or printf() is usually the easiest route.


    printf "%.20g\n", 123456789123456789;
    #        produces 123456789123456784


    sub fp_equal {
        my ($tX, $tY);
        return $tX eq $tY;

The POSIX module (part of the standard perl distribution) implements ceil(), floor(), and a number of other mathematical and trigonometric functions. The Math::Complex module (part of the standard perl distribution) defines a number of mathematical functions that can also work on real numbers. Math::Complex not as efficient as POSIX, but POSIX can't work with complex numbers.


Bigger Numbers

The standard Math::BigInt and Math::BigFloat modules provide variable precision arithmetic and overloaded operators. At the cost of some space and considerable speed, they avoid the normal pitfalls associated with limited-precision representations.

    use Math::BigInt;
    print $x * $x;

    # prints +15241578780673678515622620750190521