|
|
|
|
NAMEperlfunc - Perl builtin functions
DESCRIPTIONThe functions in this section can serve as terms in an expression. They fall
into two major categories: list operators and named unary operators. These
differ in their precedence relationship with a following comma. (See the
precedence table in
the perlop manpage.) List operators take more than one argument, while unary
operators can never take more than one argument. Thus, a comma terminates the
argument of a unary operator, but merely separates the arguments of a list
operator. A unary operator generally provides a scalar context to its argument,
while a list operator may provide either scalar or list contexts for its
arguments. If it does both, the scalar arguments will be first, and the list
argument will follow. (Note that there can ever be only one such list argument.)
For instance, In the syntax descriptions that follow, list operators that expect a list (and provide list context for the elements of the list) are shown with LIST as an argument. Such a list may consist of any combination of scalar arguments or list values; the list values will be included in the list as if each individual element were interpolated at that point in the list, forming a longer single-dimensional list value. Elements of the LIST should be separated by commas. Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use the parentheses, the simple (but occasionally surprising) rule is this: It looks like a function, therefore it is a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. And whitespace between the function and left parenthesis doesn't count--so you need to be careful sometimes: print 1+2+4; # Prints 7.
print(1+2) + 4; # Prints 3.
print (1+2)+4; # Also prints 3!
print +(1+2)+4; # Prints 7.
print ((1+2)+4); # Prints 7.
If you run Perl with the -w switch it can warn you about this. For example, the third line above produces: print (...) interpreted as function at - line 1.
Useless use of integer addition in void context at - line 1.
A few functions take no arguments at all, and therefore work as neither unary
nor list operators. These include such functions as For functions that can be used in either a scalar or list context, nonabortive failure is generally indicated in a scalar context by returning the undefined value, and in a list context by returning the null list. Remember the following important rule: There is no rule that relates the behavior of an expression in list context to its behavior in scalar context, or vice versa. It might do two totally different things. Each operator and function decides which sort of value it would be most appropriate to return in scalar context. Some operators return the length of the list that would have been returned in list context. Some operators return the first value in the list. Some operators return the last value in the list. Some operators return a count of successful operations. In general, they do what you want, unless you want consistency. An named array in scalar context is quite different from what would at first
glance appear to be a list in scalar context. You can't get a list like In general, functions in Perl that serve as wrappers for system calls of the
same name (like chown(2), fork(2), closedir(2), etc.) all return true when they
succeed and
Perl Functions by CategoryHere are Perl's functions (including things that look like functions, like some keywords and named operators) arranged by category. Some functions appear in more than one place.
PortabilityPerl was born in Unix and can therefore access all common Unix system calls. In non-Unix environments, the functionality of some Unix system calls may not be available, or details of the available functionality may differ slightly. The Perl functions affected by this are:
For more information about the portability of these functions, see the perlport manpage and other available platform-specific documentation.
Alphabetical Listing of Perl Functions
-r File is readable by effective uid/gid.
-w File is writable by effective uid/gid.
-x File is executable by effective uid/gid.
-o File is owned by effective uid.
-R File is readable by real uid/gid.
-W File is writable by real uid/gid.
-X File is executable by real uid/gid.
-O File is owned by real uid.
-e File exists.
-z File has zero size (is empty).
-s File has nonzero size (returns size in bytes).
-f File is a plain file.
-d File is a directory.
-l File is a symbolic link.
-p File is a named pipe (FIFO), or Filehandle is a pipe.
-S File is a socket.
-b File is a block special file.
-c File is a character special file.
-t Filehandle is opened to a tty.
-u File has setuid bit set.
-g File has setgid bit set.
-k File has sticky bit set.
-T File is an ASCII text file.
-B File is a "binary" file (opposite of -T).
-M Age of file in days when script started.
-A Same for access time.
-C Same for inode change time.
Example: while (<>) {
chomp;
next unless -f $_; # ignore specials
#...
}
The interpretation of the file permission operators Also note that, for the superuser on the local filesystems, the If you are using ACLs, there is a pragma called Note that The
If any of the file tests (or either the print "Can do.\n" if -r $a || -w _ || -x _; stat($filename);
print "Readable\n" if -r _;
print "Writable\n" if -w _;
print "Executable\n" if -x _;
print "Setuid\n" if -u _;
print "Setgid\n" if -g _;
print "Sticky\n" if -k _;
print "Text\n" if -T _;
print "Binary\n" if -B _;
$_.
accept(2) system call does. Returns the packed address if it
succeeded, false otherwise. See the example in
Sockets: Client/Server Communication in the perlipc manpage.
On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See $^F in the perlvar manpage.
$_ is used. (On some machines, unfortunately, the elapsed
time may be up to one second less than you specified because of how seconds
are counted.) Only one timer may be counting at once. Each call disables the
previous timer, and an argument of 0 may be supplied to cancel
the previous timer without starting a new one. The returned value is the
amount of time remaining on the previous timer.
For delays of finer granularity than one second, you may use Perl's
four-argument version of It is usually a mistake to intermix If you want to use eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
alarm $timeout;
$nread = sysread SOCKET, $buffer, $size;
alarm 0;
};
if ($@) {
die unless $@ eq "alarm\n"; # propagate unexpected errors
# timed out
}
else {
# didn't
}
For the tangent operation, you may use the sub tan { sin($_[0]) / cos($_[0]) }
":raw" for binary
mode or ":crlf" for ``text'' mode. If the DISCIPLINE is omitted,
it defaults to ":raw".
On many systems In other words: Regardless of platform, use The The operating system, device drivers, C libraries, and Perl run-time system
all work together to let the programmer treat a single character ( Mac OS and all variants of Unix use a single character to end each line in
the external representation of text (even though that single character is not
necessarily the same across these platforms). Consequently
Another consequence of using
bless is often the last
thing in a constructor, it returns the reference for convenience. Always use
the two-argument version if the function doing the blessing might be inherited
by a derived class. See
the perltoot manpage and
the perlobj manpage for more about the blessing (and blessings) of
objects.
Consider always blessing objects in CLASSNAMEs that are mixed case. Namespaces with all lowercase names are considered reserved for Perl pragmata. Builtin types have all uppercase names, so to prevent confusion, you may wish to avoid such package names as well. Make sure that CLASSNAME is a true value. See Perl Modules in the perlmod manpage.
eval or
require, and the undefined value
otherwise. In list context, returns
($package, $filename, $line) = caller; With EXPR, it returns some extra information that the debugger uses to print a stack trace. The value of EXPR indicates how many call frames to go back before the current one. ($package, $filename, $line, $subroutine, $hasargs,
$wantarray, $evaltext, $is_require, $hints, $bitmask) = caller($i);
Here $subroutine may be Furthermore, when called from within the DB package, caller returns more
detailed information: it sets the list variable Be aware that the optimizer might have optimized call frames away before
$ENV{HOME}, if set; if not,
changes to the directory specified by $ENV{LOGDIR}. If neither is
set, chdir does nothing. It returns
true upon success, false otherwise. See the example under
die.
0644
is okay, '0644' is not. Returns the number of files successfully
changed. See also oct, if all you have is a string.
$cnt = chmod 0755, 'foo', 'bar';
chmod 0755, @executables;
$mode = '0644'; chmod $mode, 'foo'; # !!! sets mode to
# --w----r-T
$mode = '0644'; chmod oct($mode), 'foo'; # this is better
$mode = 0644; chmod $mode, 'foo'; # this is best
You can also import the symbolic use Fcntl ':mode'; chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
# This is identical to the chmod 0755 of the above example.
$/ (also known as $INPUT_RECORD_SEPARATOR in the
English module). It returns the total number of characters removed from
all its arguments. It's often used to remove the newline from the end of an
input record when you're worried that the final record may be missing its
newline. When in paragraph mode ($/ = ""), it removes all
trailing newlines from the string. When in slurp mode ($/ = undef)
or fixed-length record mode ($/
is a reference to an integer or the like, see
the perlvar manpage) chomp() won't
remove anything. If VARIABLE is omitted, it chomps
$_. Example:
while (<>) {
chomp; # avoid \n on last field
@array = split(/:/);
# ...
}
If VARIABLE is a hash, it chomps the hash's values, but not its keys. You can actually chomp anything that's an lvalue, including an assignment: chomp($cwd = `pwd`);
chomp($answer = <STDIN>);
If you chomp a list, each element is chomped, and the total number of characters removed is returned.
s/.$//s
because it neither scans nor copies the string. If VARIABLE is omitted, chops
$_. If VARIABLE is a hash, it chops the hash's values, but
not its keys.
You can actually chop anything that's an lvalue, including an assignment. If you chop a list, each element is chopped. Only the value of the last
Note that
$cnt = chown $uid, $gid, 'foo', 'bar';
chown $uid, $gid, @filenames;
Here's an example that looks up nonnumeric uids in the passwd file: print "User: ";
chomp($user = <STDIN>);
print "Files: ";
chomp($pattern = <STDIN>);
($login,$pass,$uid,$gid) = getpwnam($user)
or die "$user not in passwd file";
@ary = glob($pattern); # expand filenames
chown $uid, $gid, @ary;
On most systems, you are not allowed to change the ownership of the file unless you're the superuser, although you should be able to change the group to any of your secondary groups. On insecure systems, these restrictions may be relaxed, but this is not a portable assumption. On POSIX systems, you can detect this condition this way: use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
$can_chown_giveaway = not sysconf(_PC_CHOWN_RESTRICTED);
chr(65) is "A" in
either ASCII or Unicode, and chr(0x263a)
is a Unicode smiley face (but only within the scope of a use utf8).
For the reverse, use ord. See
the utf8 manpage for more about Unicode.
If NUMBER is omitted, uses
/ by your process and all its children. (It doesn't change
your current working directory, which is unaffected.) For security reasons,
this call is restricted to the superuser. If FILENAME is omitted, does a
chroot to
$_.
You don't have to close FILEHANDLE if you are immediately going to do
another If the file handle came from a piped open Prematurely closing the read end of a pipe (i.e. before the process writing to it at the other end has closed it) will result in a SIGPIPE being delivered to the writer. If the other end can't handle that, be sure to read all the data before closing the pipe. Example: open(OUTPUT, '|sort >foo') # pipe to sort
or die "Can't start sort: $!";
#... # print stuff to output
close OUTPUT # wait for sort to finish
or warn $! ? "Error closing sort pipe: $!"
: "Exit status $? from sort";
open(INPUT, 'foo') # get sort's results
or die "Can't open 'foo' for input: $!";
FILEHANDLE may be an expression whose value can be used as an indirect filehandle, usually the real filehandle name.
opendir
and returns the success of that system call.
DIRHANDLE may be an expression whose value can be used as an indirect dirhandle, usually the real dirhandle name.
continue BLOCK attached to a BLOCK
(typically in a while or foreach), it is always
executed just before the conditional is about to be evaluated again, just like
the third part of a for loop in C. Thus it can be used to
increment a loop variable, even when the loop has been continued via the
next statement (which is similar to the
C continue statement).
while (EXPR) {
### redo always comes here
do_something;
} continue {
### next always comes here
do_something_else;
# then back the top to re-check EXPR
}
### last always comes here
Omitting the
$_.
For the inverse cosine operation, you may use the sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
crypt(3)
function in the C library (assuming that you actually have a version there
that has not been extirpated as a potential munition). This can prove useful
for checking the password file for lousy passwords, amongst other things. Only
the guys wearing white hats should do this.
Note that When verifying an existing encrypted string you should use the encrypted
text as the salt (like Here's an example that makes sure that whoever runs this program knows their own password: $pwd = (getpwuid($<))[1]; system "stty -echo";
print "Password: ";
chomp($word = <STDIN>);
print "\n";
system "stty echo";
if (crypt($word, $pwd) ne $pwd) {
die "Sorry...\n";
} else {
print "ok\n";
}
Of course, typing in your own password to whoever asks you for it is unwise. The crypt function is unsuitable for encrypting large quantities of data, not least of all because you can't get the information back. Look at the by-module/Crypt and by-module/PGP directories on your favorite CPAN mirror for a slew of potentially useful modules.
untie function.]
Breaks the binding between a DBM file and a hash.
tie function.]
This binds a dbm(3), ndbm(3), sdbm(3), gdbm(3), or Berkeley DB file to a
hash. HASH is the name of the hash. (Unlike normal If you don't have write access to the DBM file, you can only read hash
variables, not set them. If you want to test whether you can write, either use
file tests or try setting a dummy hash entry inside an
Note that functions such as # print out history file offsets
dbmopen(%HIST,'/usr/lib/news/history',0666);
while (($key,$val) = each %HIST) {
print $key, ' = ', unpack('L',$val), "\n";
}
dbmclose(%HIST);
See also the AnyDBM_File manpage for a more general description of the pros and cons of the various dbm approaches, as well as DB_File for a particularly rich implementation. You can control which DBM library you use by loading that library before you call dbmopen(): use DB_File;
dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
or die "Can't open netscape history file: $!";
undef. If EXPR is not
present,
$_ will be checked.
Many operations return You may also use Use of if (@an_array) { print "has array elements\n" }
if (%a_hash) { print "has hash members\n" }
When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use exists for the latter purpose. Examples: print if defined $switch{'D'};
print "$val\n" while defined($val = pop(@ary));
die "Can't readlink $sym: $!"
unless defined($value = readlink $sym);
sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
$debugging = 0 unless defined $debugging;
Note: Many folks tend to overuse "ab" =~ /a(.*)b/; The pattern match succeeds, and
element(s) from the
hash or array. In the case of an array, if the array elements happen to be at
the end, the size of the array will shrink to the highest element that tests
true for exists() (or 0 if no such
element exists).
Returns each element so deleted or the undefined value if there was no such
element. Deleting from Deleting an array element effectively returns that position of the array to
its initial, uninitialized state. Subsequently testing for the same element
with The following (inefficiently) deletes all the values of %HASH and @ARRAY: foreach $key (keys %HASH) {
delete $HASH{$key};
}
foreach $index (0 .. $#ARRAY) {
delete $ARRAY[$index];
}
And so do these: delete @HASH{keys %HASH};
delete @ARRAY[0 .. $#ARRAY]; But both of these are slower than just assigning the empty list or undefining %HASH or @ARRAY: %HASH = (); # completely empty %HASH
undef %HASH; # forget %HASH ever existed
@ARRAY = (); # completely empty @ARRAY
undef @ARRAY; # forget @ARRAY ever existed
Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash element, array element, hash slice, or array slice lookup: delete $ref->[$x][$y]{$key};
delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
delete $ref->[$x][$y][$index];
delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];
eval, prints the value of
LIST to STDERR and exits with the current value of
$! (errno). If
$! is 0, exits with the value of ($? >> 8)
(backtick `command` status). If ($? >> 8) is 0,
exits with 255. Inside an eval(),
the error message is stuffed into
$@ and the eval is
terminated with the undefined value. This makes die
the way to raise an exception.
Equivalent examples: die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
If the value of EXPR does not end in a newline, the current script line
number and input line number (if any) are also printed, and a newline is
supplied. Note that the ``input line number'' (also known as ``chunk'') is
subject to whatever notion of ``line'' happens to be currently in effect, and
is also available as the special variable
Hint: sometimes appending die "/etc/games is no good";
die "/etc/games is no good, stopped";
produce, respectively /etc/games is no good at canasta line 123.
/etc/games is no good, stopped at canasta line 123.
See also exit(), warn(), and the Carp module. If LIST is empty and
eval { ... };
die unless $@ =~ /Expected exception/;
If
eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };
if ($@) {
if (ref($@) && UNIVERSAL::isa($@,"Some::Module::Exception")) {
# handle Some::Module::Exception
}
else {
# handle all other possible exceptions
}
}
Because perl will stringify uncaught exception messages before displaying them, you may want to overload stringification operations on such custom exception objects. See the overload manpage for details about that. You can arrange for a callback to be run just before the
die @_ if $^S; as the first line of the handler (see $^S in the perlvar manpage). Because this promotes strange action at a distance, this counterintuitive behavior may be fixed in a future release.
SUBROUTINE(LIST)
do 'stat.pl'; is just like scalar eval `cat stat.pl`; except that it's more efficient and concise, keeps track of the current
filename for error messages, searches the @INC libraries, and updates
If Note that inclusion of library modules is better done with the
You might like to use # read in config files: system first, then user
for $file ("/share/prog/defaults.rc",
"$ENV{HOME}/.someprogrc")
{
unless ($return = do $file) {
warn "couldn't parse $file: $@" if $@;
warn "couldn't do $file: $!" unless defined $return;
warn "couldn't run $file" unless $return;
}
}
goto LABEL
(with all the restrictions that goto
suffers). Think of it as a goto with an intervening core dump and
reincarnation. If LABEL is omitted, restarts the program from the
top.
WARNING: Any files opened at the time of the dump will not be open any more when the program is reincarnated, with possible resulting confusion on the part of Perl. This function is now largely obsolete, partly because it's very hard to convert a core file into an executable, and because the real compiler backends for generating portable bytecode and compilable C code have superseded it. If you're looking to use dump to speed up your
program, consider generating bytecode or native C code as described in
perlcc. If you're just trying to accelerate a CGI script, consider using
the
Entries are returned in an apparently random order. The actual random order
is subject to change in future versions of perl, but it is guaranteed to be in
the same order as either the When the hash is entirely read, a null array is returned in list context
(which when assigned produces a false ( while (($key, $value) = each %hash) {
print $key, "\n";
delete $hash{$key}; # This is safe
}
The following prints out your environment like the while (($key,$value) = each %ENV) {
print "$key=$value\n";
}
See also
ungetcs it, so isn't very useful in an interactive context.) Do
not read from a terminal file (or call
eof(FILEHANDLE) on it) after end-of-file is reached. File types
such as terminals may lose the end-of-file condition if you do.
An In a # reset line numbering on each input file
while (<>) {
next if /^\s*#/; # skip comments
print "$.\t$_";
} continue {
close ARGV if eof; # Not eof()!
}
# insert dashes just before last line of last file
while (<>) {
if (eof()) { # check for end of current file
print "--------------\n";
close(ARGV); # close or last; is needed if we
# are reading from the terminal
}
print;
}
Practical hint: you almost never need to use
$_. This form is typically used to delay parsing and
subsequent execution of the text of EXPR until run time.
In the second form, the code within the BLOCK is parsed only once--at the same time the code surrounding the eval itself was parsed--and executed within the context of the current Perl program. This form is typically used to trap exceptions more efficiently than the first (see below), while also providing the benefit of checking the code within BLOCK at compile time. The final semicolon, if any, may be omitted from the value of EXPR or within the BLOCK. In both forms, the value returned is the value of the last expression evaluated inside the mini-program; a return statement may be also used, just as with subroutines. The expression providing the return value is evaluated in void, scalar, or list context, depending on the context of the eval itself. See wantarray for more on how the evaluation context can be determined. If there is a syntax error or runtime error, or a
Note that, because If the code to be executed doesn't vary, you may use the eval-BLOCK form to
trap run-time errors without incurring the penalty of recompiling each time.
The error, if any, is still returned in
# make divide-by-zero nonfatal
eval { $answer = $a / $b; }; warn $@ if $@;
# same thing, but less efficient
eval '$answer = $a / $b'; warn $@ if $@;
# a compile-time error
eval { $answer = }; # WRONG
# a run-time error
eval '$answer ='; # sets $@
Due to the current arguably broken state of # a very private exception trap for divide-by-zero
eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
warn $@ if $@;
This is especially significant, given that # __DIE__ hooks may modify error messages
{
local $SIG{'__DIE__'} =
sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
eval { die "foo lives here" };
print $@ if $@; # prints "bar lives here"
}
Because this promotes action at a distance, this counterintuitive behavior may be fixed in a future release. With an eval $x; # CASE 1
eval "$x"; # CASE 2
eval '$x'; # CASE 3
eval { $x }; # CASE 4
eval "\$$x++"; # CASE 5
$$x++; # CASE 6
Cases 1 and 2 above behave identically: they run the code contained in the
variable $x. (Although case 2 has misleading double quotes making the reader
wonder what else might be happening (nothing is).) Cases 3 and 4 likewise
behave in the same way: they run the code
exec function executes a system
command and never returns-- use system
instead of exec if you want it to
return. It fails and returns false only if the command does not exist and
it is executed directly instead of via your system's command shell (see
below).
Since it's a common mistake to use exec ('foo') or print STDERR "couldn't exec foo: $!";
{ exec ('foo') }; print STDERR "couldn't exec foo: $!";
If there is more than one argument in LIST, or if LIST is an array with
more than one value, calls exec '/bin/echo', 'Your arguments are: ', @ARGV;
exec "sort $outfile | uniq";
If you don't really want to execute the first argument, but want to lie to the program you are executing about its own name, you can specify the program you actually want to run as an ``indirect object'' (without a comma) in front of the LIST. (This always forces interpretation of the LIST as a multivalued list, even if there is only a single scalar in the list.) Example: $shell = '/bin/csh';
exec $shell '-sh'; # pretend it's a login shell
or, more directly, exec {'/bin/csh'} '-sh'; # pretend it's a login shell
When the arguments get executed via the system shell, results will be subject to its quirks and capabilities. See `STRING` in the perlop manpage for details. Using an indirect object with @args = ( "echo surprise" ); exec @args; # subject to shell escapes
# if @args == 1
exec { $args[0] } @args; # safe even with one-arg list
The first version, the one without the indirect object, ran the echo
program, passing it Beginning with v5.6.0, Perl will attempt to flush all files opened for
output before the exec, but this may not be supported on some platforms (see
the perlport manpage). To be safe, you may need to set
Note that
print "Exists\n" if exists $hash{$key};
print "Defined\n" if defined $hash{$key};
print "True\n" if $hash{$key};
print "Exists\n" if exists $array[$index];
print "Defined\n" if defined $array[$index];
print "True\n" if $array[$index];
A hash or array element can be true only if it's defined, and defined if it exists, but the reverse doesn't necessarily hold true. Given an expression that specifies the name of a subroutine, returns true
if the specified subroutine has ever been declared, even if it is undefined.
Mentioning a subroutine name for exists or defined does not count as declaring
it. Note that a subroutine which does not exist may still be callable: its
package may have an print "Exists\n" if exists &subroutine;
print "Defined\n" if defined &subroutine;
Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash or array key lookup or subroutine name: if (exists $ref->{A}->{B}->{$key}) { }
if (exists $hash{A}{B}{$key}) { }
if (exists $ref->{A}->{B}->[$ix]) { }
if (exists $hash{A}{B}[$ix]) { }
if (exists &{$ref->{A}{B}{$key}}) { }
Although the deepest nested array or hash will not spring into existence
just because its existence was tested, any intervening ones will. Thus undef $ref;
if (exists $ref->{"Some key"}) { }
print $ref; # prints HASH(0x80d3d5c)
This surprising autovivification in what does not at first--or even second--glance appear to be an lvalue context may be fixed in a future release. See
Pseudo-hashes: Using an array as a hash in the perlref manpage for
specifics on how Use of a subroutine call, rather than a subroutine name, as an argument to
exists ⊂ # OK
exists &sub(); # Error
$ans = <STDIN>;
exit 0 if $ans =~ /^[Xx]/;
See also Don't use The
exp($_).
fcntl(2) function.
You'll probably have to say
use Fcntl; first to get the correct constant definitions. Argument processing and
value return works just like use Fcntl;
fcntl($filehandle, F_GETFL, $packed_return_buffer)
or die "can't fcntl F_GETFL: $!";
You don't have to check for Note that
select and low-level POSIX
tty-handling operations. If FILEHANDLE is an expression, the value is taken as
an indirect filehandle, generally its name.
You can use this to find out whether two handles refer to the same underlying descriptor: if (fileno(THIS) == fileno(THAT)) {
print "THIS and THAT are dups\n";
}
fcntl(2)
locking, or lockf(3). flock is Perl's
portable file locking interface, although it locks only entire files, not
records.
Two potentially non-obvious but traditional OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with
LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but you can
use the symbolic names if you import them from the Fcntl module, either
individually, or as a group using the ':flock' tag. LOCK_SH requests a shared
lock, LOCK_EX requests an exclusive lock, and LOCK_UN releases a previously
requested lock. If LOCK_NB is bitwise-or'ed with LOCK_SH or LOCK_EX then
To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE before locking or unlocking it. Note that the emulation built with Note also that some versions of Here's a mailbox appender for BSD systems. use Fcntl ':flock'; # import LOCK_* constants sub lock {
flock(MBOX,LOCK_EX);
# and, in case someone appended
# while we were waiting...
seek(MBOX, 0, 2);
}
sub unlock {
flock(MBOX,LOCK_UN);
}
open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
or die "Can't open mailbox: $!";
lock();
print MBOX $msg,"\n\n";
unlock();
On systems that support a real flock(), locks are inherited across
See also DB_File for other
fork(2) system call to create
a new process running the same program at the same point. It returns the child
pid to the parent process, 0 to the child process, or
undef if the fork is unsuccessful. File
descriptors (and sometimes locks on those descriptors) are shared, while
everything else is copied. On most systems supporting fork(), great care has
gone into making it extremely efficient (for example, using copy-on-write
technology on data pages), making it the dominant paradigm for multitasking
over the last few decades.
Beginning with v5.6.0, Perl will attempt to flush all files opened for
output before forking the child process, but this may not be supported on some
platforms (see
the perlport manpage). To be safe, you may need to set
If you Note that if your forked child inherits system file descriptors like STDIN and STDOUT that are actually connected by a pipe or socket, even if you exit, then the remote server (such as, say, a CGI script or a backgrounded job launched from a remote shell) won't think you're done. You should reopen those to /dev/null if it's any issue.
write
function. For example:
format Something =
Test: @<<<<<<<< @||||| @>>>>>
$str, $%, '$' . int($num)
.
$str = "widget";
$num = $cost/$quantity;
$~ = 'Something';
write;
See the perlform manpage for many details and examples.
formats,
though you may call it, too. It formats (see
the perlform manpage) a list of values according to the contents of
PICTURE, placing the output into the format output accumulator,
$^A (or
$ACCUMULATOR in English). Eventually, when a
write is done, the contents of
$^A are written to some filehandle, but you could also read
$^A yourself and then set
$^A back to "". Note that a format typically
does one formline per line of form,
but the formline function itself
doesn't care how many newlines are embedded in the PICTURE. This means that
the ~ and ~~ tokens will treat the entire PICTURE as
a single line. You may therefore need to use multiple formlines to implement a
single record format, just like the |