perlfunc.pod

来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,705 行 · 第 1/5 页

POD
1,705
字号

For delays of finer granularity than one second, you may use Perl's
C<syscall()> interface to access setitimer(2) if your system supports it,
or else see L</select()>.  It is usually a mistake to intermix C<alarm()>
and C<sleep()> calls.

If you want to use C<alarm()> to time out a system call you need to use an
C<eval()>/C<die()> pair.  You can't rely on the alarm causing the system call to
fail with C<$!> set to C<EINTR> because Perl sets up signal handlers to
restart system calls on some systems.  Using C<eval()>/C<die()> always works,
modulo the caveats given in L<perlipc/"Signals">.

    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
    }

=item atan2 Y,X

Returns the arctangent of Y/X in the range -PI to PI.

For the tangent operation, you may use the C<POSIX::tan()>
function, or use the familiar relation:

    sub tan { sin($_[0]) / cos($_[0])  }

=item bind SOCKET,NAME

Binds a network address to a socket, just as the bind system call
does.  Returns TRUE if it succeeded, FALSE otherwise.  NAME should be a
packed address of the appropriate type for the socket.  See the examples in
L<perlipc/"Sockets: Client/Server Communication">.

=item binmode FILEHANDLE

Arranges for the file to be read or written in "binary" mode in operating
systems that distinguish between binary and text files.  Files that are
not in binary mode have CR LF sequences translated to LF on input and LF
translated to CR LF on output.  Binmode has no effect under Unix; in MS-DOS
and similarly archaic systems, it may be imperative--otherwise your
MS-DOS-damaged C library may mangle your file.  The key distinction between
systems that need C<binmode()> and those that don't is their text file
formats.  Systems like Unix, MacOS, and Plan9 that delimit lines with a single
character, and that encode that character in C as C<"\n">, do not need
C<binmode()>.  The rest need it.  If FILEHANDLE is an expression, the value
is taken as the name of the filehandle.

=item bless REF,CLASSNAME

=item bless REF

This function tells the thingy referenced by REF that it is now
an object in the CLASSNAME package--or the current package if no CLASSNAME
is specified, which is often the case.  It returns the reference for
convenience, because a C<bless()> is often the last thing in a constructor.
Always use the two-argument version if the function doing the blessing
might be inherited by a derived class.  See L<perltoot> and L<perlobj>
for more about the blessing (and blessings) of objects.

=item caller EXPR

=item caller

Returns the context of the current subroutine call.  In scalar context,
returns the caller's package name if there is a caller, that is, if
we're in a subroutine or C<eval()> or C<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) = caller($i);

Here C<$subroutine> may be C<"(eval)"> if the frame is not a subroutine
call, but an C<eval()>.  In such a case additional elements C<$evaltext> and
C<$is_require> are set: C<$is_require> is true if the frame is created by a
C<require> or C<use> statement, C<$evaltext> contains the text of the
C<eval EXPR> statement.  In particular, for a C<eval BLOCK> statement,
C<$filename> is C<"(eval)">, but C<$evaltext> is undefined.  (Note also that
each C<use> statement creates a C<require> frame inside an C<eval EXPR>)
frame.

Furthermore, when called from within the DB package, caller returns more
detailed information: it sets the list variable C<@DB::args> to be the
arguments with which the subroutine was invoked.

Be aware that the optimizer might have optimized call frames away before
C<caller()> had a chance to get the information. That means that C<caller(N)>
might not return information about the call frame you expect it do, for
C<N E<gt> 1>. In particular, C<@DB::args> might have information from the 
previous time C<caller()> was called.

=item chdir EXPR

Changes the working directory to EXPR, if possible.  If EXPR is
omitted, changes to home directory.  Returns TRUE upon success, FALSE
otherwise.  See example under C<die()>.

=item chmod LIST

Changes the permissions of a list of files.  The first element of the
list must be the numerical mode, which should probably be an octal
number, and which definitely should I<not> a string of octal digits:
C<0644> is okay, C<'0644'> is not.  Returns the number of files
successfully changed.  See also L</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

=item chomp VARIABLE

=item chomp LIST

=item chomp

This is a slightly safer version of L</chop>.  It removes any
line ending that corresponds to the current value of C<$/> (also known as
$INPUT_RECORD_SEPARATOR in the C<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
(C<$/ = "">), it removes all trailing newlines from the string.  If
VARIABLE is omitted, it chomps C<$_>.  Example:

    while (<>) {
	chomp;	# avoid \n on last field
	@array = split(/:/);
	# ...
    }

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.

=item chop VARIABLE

=item chop LIST

=item chop

Chops off the last character of a string and returns the character
chopped.  It's used primarily to remove the newline from the end of an
input record, but is much more efficient than C<s/\n//> because it neither
scans nor copies the string.  If VARIABLE is omitted, chops C<$_>.
Example:

    while (<>) {
	chop;	# avoid \n on last field
	@array = split(/:/);
	#...
    }

You can actually chop anything that's an lvalue, including an assignment:

    chop($cwd = `pwd`);
    chop($answer = <STDIN>);

If you chop a list, each element is chopped.  Only the value of the
last C<chop()> is returned.

Note that C<chop()> returns the last character.  To return all but the last
character, use C<substr($string, 0, -1)>.

=item chown LIST

Changes the owner (and group) of a list of files.  The first two
elements of the list must be the I<NUMERICAL> uid and gid, in that order.
Returns the number of files successfully changed.

    $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: ";
    chop($user = <STDIN>);
    print "Files: ";
    chop($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.

=item chr NUMBER

=item chr

Returns the character represented by that NUMBER in the character set.
For example, C<chr(65)> is C<"A"> in ASCII.  For the reverse, use L</ord>.

If NUMBER is omitted, uses C<$_>.

=item chroot FILENAME

=item chroot

This function works like the system call by the same name: it makes the
named directory the new root directory for all further pathnames that
begin with a C<"/"> 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 C<chroot()> to C<$_>.

=item close FILEHANDLE

=item close

Closes the file or pipe associated with the file handle, returning TRUE
only if stdio successfully flushes buffers and closes the system file
descriptor. Closes the currently selected filehandle if the argument
is omitted.

You don't have to close FILEHANDLE if you are immediately going to do
another C<open()> on it, because C<open()> will close it for you.  (See
C<open()>.)  However, an explicit C<close()> on an input file resets the line
counter (C<$.>), while the implicit close done by C<open()> does not.

If the file handle came from a piped open C<close()> will additionally
return FALSE if one of the other system calls involved fails or if the
program exits with non-zero status.  (If the only problem was that the
program exited non-zero C<$!> will be set to C<0>.)  Also, closing a pipe 
waits for the process executing on the pipe to complete, in case you
want to look at the output of the pipe afterwards.  Closing a pipe
explicitly also puts the exit status value of the command into C<$?>.

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.

=item closedir DIRHANDLE

Closes a directory opened by C<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.

=item connect SOCKET,NAME

Attempts to connect to a remote socket, just as the connect system call
does.  Returns TRUE if it succeeded, FALSE otherwise.  NAME should be a
packed address of the appropriate type for the socket.  See the examples in
L<perlipc/"Sockets: Client/Server Communication">.

=item continue BLOCK

Actually a flow control statement rather than a function.  If there is a
C<continue> BLOCK attached to a BLOCK (typically in a C<while> or
C<foreach>), it is always executed just before the conditional is about to
be evaluated again, just like the third part of a C<for> loop in C.  Thus
it can be used to increment a loop variable, even when the loop has been
continued via the C<next> statement (which is similar to the C C<continue>
statement).

C<last>, C<next>, or C<redo> may appear within a C<continue>
block. C<last> and C<redo> will behave as if they had been executed within
the main block. So will C<next>, but since it will execute a C<continue>
block, it may be more entertaining.

    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 C<continue> section is semantically equivalent to using an
empty one, logically enough. In that case, C<next> goes directly back
to check the condition at the top of the loop.

=item cos EXPR

Returns the cosine of EXPR (expressed in radians).  If EXPR is omitted,
takes cosine of C<$_>.

For the inverse cosine operation, you may use the C<POSIX::acos()>
function, or use this relation:

    sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }

=item crypt PLAINTEXT,SALT

Encrypts a string exactly like the 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 C<crypt()> is intended to be a one-way function, much like breaking
eggs to make an omelette.  There is no (known) corresponding decrypt
function.  As a result, this function isn't all that useful for
cryptography.  (For that, see your nearby CPAN mirror.)

Here's an example that makes sure that whoever runs this program knows
their own password:

    $pwd = (getpwuid($<))[1];
    $salt = substr($pwd, 0, 2);

    system "stty -echo";

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?