This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add a perl592delta.pod man page.
[perl5.git] / pod / perlfaq9.pod
CommitLineData
68dc0745 1=head1 NAME
2
5cd0b561 3perlfaq9 - Networking ($Revision: 1.15 $, $Date: 2003/01/31 17:36:57 $)
68dc0745 4
5=head1 DESCRIPTION
6
7This section deals with questions related to networking, the internet,
8and a few on the web.
9
24f1ba9b 10=head2 What is the correct form of response from a CGI script?
68dc0745 11
24f1ba9b
JH
12(Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...)
13
197aec24
RGS
14The Common Gateway Interface (CGI) specifies a software interface between
15a program ("CGI script") and a web server (HTTPD). It is not specific
16to Perl, and has its own FAQs and tutorials, and usenet group,
17comp.infosystems.www.authoring.cgi
24f1ba9b 18
1577cd80 19The original CGI specification is at: http://hoohoo.ncsa.uiuc.edu/cgi/
24f1ba9b 20
1577cd80 21Current best-practice RFC draft at: http://CGI-Spec.Golux.Com/
24f1ba9b
JH
22
23Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html
68dc0745 24
197aec24 25These Perl FAQs very selectively cover some CGI issues. However, Perl
24f1ba9b 26programmers are strongly advised to use the CGI.pm module, to take care
197aec24 27of the details for them.
68dc0745 28
24f1ba9b
JH
29The similarity between CGI response headers (defined in the CGI
30specification) and HTTP response headers (defined in the HTTP
31specification, RFC2616) is intentional, but can sometimes be confusing.
68dc0745 32
24f1ba9b
JH
33The CGI specification defines two kinds of script: the "Parsed Header"
34script, and the "Non Parsed Header" (NPH) script. Check your server
35documentation to see what it supports. "Parsed Header" scripts are
36simpler in various respects. The CGI specification allows any of the
37usual newline representations in the CGI response (it's the server's
38job to create an accurate HTTP response based on it). So "\n" written in
39text mode is technically correct, and recommended. NPH scripts are more
40tricky: they must put out a complete and accurate set of HTTP
41transaction response headers; the HTTP specification calls for records
42to be terminated with carriage-return and line-feed, i.e ASCII \015\012
43written in binary mode.
68dc0745 44
24f1ba9b
JH
45Using CGI.pm gives excellent platform independence, including EBCDIC
46systems. CGI.pm selects an appropriate newline representation
47($CGI::CRLF) and sets binmode as appropriate.
c8db1d39 48
24f1ba9b 49=head2 My CGI script runs from the command line but not the browser. (500 Server Error)
c8db1d39 50
0bc0ad85
JH
51Several things could be wrong. You can go through the "Troubleshooting
52Perl CGI scripts" guide at
53
54 http://www.perl.org/troubleshooting_CGI.html
55
197aec24 56If, after that, you can demonstrate that you've read the FAQs and that
24f1ba9b
JH
57your problem isn't something simple that can be easily answered, you'll
58probably receive a courteous and useful reply to your question if you
59post it on comp.infosystems.www.authoring.cgi (if it's something to do
60with HTTP or the CGI protocols). Questions that appear to be Perl
61questions but are really CGI ones that are posted to comp.lang.perl.misc
62are not so well received.
c8db1d39 63
197aec24 64The useful FAQs, related documents, and troubleshooting guides are
24f1ba9b
JH
65listed in the CGI Meta FAQ:
66
67 http://www.perl.org/CGI_MetaFAQ.html
c8db1d39 68
c8db1d39
TC
69
70=head2 How can I get better error messages from a CGI program?
71
72Use the CGI::Carp module. It replaces C<warn> and C<die>, plus the
73normal Carp modules C<carp>, C<croak>, and C<confess> functions with
74more verbose and safer versions. It still sends them to the normal
75server error log.
76
77 use CGI::Carp;
78 warn "This is a complaint";
79 die "But this one is serious";
80
81The following use of CGI::Carp also redirects errors to a file of your choice,
82placed in a BEGIN block to catch compile-time warnings as well:
83
84 BEGIN {
85 use CGI::Carp qw(carpout);
86 open(LOG, ">>/var/local/cgi-logs/mycgi-log")
87 or die "Unable to append to mycgi-log: $!\n";
88 carpout(*LOG);
89 }
90
91You can even arrange for fatal errors to go back to the client browser,
92which is nice for your own debugging, but might confuse the end user.
93
94 use CGI::Carp qw(fatalsToBrowser);
95 die "Bad error here";
96
97Even if the error happens before you get the HTTP header out, the module
98will try to take care of this to avoid the dreaded server 500 errors.
99Normal warnings still go out to the server error log (or wherever
100you've sent them with C<carpout>) with the application name and date
101stamp prepended.
102
68dc0745 103=head2 How do I remove HTML from a string?
104
f29c64d6 105The most correct way (albeit not the fastest) is to use HTML::Parser
bed171df 106from CPAN. Another mostly correct
7d7e76cf
MS
107way is to use HTML::FormatText which not only removes HTML but also
108attempts to do a little simple formatting of the resulting plain text.
68dc0745 109
110Many folks attempt a simple-minded regular expression approach, like
c47ff5f1 111C<< s/<.*?>//g >>, but that fails in many cases because the tags
68dc0745 112may continue over line breaks, they may contain quoted angle-brackets,
a6dd486b
JB
113or HTML comment may be present. Plus, folks forget to convert
114entities--like C<&lt;> for example.
68dc0745 115
116Here's one "simple-minded" approach, that works for most files:
117
118 #!/usr/bin/perl -p0777
119 s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
120
121If you want a more complete solution, see the 3-stage striphtml
122program in
a93751fa 123http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz
68dc0745 124.
125
c8db1d39
TC
126Here are some tricky cases that you should think about when picking
127a solution:
128
129 <IMG SRC = "foo.gif" ALT = "A > B">
130
d92eb7b0 131 <IMG SRC = "foo.gif"
c8db1d39
TC
132 ALT = "A > B">
133
134 <!-- <A comment> -->
135
136 <script>if (a<b && a>c)</script>
137
138 <# Just data #>
139
140 <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
141
142If HTML comments include other tags, those solutions would also break
143on text like this:
144
145 <!-- This section commented out.
146 <B>You can't see me!</B>
147 -->
148
68dc0745 149=head2 How do I extract URLs?
150
e67d034e
JH
151You can easily extract all sorts of URLs from HTML with
152C<HTML::SimpleLinkExtor> which handles anchors, images, objects,
197aec24
RGS
153frames, and many other tags that can contain a URL. If you need
154anything more complex, you can create your own subclass of
155C<HTML::LinkExtor> or C<HTML::Parser>. You might even use
e67d034e
JH
156C<HTML::SimpleLinkExtor> as an example for something specifically
157suited to your needs.
158
49d635f9
RGS
159You can use URI::Find to extract URLs from an arbitrary text document.
160
197aec24 161Less complete solutions involving regular expressions can save
e67d034e
JH
162you a lot of processing time if you know that the input is simple. One
163solution from Tom Christiansen runs 100 times faster than most
164module based approaches but only extracts URLs from anchors where the first
197aec24 165attribute is HREF and there are no other attributes.
e67d034e
JH
166
167 #!/usr/bin/perl -n00
168 # qxurl - tchrist@perl.com
169 print "$2\n" while m{
170 < \s*
171 A \s+ HREF \s* = \s* (["']) (.*?) \1
172 \s* >
173 }gsix;
174
68dc0745 175
176=head2 How do I download a file from the user's machine? How do I open a file on another machine?
177
49d635f9
RGS
178In this case, download means to use the file upload feature of HTML
179forms. You allow the web surfer to specify a file to send to your web
180server. To you it looks like a download, and to the user it looks
181like an upload. No matter what you call it, you do it with what's
182known as B<multipart/form-data> encoding. The CGI.pm module (which
183comes with Perl as part of the Standard Library) supports this in the
184start_multipart_form() method, which isn't the same as the startform()
185method.
186
187See the section in the CGI.pm documentation on file uploads for code
188examples and details.
68dc0745 189
190=head2 How do I make a pop-up menu in HTML?
191
c47ff5f1 192Use the B<< <SELECT> >> and B<< <OPTION> >> tags. The CGI.pm
68dc0745 193module (available from CPAN) supports this widget, as well as many
194others, including some that it cleverly synthesizes on its own.
195
196=head2 How do I fetch an HTML file?
197
46fc3d4c 198One approach, if you have the lynx text-based HTML browser installed
199on your system, is this:
68dc0745 200
201 $html_code = `lynx -source $url`;
202 $text_data = `lynx -dump $url`;
203
d92eb7b0
GS
204The libwww-perl (LWP) modules from CPAN provide a more powerful way
205to do this. They don't require lynx, but like lynx, can still work
206through proxies:
46fc3d4c 207
c8db1d39
TC
208 # simplest version
209 use LWP::Simple;
210 $content = get($URL);
211
212 # or print HTML from a URL
46fc3d4c 213 use LWP::Simple;
6cecdcac 214 getprint "http://www.linpro.no/lwp/";
46fc3d4c 215
c8db1d39 216 # or print ASCII from HTML from a URL
65acb1b1 217 # also need HTML-Tree package from CPAN
46fc3d4c 218 use LWP::Simple;
f29c64d6 219 use HTML::Parser;
46fc3d4c 220 use HTML::FormatText;
221 my ($html, $ascii);
222 $html = get("http://www.perl.com/");
223 defined $html
224 or die "Can't fetch HTML from http://www.perl.com/";
225 $ascii = HTML::FormatText->new->format(parse_html($html));
226 print $ascii;
227
c8db1d39
TC
228=head2 How do I automate an HTML form submission?
229
230If you're submitting values using the GET method, create a URL and encode
231the form using the C<query_form> method:
232
233 use LWP::Simple;
234 use URI::URL;
235
236 my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
237 $url->query_form(module => 'DB_File', readme => 1);
238 $content = get($url);
239
240If you're using the POST method, create your own user agent and encode
241the content appropriately.
242
243 use HTTP::Request::Common qw(POST);
244 use LWP::UserAgent;
245
246 $ua = LWP::UserAgent->new();
247 my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
248 [ module => 'DB_File', readme => 1 ];
249 $content = $ua->request($req)->as_string;
250
251=head2 How do I decode or create those %-encodings on the web?
68dc0745 252
68dc0745 253
575cc754
JH
254If you are writing a CGI script, you should be using the CGI.pm module
255that comes with perl, or some other equivalent module. The CGI module
256automatically decodes queries for you, and provides an escape()
257function to handle encoding.
68dc0745 258
575cc754
JH
259
260The best source of detailed information on URI encoding is RFC 2396.
261Basically, the following substitutions do it:
262
48a4adce 263 s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg; # encode
575cc754 264
f05bbc40 265 s/%([A-Fa-f\d]{2})/chr hex $1/eg; # decode
575cc754
JH
266
267However, you should only apply them to individual URI components, not
268the entire URI, otherwise you'll lose information and generally mess
269things up. If that didn't explain it, don't worry. Just go read
270section 2 of the RFC, it's probably the best explanation there is.
271
272RFC 2396 also contains a lot of other useful information, including a
273regexp for breaking any arbitrary URI into components (Appendix B).
68dc0745 274
275=head2 How do I redirect to another page?
276
24f1ba9b
JH
277Specify the complete URL of the destination (even if it is on the same
278server). This is one of the two different kinds of CGI "Location:"
279responses which are defined in the CGI specification for a Parsed Headers
280script. The other kind (an absolute URLpath) is resolved internally to
281the server without any HTTP redirection. The CGI specifications do not
282allow relative URLs in either case.
283
284Use of CGI.pm is strongly recommended. This example shows redirection
285with a complete URL. This redirection is handled by the web browser.
286
287 use CGI qw/:standard/;
288
a93751fa 289 my $url = 'http://www.cpan.org/';
24f1ba9b 290 print redirect($url);
68dc0745 291
68dc0745 292
24f1ba9b
JH
293This example shows a redirection with an absolute URLpath. This
294redirection is handled by the local web server.
68dc0745 295
24f1ba9b
JH
296 my $url = '/CPAN/index.html';
297 print redirect($url);
c8db1d39 298
d92eb7b0 299
197aec24 300But if coded directly, it could be as follows (the final "\n" is
24f1ba9b 301shown separately, for clarity), using either a complete URL or
197aec24 302an absolute URLpath.
d92eb7b0 303
24f1ba9b
JH
304 print "Location: $url\n"; # CGI response header
305 print "\n"; # end of headers
d92eb7b0 306
c8db1d39 307
68dc0745 308=head2 How do I put a password on my web pages?
309
49d635f9
RGS
310To enable authentication for your web server, you need to configure
311your web server. The configuration is different for different sorts
312of web servers---apache does it differently from iPlanet which does
313it differently from IIS. Check your web server documentation for
314the details for your particular server.
68dc0745 315
316=head2 How do I edit my .htpasswd and .htgroup files with Perl?
317
318The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
319consistent OO interface to these files, regardless of how they're
426affbf
LS
320stored. Databases may be text, dbm, Berkeley DB or any database with
321a DBI compatible driver. HTTPD::UserAdmin supports files used by the
68dc0745 322`Basic' and `Digest' authentication schemes. Here's an example:
323
324 use HTTPD::UserAdmin ();
325 HTTPD::UserAdmin
326 ->new(DB => "/foo/.htpasswd")
327 ->add($username => $password);
328
46fc3d4c 329=head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
330
24f1ba9b 331See the security references listed in the CGI Meta FAQ
46fc3d4c 332
24f1ba9b 333 http://www.perl.org/CGI_MetaFAQ.html
46fc3d4c 334
5a964f20 335=head2 How do I parse a mail header?
68dc0745 336
337For a quick-and-dirty solution, try this solution derived
b73a15ae 338from L<perlfunc/split>:
68dc0745 339
340 $/ = '';
341 $header = <MSG>;
342 $header =~ s/\n\s+/ /g; # merge continuation lines
343 %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
344
345That solution doesn't do well if, for example, you're trying to
346maintain all the Received lines. A more complete approach is to use
347the Mail::Header module from CPAN (part of the MailTools package).
348
349=head2 How do I decode a CGI form?
350
c8db1d39
TC
351You use a standard module, probably CGI.pm. Under no circumstances
352should you attempt to do so by hand!
353
354You'll see a lot of CGI programs that blindly read from STDIN the number
355of bytes equal to CONTENT_LENGTH for POSTs, or grab QUERY_STRING for
356decoding GETs. These programs are very poorly written. They only work
357sometimes. They typically forget to check the return value of the read()
358system call, which is a cardinal sin. They don't handle HEAD requests.
359They don't handle multipart forms used for file uploads. They don't deal
360with GET/POST combinations where query fields are in more than one place.
361They don't deal with keywords in the query string.
362
363In short, they're bad hacks. Resist them at all costs. Please do not be
364tempted to reinvent the wheel. Instead, use the CGI.pm or CGI_Lite.pm
365(available from CPAN), or if you're trapped in the module-free land
366of perl1 .. perl4, you might look into cgi-lib.pl (available from
65acb1b1 367http://cgi-lib.stanford.edu/cgi-lib/ ).
c8db1d39
TC
368
369Make sure you know whether to use a GET or a POST in your form.
370GETs should only be used for something that doesn't update the server.
371Otherwise you can get mangled databases and repeated feedback mail
372messages. The fancy word for this is ``idempotency''. This simply
373means that there should be no difference between making a GET request
374for a particular URL once or multiple times. This is because the
375HTTP protocol definition says that a GET request may be cached by the
376browser, or server, or an intervening proxy. POST requests cannot be
377cached, because each request is independent and matters. Typically,
378POST requests change or depend on state on the server (query or update
379a database, send mail, or purchase a computer).
68dc0745 380
5a964f20 381=head2 How do I check a valid mail address?
68dc0745 382
c8db1d39 383You can't, at least, not in real time. Bummer, eh?
68dc0745 384
c8db1d39
TC
385Without sending mail to the address and seeing whether there's a human
386on the other hand to answer you, you cannot determine whether a mail
387address is valid. Even if you apply the mail header standard, you
388can have problems, because there are deliverable addresses that aren't
389RFC-822 (the mail header standard) compliant, and addresses that aren't
390deliverable which are compliant.
68dc0745 391
49d635f9
RGS
392You can use the Email::Valid or RFC::RFC822::Address which check
393the format of the address, although they cannot actually tell you
394if it is a deliverable address (i.e. that mail to the address
395will not bounce). Modules like Mail::CheckUser and Mail::EXPN
396try to interact with the domain name system or particular
397mail servers to learn even more, but their methods do not
398work everywhere---especially for security conscious administrators.
399
c8db1d39 400Many are tempted to try to eliminate many frequently-invalid
d92eb7b0 401mail addresses with a simple regex, such as
b8c8cfe2 402C</^[\w.-]+\@(?:[\w-]+\.)+\w+$/>. It's a very bad idea. However,
c8db1d39 403this also throws out many valid ones, and says nothing about
b8c8cfe2 404potential deliverability, so it is not suggested. Instead, see
1577cd80 405http://www.cpan.org/authors/Tom_Christiansen/scripts/ckaddr.gz ,
68dc0745 406which actually checks against the full RFC spec (except for nested
5a964f20 407comments), looks for addresses you may not wish to accept mail to
68dc0745 408(say, Bill Clinton or your postmaster), and then makes sure that the
c8db1d39
TC
409hostname given can be looked up in the DNS MX records. It's not fast,
410but it works for what it tries to do.
411
412Our best advice for verifying a person's mail address is to have them
413enter their address twice, just as you normally do to change a password.
414This usually weeds out typos. If both versions match, send
415mail to that address with a personal message that looks somewhat like:
416
417 Dear someuser@host.com,
418
419 Please confirm the mail address you gave us Wed May 6 09:38:41
420 MDT 1998 by replying to this message. Include the string
421 "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
422 start with "Nik...". Once this is done, your confirmed address will
423 be entered into our records.
424
425If you get the message back and they've followed your directions,
426you can be reasonably assured that it's real.
68dc0745 427
c8db1d39
TC
428A related strategy that's less open to forgery is to give them a PIN
429(personal ID number). Record the address and PIN (best that it be a
430random one) for later processing. In the mail you send, ask them to
431include the PIN in their reply. But if it bounces, or the message is
432included via a ``vacation'' script, it'll be there anyway. So it's
433best to ask them to mail back a slight alteration of the PIN, such as
434with the characters reversed, one added or subtracted to each digit, etc.
46fc3d4c 435
68dc0745 436=head2 How do I decode a MIME/BASE64 string?
437
6a0af2f1
GA
438The MIME-Base64 package (available from CPAN) handles this as well as
439the MIME/QP encoding. Decoding BASE64 becomes as simple as:
68dc0745 440
6a0af2f1 441 use MIME::Base64;
68dc0745 442 $decoded = decode_base64($encoded);
443
26d9b02f 444The MIME-Tools package (available from CPAN) supports extraction with
6a0af2f1
GA
445decoding of BASE64 encoded attachments and content directly from email
446messages.
447
448If the string to decode is short (less than 84 bytes long)
449a more direct approach is to use the unpack() function's "u"
68dc0745 450format after minor transliterations:
451
452 tr#A-Za-z0-9+/##cd; # remove non-base64 chars
453 tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
454 $len = pack("c", 32 + 0.75*length); # compute length byte
455 print unpack("u", $len . $_); # uudecode and print
456
5a964f20 457=head2 How do I return the user's mail address?
68dc0745 458
a6dd486b 459On systems that support getpwuid, the $< variable, and the
68dc0745 460Sys::Hostname module (which is part of the standard perl distribution),
461you can probably try using something like this:
462
463 use Sys::Hostname;
231ab6d1 464 $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
68dc0745 465
5a964f20
TC
466Company policies on mail address can mean that this generates addresses
467that the company's mail system will not accept, so you should ask for
468users' mail addresses when this matters. Furthermore, not all systems
68dc0745 469on which Perl runs are so forthcoming with this information as is Unix.
470
471The Mail::Util module from CPAN (part of the MailTools package) provides a
472mailaddress() function that tries to guess the mail address of the user.
473It makes a more intelligent guess than the code above, using information
474given when the module was installed, but it could still be incorrect.
475Again, the best way is often just to ask the user.
476
c8db1d39 477=head2 How do I send mail?
68dc0745 478
c8db1d39
TC
479Use the C<sendmail> program directly:
480
481 open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
482 or die "Can't fork for sendmail: $!\n";
483 print SENDMAIL <<"EOF";
484 From: User Originating Mail <me\@host>
485 To: Final Destination <you\@otherhost>
486 Subject: A relevant subject line
487
65acb1b1
TC
488 Body of the message goes here after the blank line
489 in as many lines as you like.
c8db1d39
TC
490 EOF
491 close(SENDMAIL) or warn "sendmail didn't close nicely";
492
493The B<-oi> option prevents sendmail from interpreting a line consisting
494of a single dot as "end of message". The B<-t> option says to use the
495headers to decide who to send the message to, and B<-odq> says to put
496the message into the queue. This last option means your message won't
497be immediately delivered, so leave it out if you want immediate
498delivery.
499
d92eb7b0
GS
500Alternate, less convenient approaches include calling mail (sometimes
501called mailx) directly or simply opening up port 25 have having an
502intimate conversation between just you and the remote SMTP daemon,
503probably sendmail.
504
505Or you might be able use the CPAN module Mail::Mailer:
c8db1d39
TC
506
507 use Mail::Mailer;
508
509 $mailer = Mail::Mailer->new();
510 $mailer->open({ From => $from_address,
511 To => $to_address,
512 Subject => $subject,
513 })
514 or die "Can't open: $!\n";
515 print $mailer $body;
516 $mailer->close();
517
518The Mail::Internet module uses Net::SMTP which is less Unix-centric than
519Mail::Mailer, but less reliable. Avoid raw SMTP commands. There
d92eb7b0 520are many reasons to use a mail transport agent like sendmail. These
8305e449 521include queuing, MX records, and security.
c8db1d39 522
575cc754
JH
523=head2 How do I use MIME to make an attachment to a mail message?
524
525This answer is extracted directly from the MIME::Lite documentation.
526Create a multipart message (i.e., one with attachments).
527
528 use MIME::Lite;
529
530 ### Create a new multipart message:
531 $msg = MIME::Lite->new(
532 From =>'me@myhost.com',
533 To =>'you@yourhost.com',
534 Cc =>'some@other.com, some@more.com',
535 Subject =>'A message with 2 parts...',
536 Type =>'multipart/mixed'
537 );
538
539 ### Add parts (each "attach" has same arguments as "new"):
540 $msg->attach(Type =>'TEXT',
541 Data =>"Here's the GIF file you wanted"
542 );
543 $msg->attach(Type =>'image/gif',
544 Path =>'aaa000123.gif',
545 Filename =>'logo.gif'
546 );
547
548 $text = $msg->as_string;
549
550MIME::Lite also includes a method for sending these things.
551
552 $msg->send;
553
197aec24 554This defaults to using L<sendmail> but can be customized to use
575cc754
JH
555SMTP via L<Net::SMTP>.
556
c8db1d39
TC
557=head2 How do I read mail?
558
d92eb7b0 559While you could use the Mail::Folder module from CPAN (part of the
5cd0b561 560MailFolder package) or the Mail::Internet module from CPAN (part
a6dd486b 561of the MailTools package), often a module is overkill. Here's a
d92eb7b0
GS
562mail sorter.
563
564 #!/usr/bin/perl
5cd0b561 565
c8db1d39
TC
566 my(@msgs, @sub);
567 my $msgno = -1;
568 $/ = ''; # paragraph reads
569 while (<>) {
5cd0b561 570 if (/^From /m) {
c8db1d39
TC
571 /^Subject:\s*(?:Re:\s*)*(.*)/mi;
572 $sub[++$msgno] = lc($1) || '';
573 }
574 $msgs[$msgno] .= $_;
d92eb7b0 575 }
c8db1d39
TC
576 for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
577 print $msgs[$i];
578 }
579
d92eb7b0 580Or more succinctly,
c8db1d39
TC
581
582 #!/usr/bin/perl -n00
583 # bysub2 - awkish sort-by-subject
584 BEGIN { $msgno = -1 }
585 $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
586 $msg[$msgno] .= $_;
587 END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
588
68dc0745 589=head2 How do I find out my hostname/domainname/IP address?
590
c8db1d39
TC
591The normal way to find your own hostname is to call the C<`hostname`>
592program. While sometimes expedient, this has some problems, such as
593not knowing whether you've got the canonical name or not. It's one of
594those tradeoffs of convenience versus portability.
68dc0745 595
596The Sys::Hostname module (part of the standard perl distribution) will
597give you the hostname after which you can find out the IP address
598(assuming you have working DNS) with a gethostbyname() call.
599
600 use Socket;
601 use Sys::Hostname;
602 my $host = hostname();
65acb1b1 603 my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));
68dc0745 604
605Probably the simplest way to learn your DNS domain name is to grok
606it out of /etc/resolv.conf, at least under Unix. Of course, this
607assumes several things about your resolv.conf configuration, including
608that it exists.
609
610(We still need a good DNS domain name-learning method for non-Unix
611systems.)
612
613=head2 How do I fetch a news article or the active newsgroups?
614
615Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
a6dd486b 616This can make tasks like fetching the newsgroup list as simple as
68dc0745 617
618 perl -MNews::NNTPClient
619 -e 'print News::NNTPClient->new->list("newsgroups")'
620
621=head2 How do I fetch/put an FTP file?
622
623LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also
624available from CPAN) is more complex but can put as well as fetch.
625
626=head2 How can I do RPC in Perl?
627
a6dd486b 628A DCE::RPC module is being developed (but is not yet available) and
68dc0745 629will be released as part of the DCE-Perl package (available from
65acb1b1
TC
630CPAN). The rpcgen suite, available from CPAN/authors/id/JAKE/, is
631an RPC stub generator and includes an RPC::ONC module.
68dc0745 632
633=head1 AUTHOR AND COPYRIGHT
634
0bc0ad85 635Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.
5a964f20
TC
636All rights reserved.
637
5a7beb56
JH
638This documentation is free; you can redistribute it and/or modify it
639under the same terms as Perl itself.
5a964f20
TC
640
641Irrespective of its distribution, all code examples in this file
642are hereby placed into the public domain. You are permitted and
643encouraged to use this code in your own programs for fun
644or for profit as you see fit. A simple comment in the code giving
645credit would be courteous but is not required.