perlfaq8.pod
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 1,332 行 · 第 1/3 页
POD
1,332 行
varies from system to system--see L<passwd> for specifics) and usepwd_mkdb(8) to install it (see L<pwd_mkdb> for more details).=head2 How do I set the time and date?Assuming you're running under sufficient permissions, you should beable to set the system-wide date and time by running the date(1)program. (There is no way to set the time and date on a per-processbasis.) This mechanism will work for Unix, MS-DOS, Windows, and NT;the VMS equivalent is C<set time>.However, if all you want to do is change your time zone, you canprobably get away with setting an environment variable: $ENV{TZ} = "MST7MDT"; # unixish $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms system "trn comp.lang.perl.misc";=head2 How can I sleep() or alarm() for under a second?X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select>If you want finer granularity than the 1 second that the C<sleep()>function provides, the easiest way is to use the C<select()> function asdocumented in L<perlfunc/"select">. Try the C<Time::HiRes> andthe C<BSD::Itimer> modules (available from CPAN, and starting fromPerl 5.8 C<Time::HiRes> is part of the standard distribution).=head2 How can I measure time under a second?X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select>(contributed by brian d foy)The C<Time::HiRes> module (part of the standard distribution as ofPerl 5.8) measures time with the C<gettimeofday()> system call, whichreturns the time in microseconds since the epoch. If you can't installC<Time::HiRes> for older Perls and you are on a Unixish system, youmay be able to call C<gettimeofday(2)> directly. SeeL<perlfunc/syscall>.=head2 How can I do an atexit() or setjmp()/longjmp()? (Exception handling)Release 5 of Perl added the END block, which can be used to simulateatexit(). Each package's END block is called when the program orthread ends (see L<perlmod> manpage for more details).For example, you can use this to make sure your filter programmanaged to finish its output without filling up the disk: END { close(STDOUT) || die "stdout close failed: $!"; }The END block isn't called when untrapped signals kill the program,though, so if you use END blocks you should also use use sigtrap qw(die normal-signals);Perl's exception-handling mechanism is its eval() operator. You canuse eval() as setjmp and die() as longjmp. For details of this, seethe section on signals, especially the time-out handler for a blockingflock() in L<perlipc/"Signals"> or the section on "Signals" inthe Camel Book.If exception handling is all you're interested in, try theexceptions.pl library (part of the standard perl distribution).If you want the atexit() syntax (and an rmexit() as well), try theAtExit module available from CPAN.=head2 Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?Some Sys-V based systems, notably Solaris 2.X, redefined some of thestandard socket constants. Since these were constant across allarchitectures, they were often hardwired into perl code. The properway to deal with this is to "use Socket" to get the correct values.Note that even though SunOS and Solaris are binary compatible, thesevalues are different. Go figure.=head2 How can I call my system's unique C functions from Perl?In most cases, you write an external module to do it--see the answerto "Where can I learn about linking C with Perl? [h2xs, xsubpp]".However, if the function is a system call, and your system supportssyscall(), you can use the syscall function (documented inL<perlfunc>).Remember to check the modules that came with your distribution, andCPAN as well--someone may already have written a module to do it. OnWindows, try Win32::API. On Macs, try Mac::Carbon. If no modulehas an interface to the C function, you can inline a bit of C in yourPerl source with Inline::C.=head2 Where do I get the include files to do ioctl() or syscall()?Historically, these would be generated by the h2ph tool, part of thestandard perl distribution. This program converts cpp(1) directivesin C header files to files containing subroutine definitions, like&SYS_getitimer, which you can use as arguments to your functions.It doesn't work perfectly, but it usually gets most of the job done.Simple files like F<errno.h>, F<syscall.h>, and F<socket.h> were fine,but the hard ones like F<ioctl.h> nearly always need to hand-edited.Here's how to install the *.ph files: 1. become super-user 2. cd /usr/include 3. h2ph *.h */*.hIf your system supports dynamic loading, for reasons of portability andsanity you probably ought to use h2xs (also part of the standard perldistribution). This tool converts C header files to Perl extensions.See L<perlxstut> for how to get started with h2xs.If your system doesn't support dynamic loading, you still probablyought to use h2xs. See L<perlxstut> and L<ExtUtils::MakeMaker> formore information (in brief, just use B<make perl> instead of a plainB<make> to rebuild perl with a new static extension).=head2 Why do setuid perl scripts complain about kernel problems?Some operating systems have bugs in the kernel that make setuidscripts inherently insecure. Perl gives you a number of options(described in L<perlsec>) to work around such systems.=head2 How can I open a pipe both to and from a command?The IPC::Open2 module (part of the standard perl distribution) is aneasy-to-use approach that internally uses pipe(), fork(), and exec() to dothe job. Make sure you read the deadlock warnings in its documentation,though (see L<IPC::Open2>). SeeL<perlipc/"Bidirectional Communication with Another Process"> andL<perlipc/"Bidirectional Communication with Yourself">You may also use the IPC::Open3 module (part of the standard perldistribution), but be warned that it has a different order ofarguments from IPC::Open2 (see L<IPC::Open3>).=head2 Why can't I get the output of a command with system()?You're confusing the purpose of system() and backticks (``). system()runs a command and returns exit status information (as a 16 bit value:the low 7 bits are the signal the process died from, if any, andthe high 8 bits are the actual exit value). Backticks (``) run acommand and return what it sent to STDOUT. $exit_status = system("mail-users"); $output_string = `ls`;=head2 How can I capture STDERR from an external command?There are three basic ways of running external commands: system $cmd; # using system() $output = `$cmd`; # using backticks (``) open (PIPE, "cmd |"); # using open()With system(), both STDOUT and STDERR will go the same place as thescript's STDOUT and STDERR, unless the system() command redirects them.Backticks and open() read B<only> the STDOUT of your command.You can also use the open3() function from IPC::Open3. BenjaminGoldberg provides some sample code:To capture a program's STDOUT, but discard its STDERR: use IPC::Open3; use File::Spec; use Symbol qw(gensym); open(NULL, ">", File::Spec->devnull); my $pid = open3(gensym, \*PH, ">&NULL", "cmd"); while( <PH> ) { } waitpid($pid, 0);To capture a program's STDERR, but discard its STDOUT: use IPC::Open3; use File::Spec; use Symbol qw(gensym); open(NULL, ">", File::Spec->devnull); my $pid = open3(gensym, ">&NULL", \*PH, "cmd"); while( <PH> ) { } waitpid($pid, 0);To capture a program's STDERR, and let its STDOUT go to our own STDERR: use IPC::Open3; use Symbol qw(gensym); my $pid = open3(gensym, ">&STDERR", \*PH, "cmd"); while( <PH> ) { } waitpid($pid, 0);To read both a command's STDOUT and its STDERR separately, you canredirect them to temp files, let the command run, then read the tempfiles: use IPC::Open3; use Symbol qw(gensym); use IO::File; local *CATCHOUT = IO::File->new_tmpfile; local *CATCHERR = IO::File->new_tmpfile; my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd"); waitpid($pid, 0); seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR; while( <CATCHOUT> ) {} while( <CATCHERR> ) {}But there's no real need for *both* to be tempfiles... the followingshould work just as well, without deadlocking: use IPC::Open3; use Symbol qw(gensym); use IO::File; local *CATCHERR = IO::File->new_tmpfile; my $pid = open3(gensym, \*CATCHOUT, ">&CATCHERR", "cmd"); while( <CATCHOUT> ) {} waitpid($pid, 0); seek CATCHERR, 0, 0; while( <CATCHERR> ) {}And it'll be faster, too, since we can begin processing the program'sstdout immediately, rather than waiting for the program to finish.With any of these, you can change file descriptors before the call: open(STDOUT, ">logfile"); system("ls");or you can use Bourne shell file-descriptor redirection: $output = `$cmd 2>some_file`; open (PIPE, "cmd 2>some_file |");You can also use file-descriptor redirection to make STDERR aduplicate of STDOUT: $output = `$cmd 2>&1`; open (PIPE, "cmd 2>&1 |");Note that you I<cannot> simply open STDERR to be a dup of STDOUTin your Perl program and avoid calling the shell to do the redirection.This doesn't work: open(STDERR, ">&STDOUT"); $alloutput = `cmd args`; # stderr still escapesThis fails because the open() makes STDERR go to where STDOUT wasgoing at the time of the open(). The backticks then make STDOUT go toa string, but don't change STDERR (which still goes to the oldSTDOUT).Note that you I<must> use Bourne shell (sh(1)) redirection syntax inbackticks, not csh(1)! Details on why Perl's system() and backtickand pipe opens all use the Bourne shell are in theF<versus/csh.whynot> article in the "Far More Than You Ever Wanted ToKnow" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz . Tocapture a command's STDERR and STDOUT together: $output = `cmd 2>&1`; # either with backticks $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe while (<PH>) { } # plus a readTo capture a command's STDOUT but discard its STDERR: $output = `cmd 2>/dev/null`; # either with backticks $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe while (<PH>) { } # plus a readTo capture a command's STDERR but discard its STDOUT: $output = `cmd 2>&1 1>/dev/null`; # either with backticks $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe while (<PH>) { } # plus a readTo exchange a command's STDOUT and STDERR in order to capture the STDERRbut leave its STDOUT to come out our old STDERR: $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe while (<PH>) { } # plus a readTo read both a command's STDOUT and its STDERR separately, it's easiestto redirect them separately to files, and then read from those fileswhen the program is done: system("program args 1>program.stdout 2>program.stderr");Ordering is important in all these examples. That's because the shellprocesses file descriptor redirections in strictly left to right order. system("prog args 1>tmpfile 2>&1"); system("prog args 2>&1 1>tmpfile");The first command sends both standard out and standard error to thetemporary file. The second command sends only the old standard outputthere, and the old standard error shows up on the old standard out.=head2 Why doesn't open() return an error when a pipe open fails?If the second argument to a piped open() contains shellmetacharacters, perl fork()s, then exec()s a shell to decode themetacharacters and eventually run the desired program. If the programcouldn't be run, it's the shell that gets the message, not Perl. Allyour Perl program can find out is whether the shell itself could besuccessfully started. You can still capture the shell's STDERR andcheck it for error messages. See L<"How can I capture STDERR from anexternal command?"> elsewhere in this document, or use theIPC::Open3 module.If there are no shell metacharacters in the argument of open(), Perlruns the command directly, without using the shell, and can correctlyreport whether the command started.=head2 What's wrong with using backticks in a void context?Strictly speaking, nothing. Stylistically speaking, it's not a goodway to write maintainable code. Perl has several operators forrunning external commands. Backticks are one; they collect the outputfrom the command for use in your program. The C<system> function isanother; it doesn't do this.Writing backticks in your program sends a clear message to the readersof your code that you wanted to collect the output of the command.Why send a clear message that isn't true?Consider this line: `cat /etc/termcap`;You forgot to check C<$?> to see whether the program even rancorrectly. Even if you wrote print `cat /etc/termcap`;this code could and probably should be written as system("cat /etc/termcap") == 0 or die "cat program failed!";which will echo the cat command's output as it is generated, insteadof waiting until the program has completed to print it out. It alsochecks the return value.C<system> also provides direct control over whether shell wildcardprocessing may take place, whereas backticks do not.=head2 How can I call backticks without shell processing?This is a bit tricky. You can't simply write the commandlike this: @ok = `grep @opts '$search_string' @filenames`;As of Perl 5.8.0, you can use C<open()> with multiple arguments.Just like the list forms of C<system()> and C<exec()>, no shellescapes happen. open( GREP, "-|", 'grep', @opts, $search_string, @filenames ); chomp(@ok = <GREP>); close GREP;You can also: my @ok = (); if (open(GREP, "-|")) { while (<GREP>) { chomp; push(@ok, $_); } close GREP; } else { exec 'grep', @opts, $search_string, @filenames; }Just as with C<system()>, no shell escapes happen when you C<exec()> alist. Further examples of this can be found in L<perlipc/"Safe PipeOpens">.Note that if you're using Windows, no solution to this vexing issue iseven possible. Even if Perl were to emulate C<fork()>, you'd still bestuck, because Windows does not have an argc/argv-style API.=head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?Some stdio's set error and eof flags that need clearing. ThePOSIX module defines clearerr() that you can use. That is thetechnically correct way to do it. Here are some less reliableworkarounds:=over 4=item 1Try keeping around the seekpointer and go there, like this: $where = tell(LOG); seek(LOG, $where, 0);=item 2If that doesn't work, try seeking to a different part of the file andthen back.=item 3If that doesn't work, try seeking to a different part ofthe file, reading something, and then seeking back.=item 4If that doesn't work, give up on your stdio package and use sysread.=back=head2 How can I convert my shell script to perl?Learn Perl and rewrite it. Seriously, there's no simple converter.Things that are awkward to do in the shell are easy to do in Perl, andthis very awkwardness is what would make a shell->perl converternigh-on impossible to write. By rewriting it, you'll think about whatyou're really trying to do, and hopefully will escape the shell'spipeline datastream paradigm, which while convenient for some matters,causes many inefficiencies.=head2 Can I use perl to run a telnet or ftp session?Try the Net::FTP, TCP::Client, and Net::Telnet modules (available fromCPAN). http://www.cpan.org/scripts/netstuff/telnet.emul.sharwill also help for emulating the telnet protocol, but Net::Telnet isquite probably easier to use..If all you want to do is pretend to be telnet but don't needthe initial telnet handshaking, then the standard dual-processapproach will suffice: use IO::Socket; # new in 5.004 $handle = IO::Socket::INET->new('www.perl.com:80') or die "can't connect to port 80 on www.perl.com: $!"; $handle->autoflush(1); if (fork()) { # XXX: undef means failure select($handle); print while <STDIN>; # everything from stdin to socket } else { print while <$handle>; # everything from socket to stdout }
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?