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