📄 perlfaq8.pod
字号:
=head2 How can I call backticks without shell processing?This is a bit tricky. Instead of writing @ok = `grep @opts '$search_string' @filenames`;You have to do this: my @ok = (); if (open(GREP, "-|")) { while (<GREP>) { chomp; push(@ok, $_); } close GREP; } else { exec 'grep', @opts, $search_string, @filenames; }Just as with system(), no shell escapes happen when you exec() a list.Further examples of this can be found in L<perlipc/"Safe Pipe Opens">.Note that if you're stuck on Microsoft, no solution to this vexing issueis even possible. Even if Perl were to emulate fork(), you'd stillbe hosed, because Microsoft gives no argc/argv-style API. Their APIalways reparses from a single string, which is fundamentally wrong,but you're not likely to get the Gods of Redmond to acknowledge thisand fix it for you.=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.perl.com/CPAN/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') || 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 } 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(4)>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/; open(TTY, "/dev/tty") or die $!; $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.=head2 How do I set CPU limits?Use the BSD::Resource module from CPAN.=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<perlfunc/fork>.=head2 How do I use an SQL database?There are a number of excellent interfaces to SQL databases. See theDBD::* modules available from http://www.perl.com/CPAN/modules/DBD .A lot of information on this can be found at http://www.symbolstone.org/technology/perl/DBI/=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, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644) or die "can't open /tmp/somefile: $!":=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. To manually installthe CPAN module, or any well-behaved CPAN module for that matter, followthese 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, use the PREFIX option when generatingMakefiles: perl Makefile.PL PREFIX=/u/mydir/perlthen either set the PERL5LIB environment variable before you runscripts that use the modules/libraries (see L<perlrun>) or say use lib '/u/mydir/perl';This is almost the same as BEGIN { unshift(@INC, '/u/mydir/perl'); }except that the lib module checks for machine-dependent subdirectories.See Perl's L<lib> for more information.=head2 How do I add the directory my program lives in to the module/library search path? use FindBin; use lib "$FindBin::Bin"; use your_own_modules;=head2 How do I add a directory to my include path at runtime?Here are the suggested ways of modifying your include path: the PERLLIB environment variable the PERL5LIB environment variable the perl -Idir command line flag the use lib pragma, as in use lib "$ENV{HOME}/myown_perllib";The latter 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 perl4-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 AUTHOR AND COPYRIGHTCopyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.All rights reserved.When included as part of the Standard Version of Perl, or as part ofits complete documentation whether printed or otherwise, this workmay be distributed only under the terms of Perl's Artistic License.Any distribution of this file or derivatives thereof I<outside>of that package require that special arrangements be made withcopyright holder.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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -