perlfunc.pod

来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 1,629 行 · 第 1/5 页

POD
1,629
字号
X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password>X<decrypt> X<cryptography> X<passwd> X<encrypt>Creates a digest string exactly like the crypt(3) function in the Clibrary (assuming that you actually have a version there that has notbeen extirpated as a potential munitions).crypt() is a one-way hash function.  The PLAINTEXT and SALT is turnedinto a short string, called a digest, which is returned.  The samePLAINTEXT and SALT will always return the same string, but there is no(known) way to get the original PLAINTEXT from the hash.  Smallchanges in the PLAINTEXT or SALT will result in large changes in thedigest.There is no decrypt function.  This function isn't all that useful forcryptography (for that, look for F<Crypt> modules on your nearby CPANmirror) and the name "crypt" is a bit of a misnomer.  Instead it isprimarily used to check if two pieces of text are the same withouthaving to transmit or store the text itself.  An example is checkingif a correct password is given.  The digest of the password is stored,not the password itself.  The user types in a password that iscrypt()'d with the same salt as the stored digest.  If the two digestsmatch the password is correct.When verifying an existing digest string you should use the digest asthe salt (like C<crypt($plain, $digest) eq $digest>).  The SALT usedto create the digest is visible as part of the digest.  This ensurescrypt() will hash the new string with the same salt as the digest.This allows your code to work with the standard L<crypt|/crypt> andwith more exotic implementations.  In other words, do not assumeanything about the returned string itself, or how many bytes in thedigest matter.Traditionally the result is a string of 13 bytes: two first bytes ofthe salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and onlythe first eight bytes of the digest string mattered, but alternativehashing schemes (like MD5), higher level security schemes (like C2),and implementations on non-UNIX platforms may produce differentstrings.When choosing a new salt create a random two character string whosecharacters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.','/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>).  This set ofcharacters is just a recommendation; the characters allowed inthe salt depend solely on your system's crypt library, and Perl can'trestrict what salts C<crypt()> accepts.Here's an example that makes sure that whoever runs this program knowstheir 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|/crypt> function is unsuitable for hashing large quantitiesof data, not least of all because you can't get the informationback.  Look at the L<Digest> module for more robust algorithms.If using crypt() on a Unicode string (which I<potentially> hascharacters with codepoints above 255), Perl tries to make senseof the situation by trying to downgrade (a copy of the string)the string back to an eight-bit byte string before calling crypt()(on that copy).  If that works, good.  If not, crypt() dies withC<Wide character in crypt>.=item dbmclose HASHX<dbmclose>[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,MASKX<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm>[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 EXPRX<defined> X<undef> X<undefined>=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<&func>.  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".  It didn't really fail to match anything.  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 EXPRX<delete>Given 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 teststrue for exists() (or 0 if no such element exists).Returns a list with the same number of elements as the number of elementsfor which deletion was attempted.  Each element of that list consists ofeither the value of the element deleted, or the undefined value.  In scalarcontext, this means that you get the value of the last element deleted (orthe undefined value if that element did not exist).    %hash = (foo => 11, bar => 22, baz => 33);    $scalar = delete $hash{foo};             # $scalar is 11    $scalar = delete @hash{qw(foo bar)};     # $scalar is 22    @array  = delete @hash{qw(foo bar baz)}; # @array  is (undef,undef,33)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.  Also, deleting array elementsin the middle of an array will not shift the index of the elementsafter them down.  Use splice() for that.  See L</exists>.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 listor undefining %HASH or @ARRAY:    %HASH = ();		# completely empty %HASH    undef %HASH;	# forget %HASH ever existed    @ARRAY = ();	# completely empty @ARRAY    undef @ARRAY;	# forget @ARRAY ever existedNote that the EXPR can be arbitrarily complicated as long as the finaloperation is a hash element, array element,  hash slice, or array slicelookup:    delete $ref->[$x][$y]{$key};    delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};    delete $ref->[$x][$y][$index];    delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];=item die LISTX<die> X<throw> X<exception> X<raise> X<$@> X<abort>Outside an C<eval>, prints the value of LIST to C<STDERR> andexits with the current value of C<$!> (errno).  If C<$!> is C<0>,exits with the value of C<<< ($? >> 8) >>> (backtick `command`status).  If C<<< ($? >> 8) >>> is C<0>, exits with C<255>.  Insidean C<eval(),> the error message is stuffed into C<$@> and theC<eval> is terminated with the undefined value.  This makesC<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 last element of LIST does not end in a newline, the currentscript line number and input line number (if any) are also printed,and a newline is supplied.  Note that the "input line number" (alsoknown as "chunk") is subject to whatever notion of "line" happens tobe currently in effect, and is also available as the special variableC<$.>.  See L<perlvar/"$/"> and L<perlvar/"$.">.Hint: sometimes appending C<", stopped"> to your message will cause itto make better sense when the string C<"at foo line 123"> is appended.Suppose you are running script "canasta".    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 C<$@> already contains a value (typically from aprevious eval) that value is reused after appending C<"\t...propagated">.This is useful for propagating exceptions:    eval { ... };    die unless $@ =~ /Expected exception/;If LIST is empty and C<$@> contains an object reference that has aC<PROPAGATE> method, that method will be called with additional fileand line number parameters.  The return value replaces the value inC<$@>.  i.e. as if C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >>were called.If C<$@> is empty then the string C<"Died"> is used.die() can also be called with a reference argument.  If this happens to betrapped within an eval(), $@ contains the reference.  This behavior permitsa more elaborate exception handling implementation using objects thatmaintain arbitrary state about the nature of the exception.  Such a schemeis sometimes preferable to matching particular string values of $@ usingregular expressions.  Because $@ is a global variable, and eval() may beused within object implementations, care must be taken that analyzing theerror object doesn't replace the reference in the global variable.  Theeasiest solution is to make a local copy of the reference before doingother manipulations.  Here's an example:    use Scalar::Util 'blessed';    eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };    if (my $ev_err = $@) {        if (blessed($ev_err) && $ev_err->isa("Some::Module::Exception")) {            # handle Some::Module::Exception

⌨️ 快捷键说明

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