⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlfaq8.pod

📁 ARM上的如果你对底层感兴趣
💻 POD
📖 第 1 页 / 共 3 页
字号:
    system("cat /etc/termcap") == 0
	or die "cat program failed!";

Which will get the output quickly (as its generated, instead of only
at the end) and also check the return value.

system() also provides direct control over whether shell wildcard
processing may take place, whereas backticks do not.

=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.

There are more examples of this L<perlipc/"Safe Pipe Opens">.

=head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?

Because some stdio's set error and eof flags that need clearing.  The
POSIX module defines clearerr() that you can use.  That is the
technically correct way to do it.  Here are some less reliable
workarounds:

=over 4

=item 1

Try keeping around the seekpointer and go there, like this:

    $where = tell(LOG);
    seek(LOG, $where, 0);

=item 2

If that doesn't work, try seeking to a different part of the file and
then back.

=item 3

If that doesn't work, try seeking to a different part of
the file, reading something, and then seeking back.

=item 4

If 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, and
this very awkwardness is what would make a shell->perl converter
nigh-on impossible to write.  By rewriting it, you'll think about what
you're really trying to do, and hopefully will escape the shell's
pipeline 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 from
CPAN).  http://www.perl.com/CPAN/scripts/netstuff/telnet.emul.shar
will also help for emulating the telnet protocol, but Net::Telnet is
quite probably easier to use..

If all you want to do is pretend to be telnet but don't need
the initial telnet handshaking, then the standard dual-process
approach 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 the
standard perl distribution), which never really got finished.  If you
find it somewhere, I<don't use it>.  These days, your best bet is to
look at the Expect module available from CPAN, which also requires two
other 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 (to
avoid people seeing passwords, for example) then you should rewrite
your program so that critical information is never given as an
argument.  Hiding the arguments won't make your program completely
secure.

To actually alter the visible command line, you can assign to the
variable $0 as documented in L<perlvar>.  This won't work on all
operating systems, though.  Daemon programs like sendmail place their
state 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 Unix

In the strictest sense, it can't be done -- the script executes as a
different process from the shell it was started from.  Changes to a
process are not reflected in its parent, only in its own children
created after the change.  There is shell magic that may allow you to
fake it by eval()ing the script's output in your shell; check out the
comp.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 signal
to the process (see L<perlfunc/"kill">.  It's common to first send a TERM
signal, 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 from
its tty), then the following process is reported to work on most
Unixish systems.  Non-Unix users should check their Your_OS::Process
module for other solutions.

=over 4

=item *

Open /dev/tty and use the 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 old
tty.

=item *

Background yourself like this:

    fork && exit;

=back

=head2 How do I make my program run with sh and csh?

See the F<eg/nih> script (part of the perl source distribution).

=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 matches
the current process group of your controlling terminal as follows:

    use POSIX qw/getpgrp tcgetpgrp/;
    open(TTY, "/dev/tty") or die $!;
    $tpgrp = tcgetpgrp(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 signal
handler, as documented L<perlipc/"Signals"> and chapter 6 of the
Camel.  You may instead use the more flexible Sys::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 a
SIGCHLD is received, or else use the double-fork technique described
in L<perlfunc/fork>.

=head2 How do I use an SQL database?

There are a number of excellent interfaces to SQL databases.  See the
DBD::* modules available from
http://www.perl.com/CPAN/modules/dbperl/DBD .
A lot of information on this can be found at 
http://www.hermetica.com/technologia/perl/DBI/index.html .

=head2 How do I make a system() exit on control-C?

You can't.  You need to imitate the system() call (see L<perlipc> for
sample code) and then have a signal handler for the INT signal that
passes 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 supports
non-blocking reads (most Unixish systems do), you need only to use the
O_NDELAY or O_NONBLOCK flag from the Fcntl module in conjunction with
sysopen():

    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 CPAN module?

The easiest way is to have the CPAN module do it for you.  This module
comes with perl version 5.004 and later.  To manually install the CPAN
module, or any well-behaved CPAN module for that matter, follow these
steps:

=over 4

=item 1

Unpack the source into a temporary area.

=item 2

    perl Makefile.PL

=item 3

    make

=item 4

    make test

=item 5

    make install

=back

If your version of perl is compiled without dynamic loading, then you
just need to replace step 3 (B<make>) with B<make perl> and you will
get 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.

=head2 What's the difference between require and use?

Perl offers several different ways to include code from one file into
another.  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 generating
Makefiles:

    perl Makefile.PL PREFIX=/u/mydir/perl

then either set the PERL5LIB environment variable before you run
scripts that use the modules/libraries (see L<perlrun>) or say

    use lib '/u/mydir/perl';

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 commpand line flag
    the use lib pragma, as in
        use lib "$ENV{HOME}/myown_perllib";

The latter is particularly useful because it knows about machine
dependent architectures.  The lib.pm pragmatic module was first
included with the 5.002 release of Perl.

=head1 AUTHOR AND COPYRIGHT

Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
All rights reserved.

When included as part of the Standard Version of Perl, or as part of
its complete documentation whether printed or otherwise, this work
may 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 with
copyright holder.

Irrespective of its distribution, all code examples in this file
are hereby placed into the public domain.  You are permitted and
encouraged to use this code in your own programs for fun
or for profit as you see fit.  A simple comment in the code giving
credit would be courteous but is not required.

⌨️ 快捷键说明

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