"open" in perlfunc for details on this.
If a "<*FILEHANDLE*>" is used in a context that is looking for a
list, a list comprising all input lines is returned, one line
per list element. It's easy to grow to a rather large data space
this way, so use with care.
"<*FILEHANDLE*>" may also be spelled "readline(**FILEHANDLE*)".
See "readline" in perlfunc.
The null filehandle "<>" (sometimes called the diamond operator)
is special: it can be used to emulate the behavior of sed and
awk, and any other Unix filter program that takes a list of
filenames, doing the same to each line of input from all of
them. Input from "<>" comes either from standard input, or from
each file listed on the command line. Here's how it works: the
first time "<>" is evaluated, the @ARGV array is checked, and if
it is empty, $ARGV[0] is set to "-", which when opened gives you
standard input. The @ARGV array is then processed as a list of
filenames. The loop
while (<>) {
... # code for each line
}
is equivalent to the following Perl-like pseudo code:
unshift(@ARGV, '-') unless @ARGV;
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 the @ARGV array and put the current
filename into the $ARGV variable. 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.)
Since the null filehandle uses the two argument form of "open"
in perlfunc it interprets special characters, so if you have a
script like this:
while (<>) {
print;
}
and call it with "perl dangerous.pl 'rm -rfv *|'", it actually
opens a pipe, executes the "rm" command and reads "rm"'s output
from that pipe. If you want all items in @ARGV to be interpreted
as file names, you can use the module "ARGV::readonly" from
CPAN, or use the double diamond bracket:
while (<<>>) {
print;
}
Using double angle brackets inside of a while causes the open to
use the three argument form (with the second argument being
"<"), so all arguments in "ARGV" are treated as literal
filenames (including "-"). (Note that for convenience, if you
use "<<>>" and if @ARGV is empty, it will still read from the
standard input.)
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 though the input were one big happy
file. See the example in "eof" in perlfunc for how to reset line
numbers on each file.
If you want to set @ARGV to your own list of files, go right
ahead. This sets @ARGV to all plain text files if no @ARGV was
given:
@ARGV = grep { -f && -T } glob('*') unless @ARGV;
You can even set them to pipe commands. For example, this
automatically filters compressed arguments through gzip:
@ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;
If you want to pass switches into your script, you can use one
of the "Getopts" modules or put a loop on the front like this:
while ($_ = $ARGV[0], /^-/) {
shift;
last if /^--$/;
if (/^-D(.*)/) { $debug = $1 }
if (/^-v/) { $verbose++ }
# ... # 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 read input from STDIN.
If what the angle brackets contain is a simple scalar variable
(for example, $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. Even "<$x >" (note the extra space) is treated as
"glob("$x ")", not "readline($x)".
One level of double-quote interpretation is done first, but you
can't say "<$foo>" because that's an indirect filehandle as
explained in the previous paragraph. (In older versions of Perl,
programmers would insert curly brackets to force interpretation
as a filename glob: "<${foo}>". These days, it's considered
cleaner to call the internal function directly as "glob($foo)",
which is probably the right way to have done it in the first
place.) For example:
while (<*.c>) {
chmod 0644, $_;
}
is roughly equivalent to:
open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
while (<FOO>) {
chomp;
chmod 0644, $_;
}
except that the globbing is actually done internally using the
standard "File::Glob" extension. Of course, the shortest way to
do the above is:
chmod 0644, <*.c>;
A (file)glob evaluates its (embedded) argument only when it is
starting a new list. All values must be read before it will
start over. In list context, this isn't important because you
automatically get them all anyway. However, in scalar context
the operator returns the next value each time it's called, or
"undef" when the list has run out. As with filehandle reads, an
automatic "defined" is generated when the glob occurs in the
test part of a "while", because legal glob returns (for example,
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*>;
than
$file = <blurch*>;
because the latter will alternate between returning a filename
and returning false.
If you're trying to do variable interpolation, it's definitely
better to use the "glob()" function, because the older notation
can cause people to become confused with the indirect filehandle
notation.
@files = glob("$dir/*.[ch]");
@files = glob($files[$i]);
If an angle-bracket-based globbing expression is used as the
condition of a "while" or "for" loop, then it will be implicitly
assigned to $_. If either a globbing expression or an explicit
assignment of a globbing expression to a scalar is used as a
"while"/"for" condition, then the condition actually tests for
definedness of the expression's value, not for its regular truth
value.
Constant Folding
Like C, Perl does a certain amount of expression evaluation at compile
time whenever it determines that all arguments to an operator are static
and have no side effects. In particular, string concatenation happens at
compile time between literals that don't do variable substitution.
Backslash interpolation also happens at compile time. You can say
'Now is the time for all'
. "\n"
. 'good men to come to.'
and this all reduces to one string internally. Likewise, if you say
foreach $file (@filenames) {
if (-s $file > 5 + 100 * 2**16) { }
}
the compiler precomputes the number which that expression represents so
that the interpreter won't have to.
No-ops
Perl doesn't officially have a no-op operator, but the bare constants 0
and 1 are special-cased not to produce a warning in void context, so you
can for example safely do
1 while foo();
Bitwise String Operators
Bitstrings of any size may be manipulated by the bitwise operators ("~ |
& ^").
If the operands to a binary bitwise op are strings of different sizes, |
and ^ ops act as though the shorter operand had additional zero bits on
the right, while the & op acts as though the longer operand were
truncated to the length of the shorter. The granularity for such
extension or truncation is one or more bytes.
# ASCII-based examples
print "j p \n" ^ " a h"; # prints "JAPH\n"
print "JA" | " ph\n"; # prints "japh\n"
print "japh\nJunk" & '_____'; # prints "JAPH\n";
print 'p N$' ^ " E<H\n"; # prints "Perl\n";
If you are intending to manipulate bitstrings, 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 (0x96 | 0x69 is 0xFF)
$foo = '150' | 105; # yields 255
$foo = 150 | '105'; # yields 255
$foo = '150' | '105'; # yields string '155' (under ASCII)
$baz = 0+$foo & 0+$bar; # both ops explicitly numeric
$biz = "$foo" ^ "$bar"; # both ops explicitly stringy
This somewhat unpredictable behavior can be avoided with the "bitwise"
feature, new in Perl 5.22. You can enable it via "use feature 'bitwise'"
or "use v5.28". Before Perl 5.28, it used to emit a warning in the
"experimental::bitwise" category. Under this feature, the four standard
bitwise operators ("~ | & ^") are always numeric. Adding a dot after
each operator ("~. |. &. ^.") forces it to treat its operands as
strings:
use feature "bitwise";
$foo = 150 | 105; # yields 255 (0x96 | 0x69 is 0xFF)
$foo = '150' | 105; # yields 255
$foo = 150 | '105'; # yields 255
$foo = '150' | '105'; # yields 255
$foo = 150 |. 105; # yields string '155'
$foo = '150' |. 105; # yields string '155'
$foo = 150 |.'105'; # yields string '155'
$foo = '150' |.'105'; # yields string '155'
$baz = $foo & $bar; # both operands numeric
$biz = $foo ^. $bar; # both operands stringy
The assignment variants of these operators ("&= |= ^= &.= |.= ^.=")
behave likewise under the feature.
It is a fatal error if an operand contains a character whose ordinal
value is above 0xFF, and hence not expressible except in UTF-8. The
operation is performed on a non-UTF-8 copy for other operands encoded in
UTF-8. See "Byte and Character Semantics" in perlunicode.
See "vec" in perlfunc for information on how to manipulate individual
bits in a bit vector.
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 to use integer operations (see integer for a
detailed explanation) 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. Note that this doesn't mean
everything is an integer, merely that Perl will use integer operations
for arithmetic, comparison, and bitwise operators. For example, even
under "use integer", if you take the sqrt(2), you'll still get
1.4142135623731 or so.
Used on numbers, the bitwise operators ("&" "|" "^" "~" "<<" ">>")
always produce integral results. (But see also "Bitwise String
Operators".) However, "use integer" still has meaning for them. By
default, their results are interpreted as unsigned integers, but if
"use integer" is in effect, their results are interpreted as signed
integers. For example, "~0" usually evaluates to a large integral value.
However, "use integer; ~0" is -1 on two's-complement machines.
Floating-point Arithmetic
While "use integer" provides integer-only arithmetic, there is no
analogous mechanism to provide automatic rounding or truncation to a
certain number of decimal places. For rounding to a certain number of
digits, "sprintf()" or "printf()" is usually the easiest route. See
perlfaq4.
Floating-point numbers are only approximations to what a mathematician
would call real numbers. There are infinitely more reals than floats, so
some corners must be cut. For example:
printf "%.20g\n", 123456789123456789;
# produces 123456789123456784
Testing for exact floating-point equality or inequality is not a good
idea. Here's a (relatively expensive) work-around to compare whether two
floating-point numbers are equal to a particular number of decimal
places. See Knuth, volume II, for a more robust treatment of this topic.
sub fp_equal {
my ($X, $Y, $POINTS) = @_;
my ($tX, $tY);
$tX = sprintf("%.${POINTS}g", $X);
$tY = sprintf("%.${POINTS}g", $Y);
return $tX eq $tY;
}
The POSIX module (part of the standard perl distribution) implements
"ceil()", "floor()", and other mathematical and trigonometric functions.
The "Math::Complex" module (part of the standard perl distribution)
defines mathematical functions that work on both the reals and the
imaginary numbers. "Math::Complex" is not as efficient as POSIX, but
POSIX can't work with complex numbers.
Rounding in financial applications can have serious implications, and
the rounding method used should be specified precisely. In these cases,
it probably pays not to trust whichever system rounding is being used by
Perl, but to instead implement the rounding function you need yourself.
Bigger Numbers
The standard "Math::BigInt", "Math::BigRat", and "Math::BigFloat"
modules, along with the "bignum", "bigint", and "bigrat" pragmas,
provide variable-precision arithmetic and overloaded operators, although
they're currently pretty slow. At the cost of some space and
considerable speed, they avoid the normal pitfalls associated with
limited-precision representations.
use 5.010;
use bigint; # easy interface to Math::BigInt
$x = 123456789123456789;
say $x * $x;
+15241578780673678515622620750190521
Or with rationals:
use 5.010;
use bigrat;
$x = 3/22;
$y = 4/6;
say "x/y is ", $x/$y;
say "x*y is ", $x*$y;
x/y is 9/44
x*y is 1/11
Several modules let you calculate with unlimited or fixed precision
(bound only by memory and CPU time). There are also some non-standard
modules that provide faster implementations via external C libraries.
Here is a short, but incomplete summary:
Math::String treat string sequences like numbers
Math::FixedPrecision calculate with a fixed precision
Math::Currency for currency calculations
Bit::Vector manipulate bit vectors fast (uses C)
Math::BigIntFast Bit::Vector wrapper for big numbers
Math::Pari provides access to the Pari C library
Math::Cephes uses the external Cephes C library (no
big numbers)
Math::Cephes::Fraction fractions via the Cephes library
Math::GMP another one using an external C library
Math::GMPz an alternative interface to libgmp's big ints
Math::GMPq an interface to libgmp's fraction numbers
Math::GMPf an interface to libgmp's floating point numbers
Choose wisely.
POD ERRORS
Hey! The above document had some coding errors, which are explained
below:
Around line 183:
You forgot a '=back' before '=head2'
Around line 406:
=back without =over
Generated by phpman v3.7.12 Author: Che Dong Under GNU General Public License
2026-06-14 05:34 @216.73.216.200
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)