perlfaq8.pod

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

POD
1,332 行
字号
	close $handle;	exit;=head2 How can I write expect in Perl?Once upon a time, there was a library called chat2.pl (part of thestandard perl distribution), which never really got finished.  If youfind it somewhere, I<don't use it>.  These days, your best bet is tolook at the Expect module available from CPAN, which also requires twoother modules from CPAN, IO::Pty and IO::Stty.=head2 Is there a way to hide perl's command line from programs such as "ps"?First of all note that if you're doing this for security reasons (toavoid people seeing passwords, for example) then you should rewriteyour program so that critical information is never given as anargument.  Hiding the arguments won't make your program completelysecure.To actually alter the visible command line, you can assign to thevariable $0 as documented in L<perlvar>.  This won't work on alloperating systems, though.  Daemon programs like sendmail place theirstate there, as in:	$0 = "orcus [accepting connections]";=head2 I {changed directory, modified my environment} in a perl script.  How come the change disappeared when I exited the script?  How do I get my changes to be visible?=over 4=item UnixIn the strictest sense, it can't be done--the script executes as adifferent process from the shell it was started from.  Changes to aprocess are not reflected in its parent--only in any childrencreated after the change.  There is shell magic that may allow you tofake it by eval()ing the script's output in your shell; check out thecomp.unix.questions FAQ for details.=back=head2 How do I close a process's filehandle without waiting for it to complete?Assuming your system supports such things, just send an appropriate signalto the process (see L<perlfunc/"kill">).  It's common to first send a TERMsignal, wait a little bit, and then send a KILL signal to finish it off.=head2 How do I fork a daemon process?If by daemon process you mean one that's detached (disassociated fromits tty), then the following process is reported to work on mostUnixish systems.  Non-Unix users should check their Your_OS::Processmodule for other solutions.=over 4=item *Open /dev/tty and use the TIOCNOTTY ioctl on it.  See L<tty>for details.  Or better yet, you can just use the POSIX::setsid()function, so you don't have to worry about process groups.=item *Change directory to /=item *Reopen STDIN, STDOUT, and STDERR so they're not connected to the oldtty.=item *Background yourself like this:	fork && exit;=backThe Proc::Daemon module, available from CPAN, provides a function toperform these actions for you.=head2 How do I find out if I'm running interactively or not?Good question. Sometimes C<-t STDIN> and C<-t STDOUT> can give clues,sometimes not.	if (-t STDIN && -t STDOUT) {		print "Now what? ";		}On POSIX systems, you can test whether your own process group matchesthe current process group of your controlling terminal as follows:	use POSIX qw/getpgrp tcgetpgrp/;	# Some POSIX systems, such as Linux, can be	# without a /dev/tty at boot time.	if (!open(TTY, "/dev/tty")) {		print "no tty\n";	} else {		$tpgrp = tcgetpgrp(fileno(*TTY));		$pgrp = getpgrp();		if ($tpgrp == $pgrp) {			print "foreground\n";		} else {			print "background\n";		}	}=head2 How do I timeout a slow event?Use the alarm() function, probably in conjunction with a signalhandler, as documented in L<perlipc/"Signals"> and the section on"Signals" in the Camel.  You may instead use the more flexibleSys::AlarmCall module available from CPAN.The alarm() function is not implemented on all versions of Windows.Check the documentation for your specific version of Perl.=head2 How do I set CPU limits?X<BSD::Resource> X<limit> X<CPU>(contributed by Xho)Use the C<BSD::Resource> module from CPAN. As an example:	use BSD::Resource;	setrlimit(RLIMIT_CPU,10,20) or die $!;This sets the soft and hard limits to 10 and 20 seconds, respectively.After 10 seconds of time spent running on the CPU (not "wall" time),the process will be sent a signal (XCPU on some systems) which, if nottrapped, will cause the process to terminate.  If that signal istrapped, then after 10 more seconds (20 seconds in total) the processwill be killed with a non-trappable signal.See the C<BSD::Resource> and your systems documentation for the gorydetails.=head2 How do I avoid zombies on a Unix system?Use the reaper code from L<perlipc/"Signals"> to call wait() when aSIGCHLD is received, or else use the double-fork technique describedin L<perlfaq8/"How do I start a process in the background?">.=head2 How do I use an SQL database?The DBI module provides an abstract interface to most databaseservers and types, including Oracle, DB2, Sybase, mysql, Postgresql,ODBC, and flat files.  The DBI module accesses each database typethrough a database driver, or DBD.  You can see a complete list ofavailable drivers on CPAN: http://www.cpan.org/modules/by-module/DBD/ .You can read more about DBI on http://dbi.perl.org .Other modules provide more specific access: Win32::ODBC, Alzabo, iodbc,and others found on CPAN Search: http://search.cpan.org .=head2 How do I make a system() exit on control-C?You can't.  You need to imitate the system() call (see L<perlipc> forsample code) and then have a signal handler for the INT signal thatpasses the signal on to the subprocess.  Or you can check for it:	$rc = system($cmd);	if ($rc & 127) { die "signal death" }=head2 How do I open a file without blocking?If you're lucky enough to be using a system that supportsnon-blocking reads (most Unixish systems do), you need only to use theO_NDELAY or O_NONBLOCK flag from the Fcntl module in conjunction withsysopen():	use Fcntl;	sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)		or die "can't open /foo/somefile: $!":=head2 How do I tell the difference between errors from the shell and perl?(answer contributed by brian d foy)When you run a Perl script, something else is running the script for you,and that something else may output error messages.  The script mightemit its own warnings and error messages.  Most of the time you cannottell who said what.You probably cannot fix the thing that runs perl, but you can change howperl outputs its warnings by defining a custom warning and die functions.Consider this script, which has an error you may not notice immediately.	#!/usr/locl/bin/perl	print "Hello World\n";I get an error when I run this from my shell (which happens to bebash).  That may look like perl forgot it has a print() function,but my shebang line is not the path to perl, so the shell runs thescript, and I get the error.	$ ./test	./test: line 3: print: command not foundA quick and dirty fix involves a little bit of code, but this may be allyou need to figure out the problem.	#!/usr/bin/perl -w	BEGIN {	$SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };	$SIG{__DIE__}  = sub{ print STDERR "Perl: ", @_; exit 1};	}	$a = 1 + undef;	$x / 0;	__END__The perl message comes out with "Perl" in front.  The BEGIN blockworks at compile time so all of the compilation errors and warningsget the "Perl:" prefix too.	Perl: Useless use of division (/) in void context at ./test line 9.	Perl: Name "main::a" used only once: possible typo at ./test line 8.	Perl: Name "main::x" used only once: possible typo at ./test line 9.	Perl: Use of uninitialized value in addition (+) at ./test line 8.	Perl: Use of uninitialized value in division (/) at ./test line 9.	Perl: Illegal division by zero at ./test line 9.	Perl: Illegal division by zero at -e line 3.If I don't see that "Perl:", it's not from perl.You could also just know all the perl errors, and although there aresome people who may know all of them, you probably don't.  However, theyall should be in the perldiag manpage. If you don't find the error inthere, it probably isn't a perl error.Looking up every message is not the easiest way, so let perl to do itfor you.  Use the diagnostics pragma with turns perl's normal messagesinto longer discussions on the topic.	use diagnostics;If you don't get a paragraph or two of expanded discussion, itmight not be perl's message.=head2 How do I install a module from CPAN?The easiest way is to have a module also named CPAN do it for you.This module comes with perl version 5.004 and later.	$ perl -MCPAN -e shell	cpan shell -- CPAN exploration and modules installation (v1.59_54)	ReadLine support enabled	cpan> install Some::ModuleTo manually install the CPAN module, or any well-behaved CPAN modulefor that matter, follow these steps:=over 4=item 1Unpack the source into a temporary area.=item 2	perl Makefile.PL=item 3	make=item 4	make test=item 5	make install=backIf your version of perl is compiled without dynamic loading, then youjust need to replace step 3 (B<make>) with B<make perl> and you willget a new F<perl> binary with your extension linked in.See L<ExtUtils::MakeMaker> for more details on building extensions.See also the next question, "What's the difference between requireand use?".=head2 What's the difference between require and use?Perl offers several different ways to include code from one file intoanother.  Here are the deltas between the various inclusion constructs:	1)  do $file is like eval `cat $file`, except the former	1.1: searches @INC and updates %INC.	1.2: bequeaths an *unrelated* lexical scope on the eval'ed code.	2)  require $file is like do $file, except the former	2.1: checks for redundant loading, skipping already loaded files.	2.2: raises an exception on failure to find, compile, or execute $file.	3)  require Module is like require "Module.pm", except the former	3.1: translates each "::" into your system's directory separator.	3.2: primes the parser to disambiguate class Module as an indirect object.	4)  use Module is like require Module, except the former	4.1: loads the module at compile time, not run-time.	4.2: imports symbols and semantics from that package to the current one.In general, you usually want C<use> and a proper Perl module.=head2 How do I keep my own module/library directory?When you build modules, tell Perl where to install the modules.For C<Makefile.PL>-based distributions, use the PREFIX and LIB optionswhen generating Makefiles:	perl Makefile.PL PREFIX=/mydir/perl LIB=/mydir/perl/libYou can set this in your CPAN.pm configuration so modules automatically installin your private library directory when you use the CPAN.pm shell:	% cpan	cpan> o conf makepl_arg PREFIX=/mydir/perl,LIB=/mydir/perl/lib	cpan> o conf commitFor C<Build.PL>-based distributions, use the --install_base option:	perl Build.PL --install_base /mydir/perl You can configure CPAN.pm to automatically use this option too:	% cpan	cpan> o conf mbuild_arg --install_base /mydir/perl	cpan> o conf commit=head2 How do I add the directory my program lives in to the module/library search path?(contributed by brian d foy)If you know the directory already, you can add it to C<@INC> as you wouldfor any other directory. You might <use lib> if you know the directoryat compile time:	use lib $directory;	The trick in this task is to find the directory. Before your script doesanything else (such as a C<chdir>), you can get the current workingdirectory with the C<Cwd> module, which comes with Perl:	BEGIN {		use Cwd;		our $directory = cwd;		}		use lib $directory;	You can do a similar thing with the value of C<$0>, which holds thescript name. That might hold a relative path, but C<rel2abs> can turnit into an absolute path. Once you have the 	BEGIN {			use File::Spec::Functions qw(rel2abs);		use File::Basename qw(dirname);				my $path   = rel2abs( $0 );		our $directory = dirname( $path );		}			use lib $directory;The C<FindBin> module, which comes with Perl, might work. It searchesthrough C<$ENV{PATH}> (so your script has to be in one of thosedirectories). You can then use that directory (in C<$FindBin::Bin>)to locate nearby directories you want to add:	use FindBin;	use lib "$FindBin::Bin/../lib";=head2 How do I add a directory to my include path (@INC) at runtime?Here are the suggested ways of modifying your include path, includingenvironment variables, run-time switches, and in-code statements:=over 4=item the PERLLIB environment variable	$ export PERLLIB=/path/to/my/dir	$ perl program.pl=item the PERL5LIB environment variable	$ export PERL5LIB=/path/to/my/dir	$ perl program.pl=item the perl -Idir command line flag	$ perl -I/path/to/my/dir program.pl=item the use lib pragma:	use lib "$ENV{HOME}/myown_perllib";=backThe last is particularly useful because it knows about machinedependent architectures.  The lib.pm pragmatic module was firstincluded with the 5.002 release of Perl.=head2 What is socket.ph and where do I get it?It's a Perl 4 style file defining values for system networkingconstants.  Sometimes it is built using h2ph when Perl is installed,but other times it is not.  Modern programs C<use Socket;> instead.=head1 REVISIONRevision: $Revision: 10183 $Date: $Date: 2007-11-07 09:35:12 +0100 (Wed, 07 Nov 2007) $See L<perlfaq> for source control details and availability.=head1 AUTHOR AND COPYRIGHTCopyright (c) 1997-2007 Tom Christiansen, Nathan Torkington, andother authors as noted. All rights reserved.This documentation is free; you can redistribute it and/or modify itunder the same terms as Perl itself.Irrespective of its distribution, all code examples in this fileare hereby placed into the public domain.  You are permitted andencouraged to use this code in your own programs for funor for profit as you see fit.  A simple comment in the code givingcredit would be courteous but is not required.

⌨️ 快捷键说明

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