perlfunc.pod
来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 1,621 行 · 第 1/5 页
POD
1,621 行
$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 thefile unless you're the superuser, although you should be able to changethe group to any of your secondary groups. On insecure systems, theserestrictions 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);=item chr NUMBER=item chrReturns the character represented by that NUMBER in the character set.For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, andchr(0x263a) is a Unicode smiley face (but only within the scope ofa C<use utf8>). For the reverse, use L</ord>. See L<utf8> for more about Unicode.If NUMBER is omitted, uses C<$_>.=item chroot FILENAME=item chrootThis function works like the system call by the same name: it makes thenamed directory the new root directory for all further pathnames thatbegin with a C</> by your process and all its children. (It doesn'tchange your current working directory, which is unaffected.) For securityreasons, this call is restricted to the superuser. If FILENAME isomitted, does a C<chroot> to C<$_>.=item close FILEHANDLE=item closeCloses the file or pipe associated with the file handle, returning trueonly if stdio successfully flushes buffers and closes the system filedescriptor. Closes the currently selected filehandle if the argumentis omitted.You don't have to close FILEHANDLE if you are immediately going to doanother C<open> on it, because C<open> will close it for you. (SeeC<open>.) However, an explicit C<close> on an input file resets the linecounter (C<$.>), while the implicit close done by C<open> does not.If the file handle came from a piped open C<close> will additionallyreturn false if one of the other system calls involved fails or if theprogram exits with non-zero status. (If the only problem was that theprogram exited non-zero C<$!> will be set to C<0>.) Closing a pipe also waits for the process executing on the pipe to complete, in case youwant to look at the output of the pipe afterwards, and implicitly puts the exit status value of that command into C<$?>.Prematurely closing the read end of a pipe (i.e. before the processwriting to it at the other end has closed it) will result in aSIGPIPE being delivered to the writer. If the other end can'thandle 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 indirectfilehandle, usually the real filehandle name.=item closedir DIRHANDLECloses a directory opened by C<opendir> and returns the success of thatsystem call.DIRHANDLE may be an expression whose value can be used as an indirectdirhandle, usually the real dirhandle name.=item connect SOCKET,NAMEAttempts to connect to a remote socket, just as the connect system calldoes. Returns true if it succeeded, false otherwise. NAME should be apacked address of the appropriate type for the socket. See the examples inL<perlipc/"Sockets: Client/Server Communication">.=item continue BLOCKActually a flow control statement rather than a function. If there is aC<continue> BLOCK attached to a BLOCK (typically in a C<while> orC<foreach>), it is always executed just before the conditional is about tobe evaluated again, just like the third part of a C<for> loop in C. Thusit can be used to increment a loop variable, even when the loop has beencontinued 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 withinthe 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 hereOmitting the C<continue> section is semantically equivalent to using anempty one, logically enough. In that case, C<next> goes directly backto check the condition at the top of the loop.=item cos EXPR=item cosReturns 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<Math::Trig::acos()>function, or use this relation: sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }=item crypt PLAINTEXT,SALTEncrypts a string exactly like the crypt(3) function in the C library(assuming that you actually have a version there that has not beenextirpated as a potential munition). This can prove useful for checkingthe password file for lousy passwords, amongst other things. Only theguys wearing white hats should do this.Note that C<crypt> is intended to be a one-way function, much like breakingeggs to make an omelette. There is no (known) corresponding decryptfunction. As a result, this function isn't all that useful forcryptography. (For that, see your nearby CPAN mirror.)When verifying an existing encrypted string you should use the encryptedtext as the salt (like C<crypt($plain, $crypted) eq $crypted>). Thisallows your code to work with the standard C<crypt> and with moreexotic implementations. When choosing a new salt create a random twocharacter string whose characters come from the set C<[./0-9A-Za-z]>(like C<join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>).Here's an example that makes sure that whoever runs this program knowstheir 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 youfor it is unwise.The L<crypt> function is unsuitable for encrypting large quantitiesof data, not least of all because you can't get the informationback. Look at the F<by-module/Crypt> and F<by-module/PGP> directorieson your favorite CPAN mirror for a slew of potentially usefulmodules.=item dbmclose HASH[This function has been largely superseded by the C<untie> function.]Breaks the binding between a DBM file and a hash.=item dbmopen HASH,DBNAME,MASK[This function has been largely superseded by the C<tie> function.]This binds a dbm(3), ndbm(3), sdbm(3), gdbm(3), or Berkeley DB file to ahash. HASH is the name of the hash. (Unlike normal C<open>, the firstargument is I<not> a filehandle, even though it looks like one). DBNAMEis the name of the database (without the F<.dir> or F<.pag> extension ifany). If the database does not exist, it is created with protectionspecified by MASK (as modified by the C<umask>). If your system supportsonly the older DBM functions, you may perform only one C<dbmopen> in yourprogram. In older versions of Perl, if your system had neither DBM norndbm, calling C<dbmopen> produced a fatal error; it now falls back tosdbm(3).If you don't have write access to the DBM file, you can only read hashvariables, 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 C<eval>,which will trap the error.Note that functions such as C<keys> and C<values> may return huge listswhen used on large DBM files. You may prefer to use the C<each>function to iterate over large DBM files. Example: # 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 L<AnyDBM_File> for a more general description of the pros andcons of the various dbm approaches, as well as L<DB_File> for a particularlyrich implementation.You can control which DBM library you use by loading that librarybefore you call dbmopen(): use DB_File; dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") or die "Can't open netscape history file: $!";=item defined EXPR=item definedReturns a Boolean value telling whether EXPR has a value other thanthe undefined value C<undef>. If EXPR is not present, C<$_> will bechecked.Many operations return C<undef> to indicate failure, end of file,system error, uninitialized variable, and other exceptionalconditions. This function allows you to distinguish C<undef> fromother values. (A simple Boolean test will not distinguish amongC<undef>, zero, the empty string, and C<"0">, which are all equallyfalse.) Note that since C<undef> is a valid scalar, its presencedoesn't I<necessarily> indicate an exceptional condition: C<pop>returns C<undef> when its argument is an empty array, I<or> when theelement to return happens to be C<undef>.You may also use C<defined(&func)> to check whether subroutine C<&func>has ever been defined. The return value is unaffected by any forwarddeclarations of C<&foo>. Note that a subroutine which is not definedmay still be callable: its package may have an C<AUTOLOAD> method thatmakes it spring into existence the first time that it is called -- seeL<perlsub>.Use of C<defined> on aggregates (hashes and arrays) is deprecated. Itused to report whether memory for that aggregate has ever beenallocated. This behavior may disappear in future versions of Perl.You should instead use a simple test for size: 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 L</exists> for the latterpurpose.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 C<defined>, and then are surprised todiscover that the number C<0> and C<""> (the zero-length string) are, in fact,defined values. For example, if you say "ab" =~ /a(.*)b/;The pattern match succeeds, and C<$1> is defined, despite the fact that itmatched "nothing". But it didn't really match nothing--rather, itmatched something that happened to be zero characters long. This is allvery above-board and honest. When a function returns an undefined value,it's an admission that it couldn't give you an honest answer. So youshould use C<defined> only when you're questioning the integrity of whatyou're trying to do. At other times, a simple comparison to C<0> or C<""> iswhat you want.See also L</undef>, L</exists>, L</ref>.=item delete EXPRGiven an expression that specifies a hash element, array element, hash slice,or array slice, deletes the specified 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 suchelement. Deleting from C<$ENV{}> modifies the environment. Deleting froma hash tied to a DBM file deletes the entry from the DBM file. Deletingfrom a C<tie>d hash or array may not necessarily return anything.Deleting an array element effectively returns that position of the arrayto its initial, uninitialized state. Subsequently testing for the sameelement with exists() will return false. Note that deleting arrayelements in the middle of an array will not shift the index of the onesafter them down--use splice() for that. See L</exists>.The following (inefficiently) deletes all the values of %HASH and @ARRAY: foreach $key (keys %HASH) {
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?