Imported upstream version 1.5
[manpages-zh.git] / src / man1 / perlfaq9.1
bloba9b69530d32981c4b4ea6bb06d84854d4dfb1e8f
1 .\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14
2 .\"
3 .\" Standard preamble:
4 .\" ========================================================================
5 .de Sh \" Subsection heading
6 .br
7 .if t .Sp
8 .ne 5
9 .PP
10 \fB\\$1\fR
11 .PP
13 .de Sp \" Vertical space (when we can't use .PP)
14 .if t .sp .5v
15 .if n .sp
17 .de Vb \" Begin verbatim text
18 .ft CW
19 .nf
20 .ne \\$1
22 .de Ve \" End verbatim text
23 .ft R
24 .fi
26 .\" Set up some character translations and predefined strings.  \*(-- will
27 .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28 .\" double quote, and \*(R" will give a right double quote.  | will give a
29 .\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
30 .\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
31 .\" expand to `' in nroff, nothing in troff, for use with C<>.
32 .tr \(*W-|\(bv\*(Tr
33 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34 .ie n \{\
35 .    ds -- \(*W-
36 .    ds PI pi
37 .    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38 .    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
39 .    ds L" ""
40 .    ds R" ""
41 .    ds C` ""
42 .    ds C' ""
43 'br\}
44 .el\{\
45 .    ds -- \|\(em\|
46 .    ds PI \(*p
47 .    ds L" ``
48 .    ds R" ''
49 'br\}
50 .\"
51 .\" If the F register is turned on, we'll generate index entries on stderr for
52 .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53 .\" entries marked with X<> in POD.  Of course, you'll have to process the
54 .\" output yourself in some meaningful fashion.
55 .if \nF \{\
56 .    de IX
57 .    tm Index:\\$1\t\\n%\t"\\$2"
59 .    nr % 0
60 .    rr F
61 .\}
62 .\"
63 .\" For nroff, turn off justification.  Always turn off hyphenation; it makes
64 .\" way too many mistakes in technical documents.
65 .hy 0
66 .if n .na
67 .\"
68 .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69 .\" Fear.  Run.  Save yourself.  No user-serviceable parts.
70 .    \" fudge factors for nroff and troff
71 .if n \{\
72 .    ds #H 0
73 .    ds #V .8m
74 .    ds #F .3m
75 .    ds #[ \f1
76 .    ds #] \fP
77 .\}
78 .if t \{\
79 .    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80 .    ds #V .6m
81 .    ds #F 0
82 .    ds #[ \&
83 .    ds #] \&
84 .\}
85 .    \" simple accents for nroff and troff
86 .if n \{\
87 .    ds ' \&
88 .    ds ` \&
89 .    ds ^ \&
90 .    ds , \&
91 .    ds ~ ~
92 .    ds /
93 .\}
94 .if t \{\
95 .    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96 .    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97 .    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98 .    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99 .    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100 .    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
102 .    \" troff and (daisy-wheel) nroff accents
103 .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104 .ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105 .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106 .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107 .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108 .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109 .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110 .ds ae a\h'-(\w'a'u*4/10)'e
111 .ds Ae A\h'-(\w'A'u*4/10)'E
112 .    \" corrections for vroff
113 .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114 .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115 .    \" for low resolution devices (crt and lpr)
116 .if \n(.H>23 .if \n(.V>19 \
118 .    ds : e
119 .    ds 8 ss
120 .    ds o a
121 .    ds d- d\h'-1'\(ga
122 .    ds D- D\h'-1'\(hy
123 .    ds th \o'bp'
124 .    ds Th \o'LP'
125 .    ds ae ae
126 .    ds Ae AE
128 .rm #[ #] #H #V #F C
129 .\" ========================================================================
131 .IX Title "PERLFAQ9 1"
132 .TH PERLFAQ9 1 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide"
133 .SH "NAME"
134 perlfaq9 \- 网络 (2003/01/31 17:36:57 )
135 .SH "DESCRIPTION 描述"
136 .IX Header "DESCRIPTION"
137 网络通信,互联网以及少量有关 web 的内容
138 .Sh "What is the correct form of response from a \s-1CGI\s0 script?"
139 .IX Subsection "一个 CGI 脚本的回应的正确格式是什么?"
140 (Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...)
142 The Common Gateway Interface (\s-1CGI\s0) specifies a software interface between
143 a program (\*(L"\s-1CGI\s0 script\*(R") and a web server (\s-1HTTPD\s0). It is not specific
144 to Perl, and has its own FAQs and tutorials, and usenet group,
145 comp.infosystems.www.authoring.cgi
147 The original \s-1CGI\s0 specification is at: http://hoohoo.ncsa.uiuc.edu/cgi/
149 Current best-practice \s-1RFC\s0 draft at: http://CGI\-Spec.Golux.Com/
151 Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html
153 These Perl FAQs very selectively cover some \s-1CGI\s0 issues. However, Perl
154 programmers are strongly advised to use the \s-1CGI\s0.pm module, to take care
155 of the details for them.
157 The similarity between \s-1CGI\s0 response headers (defined in the \s-1CGI\s0
158 specification) and \s-1HTTP\s0 response headers (defined in the \s-1HTTP\s0
159 specification, \s-1RFC2616\s0) is intentional, but can sometimes be confusing.
161 The \s-1CGI\s0 specification defines two kinds of script: the \*(L"Parsed Header\*(R"
162 script, and the \*(L"Non Parsed Header\*(R" (\s-1NPH\s0) script. Check your server
163 documentation to see what it supports. \*(L"Parsed Header\*(R" scripts are
164 simpler in various respects. The \s-1CGI\s0 specification allows any of the
165 usual newline representations in the \s-1CGI\s0 response (it's the server's
166 job to create an accurate \s-1HTTP\s0 response based on it). So \*(L"\en\*(R" written in
167 text mode is technically correct, and recommended. \s-1NPH\s0 scripts are more
168 tricky: they must put out a complete and accurate set of \s-1HTTP\s0
169 transaction response headers; the \s-1HTTP\s0 specification calls for records
170 to be terminated with carriage-return and line\-feed, i.e \s-1ASCII\s0 \e015\e012
171 written in binary mode.
173 Using \s-1CGI\s0.pm gives excellent platform independence, including \s-1EBCDIC\s0
174 systems. \s-1CGI\s0.pm selects an appropriate newline representation
175 ($CGI::CRLF) and sets binmode as appropriate.
176 .Sh "我的 CGI 脚本从命令行执行正常,但是在浏览器中不行 (500 Server Error)。"
177 .IX Subsection "My CGI script runs from the command line but not the browser.  (500 Server Error)"
178 可能有很多事错了。可以仔细阅读 \*(L"Troubleshooting
179 Perl \s-1CGI\s0 scripts\*(R" guide, 位置是
181 .Vb 1
182 \&        http://www.perl.org/troubleshooting_CGI.html
185 如果接下来,你能证明你已阅读了 FAQ 并且你的问题不是那么简单,非叁言两语即可回答的话,那麽您 post到 comp.infosystems.www.authoring.cgi上(如果是有关 HTTP 、 HTML ,或 CGI通信协定)的问题可能也会得到口气和缓而有用的答覆。表面上看似 Perl,但骨子里是 CGI之类的问题,如果 post到 comp.lang.perl.misc人家可能就不会这麽乐意地接受了。
187 几个实用的 FAQ,相关文档和查错向导列在 \s-1CGI\s0 Meta \s-1FAQ\s0 中:
189 .Vb 1
190 \&        http://www.perl.org/CGI_MetaFAQ.html
192 .Sh "如何从 CGI 程序中得到好一点的错误提示?"
193 .IX Subsection "How can I get better error messages from a CGI program?"
194 Use the CGI::Carp module.  It replaces \f(CW\*(C`warn\*(C'\fR and \f(CW\*(C`die\*(C'\fR, plus the
195 normal Carp modules \f(CW\*(C`carp\*(C'\fR, \f(CW\*(C`croak\*(C'\fR, and \f(CW\*(C`confess\*(C'\fR functions with
196 more verbose and safer versions.  It still sends them to the normal
197 server error log.
199 .Vb 3
200 \&    use CGI::Carp;
201 \&    warn "This is a complaint";
202 \&    die "But this one is serious";
205 The following use of CGI::Carp also redirects errors to a file of your choice,
206 placed in a \s-1BEGIN\s0 block to catch compile-time warnings as well:
208 .Vb 6
209 \&    BEGIN {
210 \&        use CGI::Carp qw(carpout);
211 \&        open(LOG, ">>/var/local/cgi-logs/mycgi-log")
212 \&            or die "Unable to append to mycgi-log: $!\en";
213 \&        carpout(*LOG);
214 \&    }
217 You can even arrange for fatal errors to go back to the client browser,
218 which is nice for your own debugging, but might confuse the end user.
220 .Vb 2
221 \&    use CGI::Carp qw(fatalsToBrowser);
222 \&    die "Bad error here";
225 Even if the error happens before you get the \s-1HTTP\s0 header out, the module
226 will try to take care of this to avoid the dreaded server 500 errors.
227 Normal warnings still go out to the server error log (or wherever
228 you've sent them with \f(CW\*(C`carpout\*(C'\fR) with the application name and date
229 stamp prepended.
230 .Sh "如何将字符串中的 HTML 删除?"
231 .IX Subsection "How do I remove HTML from a string?"
232 最正确(尽管不是最快)的方法是使用 HTML::Parse模组(可由 CPAN取得,是所有写 Web程式者必备的 libwww-perl 套件的一部分)。另一中最正确的办法是使用 HTML::FormatText,它不仅删除了 \s-1HTML\s0,同时也试图对结果文本进行简单的格式化。
234 许多人尝试用简陋的正规表示式来解决这个问题,譬如说像 \f(CW\*(C`s/<.*?>//g\*(C'\fR,但这个式子在很多情况下会失败,因为要处理的字串可能会跨越断行字元,也可能含有被 quote【跳脱】的箭头号,或有 HTML comment出现;再加上一些疏忽,譬如,人们常忘了转换如 < 的 entities(跳脱字 元\f(CW\*(C`&lt;\*(C'\fR)。
236 以下这个「简陋」的方法对大多数的档案都有效:
238 .Vb 2
239 \&    #!/usr/bin/perl -p0777
240 \&    s/<(?:[^>'"]*|(['"]).*?\e1)*>//gs
243 如果您想要更完整的解法,请看叁部曲的 striphtml 程式,
244 http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz
247 Here are some tricky cases that you should think about when picking
248 a solution:
250 .Vb 1
251 \&    <IMG SRC = "foo.gif" ALT = "A > B">
254 .Vb 2
255 \&    <IMG SRC = "foo.gif"
256 \&         ALT = "A > B">
259 .Vb 1
260 \&    <!-- <A comment> -->
263 .Vb 1
264 \&    <script>if (a<b && a>c)</script>
267 .Vb 1
268 \&    <# Just data #>
271 .Vb 1
272 \&    <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
275 If \s-1HTML\s0 comments include other tags, those solutions would also break
276 on text like this:
278 .Vb 3
279 \&    <!-- This section commented out.
280 \&        <B>You can't see me!</B>
281 \&    -->
283 .Sh "如何萃取 URL?"
284 .IX Subsection "How do I extract URLs?"
285 可以简单地从 HTML 中得到所有种类的 URL,只要使用 \f(CW\*(C`HTML::SimpleLinkExtor\*(C'\fR 模块,它可以处理锚,图像,对象,桢,其他包含 URL 的标签。如果需要更复杂的东西,可以创建 \f(CW\*(C`HTML::LinkExtor\*(C'\fR 的子类或使用 \f(CW\*(C`HTML::Parser\*(C'\fR. 你甚至可以用
286 \&\f(CW\*(C`HTML::SimpleLinkExtor\*(C'\fR 作为范例,来书写适合你特殊需要的程序。
288 You can use URI::Find to extract URLs from an arbitrary text document.
290 Less complete solutions involving regular expressions can save
291 you a lot of processing time if you know that the input is simple.  One
292 solution from Tom Christiansen runs 100 times faster than most
293 module based approaches but only extracts URLs from anchors where the first
294 attribute is \s-1HREF\s0 and there are no other attributes.
296 .Vb 7
297 \&        #!/usr/bin/perl -n00
298 \&        # qxurl - tchrist@perl.com
299 \&        print "$2\en" while m{
300 \&            < \es*
301 \&              A \es+ HREF \es* = \es* (["']) (.*?) \e1
302 \&            \es* >
303 \&        }gsix;
305 .Sh "如何从用户的机器上下载文件?如何打开其他机器上的文件?"
306 .IX Subsection "How do I download a file from the user's machine?  How do I open a file on another machine?"
307 In this case, download means to use the file upload feature of \s-1HTML\s0
308 forms.  You allow the web surfer to specify a file to send to your web
309 server.  To you it looks like a download, and to the user it looks
310 like an upload.  No matter what you call it, you do it with what's
311 known as \fBmultipart/form\-data\fR encoding.  The \s-1CGI\s0.pm module (which
312 comes with Perl as part of the Standard Library) supports this in the
313 \&\fIstart_multipart_form()\fR method, which isn't the same as the \fIstartform()\fR
314 method.
316 See the section in the \s-1CGI\s0.pm documentation on file uploads for code
317 examples and details.
318 .Sh "如何在 HTML 添加一个弹出菜单?"
319 .IX Subsection "How do I make a pop-up menu in HTML?"
320 用 <SELECT> 和 <OPTION>这两个标签。 CGI.pm模组(可由 CPAN取得)对这个 widget【此指跳出式选单这个介面成分】还有许多其他的介面成分都有支援【即有制作动态标签的函式】,其中有些是以巧妙模拟的方 式达成。
321 .Sh "如何获取 HTML 文件?"
322 .IX Subsection "How do I fetch an HTML file?"
323 有一个方法是,如果您的系统上装有 lynx一类的文字模式的 HTML浏览器的话,那麽可以这麽做:
325 .Vb 2
326 \&    $html_code = `lynx -source $url`;
327 \&    $text_data = `lynx -dump $url`;
330 收录在 CPAN里的 libwww-perl (LWP)模组则提供了更强的方法来做这件事。它不但可钻过 proxies,而且也不需要 lynx:
332 .Vb 3
333 \&    # simplest version
334 \&    use LWP::Simple;
335 \&    $content = get($URL);
338 .Vb 3
339 \&    # or print HTML from a URL
340 \&    use LWP::Simple;
341 \&    getprint "http://www.linpro.no/lwp/";
344 .Vb 11
345 \&    # or print ASCII from HTML from a URL
346 \&    # also need HTML-Tree package from CPAN
347 \&    use LWP::Simple;
348 \&    use HTML::Parser;
349 \&    use HTML::FormatText;
350 \&    my ($html, $ascii);
351 \&    $html = get("http://www.perl.com/");
352 \&    defined $html
353 \&        or die "Can't fetch HTML from http://www.perl.com/";
354 \&    $ascii = HTML::FormatText->new->format(parse_html($html));
355 \&    print $ascii;
357 .Sh "如何根据提交的内容自动生成一个 HTML ?"
358 .IX Subsection "How do I automate an HTML form submission?"
359 If you're submitting values using the \s-1GET\s0 method, create a \s-1URL\s0 and encode
360 the form using the \f(CW\*(C`query_form\*(C'\fR method:
362 .Vb 2
363 \&    use LWP::Simple;
364 \&    use URI::URL;
367 .Vb 3
368 \&    my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
369 \&    $url->query_form(module => 'DB_File', readme => 1);
370 \&    $content = get($url);
373 If you're using the \s-1POST\s0 method, create your own user agent and encode
374 the content appropriately.
376 .Vb 2
377 \&    use HTTP::Request::Common qw(POST);
378 \&    use LWP::UserAgent;
381 .Vb 4
382 \&    $ua = LWP::UserAgent->new();
383 \&    my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
384 \&                   [ module => 'DB_File', readme => 1 ];
385 \&    $content = $ua->request($req)->as_string;
387 .Sh "如何解码或创建 web 中的 %-encoding?"
388 .IX Subsection "How do I decode or create those %-encodings on the web?"
389 If you are writing a \s-1CGI\s0 script, you should be using the \s-1CGI\s0.pm module
390 that comes with perl, or some other equivalent module.  The \s-1CGI\s0 module
391 automatically decodes queries for you, and provides an \fIescape()\fR
392 function to handle encoding.
394 The best source of detailed information on \s-1URI\s0 encoding is \s-1RFC\s0 2396.
395 Basically, the following substitutions do it:
397 .Vb 1
398 \&    s/([^\ew()'*~!.-])/sprintf '%%%02x', ord $1/eg;   # encode
401 .Vb 1
402 \&    s/%([A-Fa-f\ed]{2})/chr hex $1/eg;            # decode
405 However, you should only apply them to individual \s-1URI\s0 components, not
406 the entire \s-1URI\s0, otherwise you'll lose information and generally mess
407 things up.  If that didn't explain it, don't worry.  Just go read
408 section 2 of the \s-1RFC\s0, it's probably the best explanation there is.
410 \&\s-1RFC\s0 2396 also contains a lot of other useful information, including a
411 regexp for breaking any arbitrary \s-1URI\s0 into components (Appendix B).
412 .Sh "如何重定向到其他页面?"
413 .IX Subsection "How do I redirect to another page?"
414 Specify the complete \s-1URL\s0 of the destination (even if it is on the same
415 server). This is one of the two different kinds of \s-1CGI\s0 \*(L"Location:\*(R"
416 responses which are defined in the \s-1CGI\s0 specification for a Parsed Headers
417 script. The other kind (an absolute URLpath) is resolved internally to
418 the server without any \s-1HTTP\s0 redirection. The \s-1CGI\s0 specifications do not
419 allow relative URLs in either case.
421 Use of \s-1CGI\s0.pm is strongly recommended.  This example shows redirection
422 with a complete \s-1URL\s0. This redirection is handled by the web browser.
424 .Vb 1
425 \&      use CGI qw/:standard/;
428 .Vb 2
429 \&      my $url = 'http://www.cpan.org/';
430 \&      print redirect($url);
433 This example shows a redirection with an absolute URLpath.  This
434 redirection is handled by the local web server.
436 .Vb 2
437 \&      my $url = '/CPAN/index.html';
438 \&      print redirect($url);
441 But if coded directly, it could be as follows (the final \*(L"\en\*(R" is
442 shown separately, for clarity), using either a complete \s-1URL\s0 or
443 an absolute URLpath.
445 .Vb 2
446 \&      print "Location: $url\en";   # CGI response header
447 \&      print "\en";                 # end of headers
449 .Sh "如何为我的网页加上密码?"
450 .IX Subsection "How do I put a password on my web pages?"
451 要启用 web 服务器的验证,你需要配置你的 web 服务器,不同的服务器有不同的方法\-\-\-apache 与 iPlanet 不同,后者又与 \s-1IIS\s0 不同。从你的 web 服务器的文档中查找特定服务器的配置细节。
452 .Sh "如何用 Perl 修改我的 .htpasswd 和 .htgroup 文件?"
453 .IX Subsection "How do I edit my .htpasswd and .htgroup files with Perl?"
454 HTTPD::UserAdmin 和 HTTPD::GroupAdmin 等模组为这些档案提供了统一的物件导向介面,尽管这些档案可能以各种不同的格式储存。这些资料库可能是纯文字格式、 dbm、Berkeley DB或任何 DBI相容的资料库驱动程式 (drivers)。 HTTPD::UserAdmin支援`Basic' 和 `Digest'这两个认证模式所用的档案。以下是 一例:
456 .Vb 4
457 \&    use HTTPD::UserAdmin ();
458 \&    HTTPD::UserAdmin
459 \&          ->new(DB => "/foo/.htpasswd")
460 \&          ->add($username => $password);
462 .Sh "如何确保用户不会在表单中输入使我的 CGI 脚本作坏事的值?"
463 .IX Subsection "How do I make sure users can't enter values into a form that cause my CGI script to do bad things?"
464 阅读 \s-1CGI\s0 Meta \s-1FAQ\s0 列出的安全索引
466 .Vb 1
467 \&        http://www.perl.org/CGI_MetaFAQ.html
469 .Sh "如何解释一个邮件头?"
470 .IX Subsection "How do I parse a mail header?"
471 要使用一个快速的方法,可以这样使用 perlfunc 中的 \*(L"split\*(R" 函数:
473 .Vb 4
474 \&    $/ = '';
475 \&    $header = <MSG>;
476 \&    $header =~ s/\en\es+/ /g;      # 将延续行合并成单行
477 \&    %head = ( UNIX_FROM_LINE, split /^([-\ew]+):\es*/m, $header );
480 但是,如果您若想保留所有 Received栏位资料的话【因 Received 栏位通常不止一个】,这个解法便不太行了。一个完整的解法是使用收录在 CPAN的 Mail::Header 模组( MailTools 套件的一部分)。
481 .Sh "如何解码一个 CGI 表单?"
482 .IX Subsection "How do I decode a CGI form?"
483 使用标准模块,应该是 \s-1CGI\s0.pm。没有理由去尝试手动去做!
485 你大概都看过一大堆从 STDIN 读取与 $ENV{CONTENT_LENGTH} 长度相同的字节,或者获取 $ENV{QUERY_STRING} 来解码 GET。这些程序都非常糟糕。他们仅在某些时候工作。他们通常不检查 read() 的返回值,这是主要的错误。他们不处理 \s-1HEAD\s0 请求。他们不处理文件上载时的多成分表单。They don't deal
486 with \s-1GET/POST\s0 combinations where query fields are in more than one place.
487 They don't deal with keywords in the query string.
489 In short, they're bad hacks.  Resist them at all costs.  Please do not be
490 tempted to reinvent the wheel.  Instead, use the \s-1CGI\s0.pm or CGI_Lite.pm
491 (available from \s-1CPAN\s0), or if you're trapped in the module-free land
492 of perl1 .. perl4, you might look into cgi\-lib.pl (available from
493 http://cgi\-lib.stanford.edu/cgi\-lib/ ).
495 Make sure you know whether to use a \s-1GET\s0 or a \s-1POST\s0 in your form.
496 GETs should only be used for something that doesn't update the server.
497 Otherwise you can get mangled databases and repeated feedback mail
498 messages.  The fancy word for this is ``idempotency''.  This simply
499 means that there should be no difference between making a \s-1GET\s0 request
500 for a particular \s-1URL\s0 once or multiple times.  This is because the
501 \&\s-1HTTP\s0 protocol definition says that a \s-1GET\s0 request may be cached by the
502 browser, or server, or an intervening proxy.  \s-1POST\s0 requests cannot be
503 cached, because each request is independent and matters.  Typically,
504 \&\s-1POST\s0 requests change or depend on state on the server (query or update
505 a database, send mail, or purchase a computer).
506 .Sh "如何检测一个有效的邮件地址?"
507 .IX Subsection "How do I check a valid mail address?"
508 没有办法。至少,没有可行的办法。
510 如果没有寄封信到一个位址去试试看它会不会弹回来(即使是这麽做您还得面对停顿的问题),您是无法确定一个位址是否真的存在的。即使您套用 email 标头的标准规格来做检查的依据,您还是有可能会遇到问题,因为有些送得到的位址并不 符合 RFC-822(电子邮件标头的标准)的规定,但有些符合标准的位址却无法投 递。
512 You can use the Email::Valid or RFC::RFC822::Address which check
513 the format of the address, although they cannot actually tell you
514 if it is a deliverable address (i.e. that mail to the address
515 will not bounce).  Modules like Mail::CheckUser and Mail::EXPN
516 try to interact with the domain name system or particular
517 mail servers to learn even more, but their methods do not
518 work everywhere\-\-\-especially for security conscious administrators.
520 许多人试图用一个简单的正规表示式,例如 \f(CW\*(C`/^[\ew.\-]+\e@(?:[\ew\-]+\e.)+\ew+$/\*(C'\fR 来消除一些通常是无效的 email 位址。不过,这样做也把很多合格的位址给一起滤掉了,而且对测试一个位址有没有希望投递成功完全没有帮助,所以在此建议大家不要这麽做;不过您可以看看:
521 http://www.cpan.org/authors/Tom_Christiansen/scripts/ckaddr.gz ,
522 这个 script真的彻底地依据所有的 RFC规定来做检验(除了内嵌式 comments外),同时会排除一些您可能不会想送信去的位址(如 Bill Clinton【美国总统】或您的 postmaster),然後它会确定位址中的主机名称可在 DNS中找得到。这个 script 跑起来不是很快,但至少有效。
524 Our best advice for verifying a person's mail address is to have them
525 enter their address twice, just as you normally do to change a password.
526 This usually weeds out typos.  If both versions match, send
527 mail to that address with a personal message that looks somewhat like:
529 .Vb 1
530 \&    Dear someuser@host.com,
533 .Vb 5
534 \&    Please confirm the mail address you gave us Wed May  6 09:38:41
535 \&    MDT 1998 by replying to this message.  Include the string
536 \&    "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
537 \&    start with "Nik...".  Once this is done, your confirmed address will
538 \&    be entered into our records.
541 If you get the message back and they've followed your directions,
542 you can be reasonably assured that it's real.
544 A related strategy that's less open to forgery is to give them a \s-1PIN\s0
545 (personal \s-1ID\s0 number).  Record the address and \s-1PIN\s0 (best that it be a
546 random one) for later processing.  In the mail you send, ask them to
547 include the \s-1PIN\s0 in their reply.  But if it bounces, or the message is
548 included via a ``vacation'' script, it'll be there anyway.  So it's
549 best to ask them to mail back a slight alteration of the \s-1PIN\s0, such as
550 with the characters reversed, one added or subtracted to each digit, etc.
551 .Sh "如何解码一个 MIME/BASE64 字符串?"
552 .IX Subsection "How do I decode a MIME/BASE64 string?"
553 MIME-tools套件(可自 CPAN取得)不但可处理这个问题而且有许多其他的功能。有了这个套件,解 BASE64码就变得像这麽容易:
555 .Vb 2
556 \&    use MIME::Base64;
557 \&    $decoded = decode_base64($encoded);
560 The MIME-Tools package (available from \s-1CPAN\s0) supports extraction with
561 decoding of \s-1BASE64\s0 encoded attachments and content directly from email
562 messages.
564 一个比较直接的解法是先做一点简单的转译,然後使用 unpack()这个函数的 ``u'' 格式:
566 .Vb 4
567 \&    tr#A-Za-z0-9+/##cd;                   # remove non-base64 chars
568 \&    tr#A-Za-z0-9+/# -_#;                  # convert to uuencoded format
569 \&    $len = pack("c", 32 + 0.75*length);   # compute length byte
570 \&    print unpack("u", $len . $_);         # uudecode and print
572 .Sh "如何返回用户的邮件地址?"
573 .IX Subsection "How do I return the user's mail address?"
574 On systems that support getpwuid, the $< variable, and the
575 Sys::Hostname module (which is part of the standard perl distribution),
576 you can probably try using something like this:
578 .Vb 2
579 \&    use Sys::Hostname;
580 \&    $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
583 Company policies on mail address can mean that this generates addresses
584 that the company's mail system will not accept, so you should ask for
585 users' mail addresses when this matters.  Furthermore, not all systems
586 on which Perl runs are so forthcoming with this information as is Unix.
588 The Mail::Util module from \s-1CPAN\s0 (part of the MailTools package) provides a
589 \&\fImailaddress()\fR function that tries to guess the mail address of the user.
590 It makes a more intelligent guess than the code above, using information
591 given when the module was installed, but it could still be incorrect.
592 Again, the best way is often just to ask the user.
593 .Sh "如何发邮件?"
594 .IX Subsection "How do I send mail?"
595 Use the \f(CW\*(C`sendmail\*(C'\fR program directly:
597 .Vb 6
598 \&    open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
599 \&                        or die "Can't fork for sendmail: $!\en";
600 \&    print SENDMAIL <<"EOF";
601 \&    From: User Originating Mail <me\e@host>
602 \&    To: Final Destination <you\e@otherhost>
603 \&    Subject: A relevant subject line
606 .Vb 4
607 \&    Body of the message goes here after the blank line
608 \&    in as many lines as you like.
609 \&    EOF
610 \&    close(SENDMAIL)     or warn "sendmail didn't close nicely";
613 The \fB\-oi\fR option prevents sendmail from interpreting a line consisting
614 of a single dot as \*(L"end of message\*(R".  The \fB\-t\fR option says to use the
615 headers to decide who to send the message to, and \fB\-odq\fR says to put
616 the message into the queue.  This last option means your message won't
617 be immediately delivered, so leave it out if you want immediate
618 delivery.
620 Alternate, less convenient approaches include calling mail (sometimes
621 called mailx) directly or simply opening up port 25 have having an
622 intimate conversation between just you and the remote \s-1SMTP\s0 daemon,
623 probably sendmail.
625 Or you might be able use the \s-1CPAN\s0 module Mail::Mailer:
627 .Vb 1
628 \&    use Mail::Mailer;
631 .Vb 8
632 \&    $mailer = Mail::Mailer->new();
633 \&    $mailer->open({ From    => $from_address,
634 \&                    To      => $to_address,
635 \&                    Subject => $subject,
636 \&                  })
637 \&        or die "Can't open: $!\en";
638 \&    print $mailer $body;
639 \&    $mailer->close();
642 The Mail::Internet module uses Net::SMTP which is less Unix-centric than
643 Mail::Mailer, but less reliable.  Avoid raw \s-1SMTP\s0 commands.  There
644 are many reasons to use a mail transport agent like sendmail.  These
645 include queuing, \s-1MX\s0 records, and security.
646 .Sh "如何使用 MIME 来为邮件消息增加附件?"
647 .IX Subsection "How do I use MIME to make an attachment to a mail message?"
648 This answer is extracted directly from the MIME::Lite documentation.
649 Create a multipart message (i.e., one with attachments).
651 .Vb 1
652 \&    use MIME::Lite;
655 .Vb 8
656 \&    ### Create a new multipart message:
657 \&    $msg = MIME::Lite->new(
658 \&                 From    =>'me@myhost.com',
659 \&                 To      =>'you@yourhost.com',
660 \&                 Cc      =>'some@other.com, some@more.com',
661 \&                 Subject =>'A message with 2 parts...',
662 \&                 Type    =>'multipart/mixed'
663 \&                 );
666 .Vb 8
667 \&    ### Add parts (each "attach" has same arguments as "new"):
668 \&    $msg->attach(Type     =>'TEXT',
669 \&                 Data     =>"Here's the GIF file you wanted"
670 \&                 );
671 \&    $msg->attach(Type     =>'image/gif',
672 \&                 Path     =>'aaa000123.gif',
673 \&                 Filename =>'logo.gif'
674 \&                 );
677 .Vb 1
678 \&    $text = $msg->as_string;
681 MIME::Lite also includes a method for sending these things.
683 .Vb 1
684 \&    $msg->send;
687 This defaults to using sendmail but can be customized to use
688 \&\s-1SMTP\s0 via Net::SMTP.
689 .Sh "如何读邮件?"
690 .IX Subsection "How do I read mail?"
691 While you could use the Mail::Folder module from \s-1CPAN\s0 (part of the
692 MailFolder package) or the Mail::Internet module from \s-1CPAN\s0 (part
693 of the MailTools package), often a module is overkill.  Here's a
694 mail sorter.
696 .Vb 1
697 \&    #!/usr/bin/perl
700 .Vb 13
701 \&    my(@msgs, @sub);
702 \&    my $msgno = -1;
703 \&    $/ = '';                    # paragraph reads
704 \&    while (<>) {
705 \&        if (/^From /m) {
706 \&            /^Subject:\es*(?:Re:\es*)*(.*)/mi;
707 \&            $sub[++$msgno] = lc($1) || '';
708 \&        }
709 \&        $msgs[$msgno] .= $_;
710 \&    }
711 \&    for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
712 \&        print $msgs[$i];
713 \&    }
716 Or more succinctly,
718 .Vb 6
719 \&    #!/usr/bin/perl -n00
720 \&    # bysub2 - awkish sort-by-subject
721 \&    BEGIN { $msgno = -1 }
722 \&    $sub[++$msgno] = (/^Subject:\es*(?:Re:\es*)*(.*)/mi)[0] if /^From/m;
723 \&    $msg[$msgno] .= $_;
724 \&    END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
726 .Sh "如何找到我的主机名/域名/IP 地址?"
727 .IX Subsection "How do I find out my hostname/domainname/IP address?"
728 长久以来许多 code都很草率地直接呼叫 `hostname` 这个程式来取得主机名。虽然这麽做很方便,但也同时增加了移植到其他平台上的困难。这是一个很典型的例子,在方便和可移植性之间作抉择,不论选哪一边,必须付出一些牺牲和代价。
730 Sys::Hostname这个模组(标准 perl发行的一部分)可用来取得机器的名字,然後您便可利用 gethostbyname()这个系统呼叫来找出该机的 IP位址了(假定您的 DNS 运作正常)。
732 .Vb 4
733 \&    use Socket;
734 \&    use Sys::Hostname;
735 \&    my $host = hostname();
736 \&    my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));
739 至少在 Unix 底下,取得 DNS网域名最简单的方法大概要算是直接从 /etc/resolv.conf 这个档案里面找。当然,这麽做的前提是 resolv.conf 这个档案的设定必须照惯例的格式,还有就是这个档案必先存在才行。
741 (Perl在非 Unix系统下尚需要一有效的方法来测出机器和网域名)
742 .Sh "如何获取一篇新闻文章或活动的新闻组?"
743 .IX Subsection "How do I fetch a news article or the active newsgroups?"
744 使用 Net::NNTP或 News::NNTPClient模组,两者皆可自 CPAN下载。这些模组让抓群组名录这类的差事变得这麽容易:
746 .Vb 2
747 \&    perl -MNews::NNTPClient
748 \&      -e 'print News::NNTPClient->new->list("newsgroups")'
750 .Sh "如何获取/上传一个 FTP 文件?"
751 .IX Subsection "How do I fetch/put an FTP file?"
752 LWP::Simple模组(可自 CPAN下载)可以抓,但不能上传档案。 Net::FTP模组(也可自 CPAN下载)虽比较复杂,但可用来上传、也能抓档案。
753 .Sh "如何进行远程过程调用 RPC ?"
754 .IX Subsection "How can I do RPC in Perl?"
755 模块 \s-1DCE::RPC\s0 正在开发中 (但是还不可用),将成为 DCE-Perl 包 (可以从 CPAN 下载) 的一部分。rpcgen 套件,可以从 CPAN/authors/id/JAKE/ 找到,是一个 \s-1RPC\s0 存根生成器,包含一个 \s-1RPC::ONC\s0 模块。
756 .SH "AUTHOR AND COPYRIGHT"
757 .IX Header "AUTHOR AND COPYRIGHT"
758 Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington.
759 All rights reserved.
761 This documentation is free; you can redistribute it and/or modify it
762 under the same terms as Perl itself.
764 Irrespective of its distribution, all code examples in this file
765 are hereby placed into the public domain.  You are permitted and
766 encouraged to use this code in your own programs for fun
767 or for profit as you see fit.  A simple comment in the code giving
768 credit would be courteous but is not required.
769 .SH "译者"
770 .B 萧百龄,两只老虎工作室