perlfunc.pod
来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,705 行 · 第 1/5 页
POD
1,705 行
print "Password: ";
chop($word = <STDIN>);
print "\n";
system "stty echo";
if (crypt($word, $salt) ne $pwd) {
die "Sorry...\n";
} else {
print "ok\n";
}
Of course, typing in your own password to whoever asks you
for it is unwise.
=item dbmclose HASH
[This function has been superseded by the C<untie()> function.]
Breaks the binding between a DBM file and a hash.
=item dbmopen HASH,DBNAME,MODE
[This function has been superseded by the C<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 C<open()>, the first
argument is I<NOT> a filehandle, even though it looks like one). DBNAME
is the name of the database (without the F<.dir> or F<.pag> extension if
any). If the database does not exist, it is created with protection
specified by MODE (as modified by the C<umask()>). If your system supports
only the older DBM functions, you may perform only one C<dbmopen()> in your
program. In older versions of Perl, if your system had neither DBM nor
ndbm, calling C<dbmopen()> produced a fatal error; it now falls back to
sdbm(3).
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 C<eval()>,
which will trap the error.
Note that functions such as C<keys()> and C<values()> may return huge lists
when 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 and
cons of the various dbm approaches, as well as L<DB_File> for a particularly
rich implementation.
=item defined EXPR
=item defined
Returns a Boolean value telling whether EXPR has a value other than
the undefined value C<undef>. If EXPR is not present, C<$_> will be
checked.
Many operations return C<undef> to indicate failure, end of file,
system error, uninitialized variable, and other exceptional
conditions. This function allows you to distinguish C<undef> from
other values. (A simple Boolean test will not distinguish among
C<undef>, zero, the empty string, and C<"0">, which are all equally
false.) Note that since C<undef> is a valid scalar, its presence
doesn't I<necessarily> indicate an exceptional condition: C<pop()>
returns C<undef> when its argument is an empty array, I<or> when the
element to return happens to be C<undef>.
You may also use C<defined()> to check whether a subroutine exists, by
saying C<defined &func> without parentheses. On the other hand, use
of C<defined()> upon aggregates (hashes and arrays) is not guaranteed to
produce intuitive results, and should probably be avoided.
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 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 C<defined()>, and then are surprised to
discover 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 it
matched "nothing". But it didn't really match nothing--rather, it
matched something that happened to be C<0> characters long. This is all
very 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 you
should use C<defined()> only when you're questioning the integrity of what
you're trying to do. At other times, a simple comparison to C<0> or C<""> is
what you want.
Currently, using C<defined()> on an entire array or hash reports whether
memory for that aggregate has ever been allocated. So an array you set
to the empty list appears undefined initially, and one that once was full
and that you then set to the empty list still appears defined. 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" }
Using C<undef()> on these, however, does clear their memory and then report
them as not defined anymore, but you shouldn't do that unless you don't
plan to use them again, because it saves time when you load them up
again to have memory already ready to be filled. The normal way to
free up space used by an aggregate is to assign the empty list.
This counterintuitive behavior of C<defined()> on aggregates may be
changed, fixed, or broken in a future release of Perl.
See also L</undef>, L</exists>, L</ref>.
=item delete EXPR
Deletes the specified key(s) and their associated values from a hash.
For each key, returns the deleted value associated with that key, or
the undefined value if there was no such key. Deleting from C<$ENV{}>
modifies the environment. Deleting from a hash tied to a DBM file
deletes the entry from the DBM file. (But deleting from a C<tie()>d hash
doesn't necessarily return anything.)
The following deletes all the values of a hash:
foreach $key (keys %HASH) {
delete $HASH{$key};
}
And so does this:
delete @HASH{keys %HASH}
(But both of these are slower than just assigning the empty list, or
using C<undef()>.) Note that the EXPR can be arbitrarily complicated as
long as the final operation is a hash element lookup or hash slice:
delete $ref->[$x][$y]{$key};
delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
=item die LIST
Outside an C<eval()>, prints the value of LIST to C<STDERR> and exits with
the current value of C<$!> (errno). If C<$!> is C<0>, exits with the value of
C<($? E<gt>E<gt> 8)> (backtick `command` status). If C<($? E<gt>E<gt> 8)>
is C<0>, exits with C<255>. Inside an C<eval(),> the error message is stuffed into
C<$@> and the C<eval()> is terminated with the undefined value. This makes
C<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. Hint: sometimes appending C<", stopped"> to your message
will cause it to 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 C<exit()> and C<warn()>.
If LIST is empty and C<$@> already contains a value (typically from a
previous eval) that value is reused after appending C<"\t...propagated">.
This is useful for propagating exceptions:
eval { ... };
die unless $@ =~ /Expected exception/;
If C<$@> is empty then the string C<"Died"> is used.
You can arrange for a callback to be run just before the C<die()> does
its deed, by setting the C<$SIG{__DIE__}> hook. The associated handler
will be called with the error text and can change the error message, if
it sees fit, by calling C<die()> again. See L<perlvar/$SIG{expr}> for details on
setting C<%SIG> entries, and L<"eval BLOCK"> for some examples.
Note that the C<$SIG{__DIE__}> hook is called even inside eval()ed
blocks/strings. If one wants the hook to do nothing in such
situations, put
die @_ if $^S;
as the first line of the handler (see L<perlvar/$^S>).
=item do BLOCK
Not really a function. Returns the value of the last command in the
sequence of commands indicated by BLOCK. When modified by a loop
modifier, executes the BLOCK once before testing the loop condition.
(On other statements the loop modifiers test the conditional first.)
=item do SUBROUTINE(LIST)
A deprecated form of subroutine call. See L<perlsub>.
=item do EXPR
Uses the value of EXPR as a filename and executes the contents of the
file as a Perl script. Its primary use is to include subroutines
from a Perl subroutine library.
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, and searches all the B<-I>
libraries if the file isn't in the current directory (see also the @INC
array in L<perlvar/Predefined Names>). It is also different in how
code evaluated with C<do FILENAME> doesn't see lexicals in the enclosing
scope like C<eval STRING> does. It's the same, however, in that it does
reparse the file every time you call it, so you probably don't want to
do this inside a loop.
If C<do> cannot read the file, it returns undef and sets C<$!> to the
error. If C<do> can read the file but cannot compile it, it
returns undef and sets an error message in C<$@>. If the file is
successfully compiled, C<do> returns the value of the last expression
evaluated.
Note that inclusion of library modules is better done with the
C<use()> and C<require()> operators, which also do automatic error checking
and raise an exception if there's a problem.
You might like to use C<do> to read in a program configuration
file. Manual error checking can be done this way:
# 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;
}
}
=item dump LABEL
This causes an immediate core dump. Primarily this is so that you can
use the B<undump> program to turn your core dump into an executable binary
after having initialized all your variables at the beginning of the
program. When the new binary is executed it will begin by executing a
C<goto LABEL> (with all the restrictions that C<goto> suffers). Think of
it as a goto with an intervening core dump and reincarnation. If C<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. See also B<-u> option in L<perlrun>.
Example:
#!/usr/bin/perl
require 'getopt.pl';
require 'stat.pl';
%days = (
'Sun' => 1,
'Mon' => 2,
'Tue' => 3,
'Wed' => 4,
'Thu' => 5,
'Fri' => 6,
'Sat' => 7,
);
dump QUICKSTART if $ARGV[0] eq '-d';
QUICKSTART:
Getopt('f');
This operator is largely obsolete, partly because it's very hard to
convert a core file into an executable, and because the real perl-to-C
compiler has superseded it.
=item each HASH
When called in list context, returns a 2-element list consisting of the
key and value for the next element of a hash, so that you can iterate over
it. When called in scalar context, returns the key for only the "next"
element in the hash. (Note: Keys may be C<"0"> or C<"">, which are logically
false; you may wish to avoid constructs like C<while ($k = each %foo) {}>
for this reason.)
Entries are returned in an apparently random order. When the hash is
entirely read, a null array is returned in list context (which when
assigned produces a FALSE (C<0>) value), and C<undef> in
scalar context. The next call to C<each()> after that will start iterating
again. There is a single iterator for each hash, shared by all C<each()>,
C<keys()>, and C<values()> function calls in the program; it can be reset by
reading all the elements from the hash, or by evaluating C<keys HASH> or
C<values HASH>. If you add or delete elements of a hash while you're
iterating over it, you may get entries skipped or duplicated, so don't.
The following prints out your environment like the printenv(1) program,
only in a different order:
while (($key,$value) = each %ENV) {
print "$key=$value\n";
}
See also C<keys()> and C<values()>.
=item eof FILEHANDLE
=item eof ()
=item eof
Returns 1 if the next read on FILEHANDLE will return end of file, or if
FILEHANDLE is not open. FILEHANDLE may be an expression whose value
gives the real filehandle. (Note that this function actually
reads a character and then C<ungetc()>s it, so isn't very useful in an
interactive context.) Do not read from a terminal file (or call
C<eof(FILEHANDLE)> on it) after end-of-file is reached. Filetypes such
as terminals may lose the end-of-file condition if you do.
An C<eof> without an argument uses the last file read as argument.
Using C<eof()> with empty parentheses is very different. It indicates the pseudo file formed of
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?