This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Unused 'cv'
[perl5.git] / pod / perlfaq9.pod
CommitLineData
68dc0745 1=head1 NAME
2
ee891a00 3perlfaq9 - Networking ($Revision: 8539 $)
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
e573f903
RGS
189=head2 How do I make an HTML pop-up menu with Perl?
190
191(contributed by brian d foy)
192
193The CGI.pm module (which comes with Perl) has functions to create
194the HTML form widgets. See the CGI.pm documentation for more
195examples.
196
197 use CGI qw/:standard/;
198 print header,
199 start_html('Favorite Animals'),
200
201 start_form,
202 "What's your favorite animal? ",
203 popup_menu(
204 -name => 'animal',
205 -values => [ qw( Llama Alpaca Camel Ram ) ]
206 ),
207 submit,
208
209 end_form,
210 end_html;
68dc0745 211
68dc0745 212
213=head2 How do I fetch an HTML file?
214
46fc3d4c 215One approach, if you have the lynx text-based HTML browser installed
216on your system, is this:
68dc0745 217
218 $html_code = `lynx -source $url`;
219 $text_data = `lynx -dump $url`;
220
d92eb7b0
GS
221The libwww-perl (LWP) modules from CPAN provide a more powerful way
222to do this. They don't require lynx, but like lynx, can still work
223through proxies:
46fc3d4c 224
c8db1d39
TC
225 # simplest version
226 use LWP::Simple;
227 $content = get($URL);
228
229 # or print HTML from a URL
46fc3d4c 230 use LWP::Simple;
6cecdcac 231 getprint "http://www.linpro.no/lwp/";
46fc3d4c 232
c8db1d39 233 # or print ASCII from HTML from a URL
65acb1b1 234 # also need HTML-Tree package from CPAN
46fc3d4c 235 use LWP::Simple;
f29c64d6 236 use HTML::Parser;
46fc3d4c 237 use HTML::FormatText;
238 my ($html, $ascii);
239 $html = get("http://www.perl.com/");
240 defined $html
241 or die "Can't fetch HTML from http://www.perl.com/";
242 $ascii = HTML::FormatText->new->format(parse_html($html));
243 print $ascii;
244
c8db1d39
TC
245=head2 How do I automate an HTML form submission?
246
7678cced
RGS
247If you are doing something complex, such as moving through many pages
248and forms or a web site, you can use C<WWW::Mechanize>. See its
249documentation for all the details.
250
c8db1d39
TC
251If you're submitting values using the GET method, create a URL and encode
252the form using the C<query_form> method:
253
254 use LWP::Simple;
255 use URI::URL;
256
257 my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
258 $url->query_form(module => 'DB_File', readme => 1);
259 $content = get($url);
260
261If you're using the POST method, create your own user agent and encode
262the content appropriately.
263
264 use HTTP::Request::Common qw(POST);
265 use LWP::UserAgent;
266
267 $ua = LWP::UserAgent->new();
268 my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
269 [ module => 'DB_File', readme => 1 ];
270 $content = $ua->request($req)->as_string;
271
272=head2 How do I decode or create those %-encodings on the web?
68dc0745 273
575cc754
JH
274If you are writing a CGI script, you should be using the CGI.pm module
275that comes with perl, or some other equivalent module. The CGI module
276automatically decodes queries for you, and provides an escape()
277function to handle encoding.
68dc0745 278
575cc754
JH
279The best source of detailed information on URI encoding is RFC 2396.
280Basically, the following substitutions do it:
281
48a4adce 282 s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg; # encode
575cc754 283
a05e4845
RGS
284 s/%([A-Fa-f\d]{2})/chr hex $1/eg; # decode
285 s/%([[:xdigit:]]{2})/chr hex $1/eg; # same thing
575cc754
JH
286
287However, you should only apply them to individual URI components, not
288the entire URI, otherwise you'll lose information and generally mess
289things up. If that didn't explain it, don't worry. Just go read
290section 2 of the RFC, it's probably the best explanation there is.
291
292RFC 2396 also contains a lot of other useful information, including a
293regexp for breaking any arbitrary URI into components (Appendix B).
68dc0745 294
295=head2 How do I redirect to another page?
296
24f1ba9b
JH
297Specify the complete URL of the destination (even if it is on the same
298server). This is one of the two different kinds of CGI "Location:"
299responses which are defined in the CGI specification for a Parsed Headers
300script. The other kind (an absolute URLpath) is resolved internally to
301the server without any HTTP redirection. The CGI specifications do not
302allow relative URLs in either case.
303
304Use of CGI.pm is strongly recommended. This example shows redirection
305with a complete URL. This redirection is handled by the web browser.
306
307 use CGI qw/:standard/;
308
a93751fa 309 my $url = 'http://www.cpan.org/';
24f1ba9b 310 print redirect($url);
68dc0745 311
68dc0745 312
24f1ba9b
JH
313This example shows a redirection with an absolute URLpath. This
314redirection is handled by the local web server.
68dc0745 315
24f1ba9b
JH
316 my $url = '/CPAN/index.html';
317 print redirect($url);
c8db1d39 318
d92eb7b0 319
197aec24 320But if coded directly, it could be as follows (the final "\n" is
24f1ba9b 321shown separately, for clarity), using either a complete URL or
197aec24 322an absolute URLpath.
d92eb7b0 323
24f1ba9b
JH
324 print "Location: $url\n"; # CGI response header
325 print "\n"; # end of headers
d92eb7b0 326
c8db1d39 327
68dc0745 328=head2 How do I put a password on my web pages?
329
49d635f9
RGS
330To enable authentication for your web server, you need to configure
331your web server. The configuration is different for different sorts
ac9dac7f 332of web servers--apache does it differently from iPlanet which does
49d635f9
RGS
333it differently from IIS. Check your web server documentation for
334the details for your particular server.
68dc0745 335
336=head2 How do I edit my .htpasswd and .htgroup files with Perl?
337
338The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
339consistent OO interface to these files, regardless of how they're
426affbf
LS
340stored. Databases may be text, dbm, Berkeley DB or any database with
341a DBI compatible driver. HTTPD::UserAdmin supports files used by the
b432a672 342"Basic" and "Digest" authentication schemes. Here's an example:
68dc0745 343
344 use HTTPD::UserAdmin ();
345 HTTPD::UserAdmin
346 ->new(DB => "/foo/.htpasswd")
347 ->add($username => $password);
348
46fc3d4c 349=head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
350
24f1ba9b 351See the security references listed in the CGI Meta FAQ
46fc3d4c 352
24f1ba9b 353 http://www.perl.org/CGI_MetaFAQ.html
46fc3d4c 354
5a964f20 355=head2 How do I parse a mail header?
68dc0745 356
357For a quick-and-dirty solution, try this solution derived
b73a15ae 358from L<perlfunc/split>:
68dc0745 359
360 $/ = '';
361 $header = <MSG>;
362 $header =~ s/\n\s+/ /g; # merge continuation lines
363 %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
364
365That solution doesn't do well if, for example, you're trying to
366maintain all the Received lines. A more complete approach is to use
367the Mail::Header module from CPAN (part of the MailTools package).
368
369=head2 How do I decode a CGI form?
370
7678cced
RGS
371(contributed by brian d foy)
372
373Use the CGI.pm module that comes with Perl. It's quick,
374it's easy, and it actually does quite a bit of work to
375ensure things happen correctly. It handles GET, POST, and
376HEAD requests, multipart forms, multivalued fields, query
377string and message body combinations, and many other things
378you probably don't want to think about.
379
380It doesn't get much easier: the CGI module automatically
381parses the input and makes each value available through the
382C<param()> function.
383
384 use CGI qw(:standard);
6670e5e7 385
9e72e4c6 386 my $total = param( 'price' ) + param( 'shipping' );
6670e5e7 387
9e72e4c6 388 my @items = param( 'item' ); # multiple values, same field name
6670e5e7 389
7678cced
RGS
390If you want an object-oriented approach, CGI.pm can do that too.
391
392 use CGI;
6670e5e7 393
7678cced 394 my $cgi = CGI->new();
6670e5e7 395
9e72e4c6 396 my $total = $cgi->param( 'price' ) + $cgi->param( 'shipping' );
6670e5e7 397
9e72e4c6 398 my @items = $cgi->param( 'item' );
7678cced
RGS
399
400You might also try CGI::Minimal which is a lightweight version
401of the same thing. Other CGI::* modules on CPAN might work better
402for you, too.
403
404Many people try to write their own decoder (or copy one from
405another program) and then run into one of the many "gotchas"
406of the task. It's much easier and less hassle to use CGI.pm.
68dc0745 407
5a964f20 408=head2 How do I check a valid mail address?
68dc0745 409
322be77c 410(partly contributed by Aaron Sherman)
68dc0745 411
322be77c 412This isn't as simple a question as it sounds. There are two parts:
c8db1d39 413
322be77c 414a) How do I verify that an email address is correctly formatted?
c8db1d39 415
322be77c 416b) How do I verify that an email address targets a valid recipient?
c8db1d39 417
322be77c
RGS
418Without sending mail to the address and seeing whether there's a human
419on the other end to answer you, you cannot fully answer part I<b>, but
420either the C<Email::Valid> or the C<RFC::RFC822::Address> module will do
421both part I<a> and part I<b> as far as you can in real-time.
422
423If you want to just check part I<a> to see that the address is valid
424according to the mail header standard with a simple regular expression,
425you can have problems, because there are deliverable addresses that
426aren't RFC-2822 (the latest mail header standard) compliant, and
427addresses that aren't deliverable which, are compliant. However, the
428following will match valid RFC-2822 addresses that do not have comments,
429folding whitespace, or any other obsolete or non-essential elements.
430This I<just> matches the address itself:
431
432 my $atom = qr{[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+};
433 my $dot_atom = qr{$atom(?:\.$atom)*};
434 my $quoted = qr{"(?:\\[^\r\n]|[^\\"])*"};
435 my $local = qr{(?:$dot_atom|$quoted)};
6f63574e
DK
436 my $quotedpair = qr{\\[\x00-\x09\x0B-\x0c\x0e-\x7e]};
437 my $domain_lit = qr{\[(?:$quotedpair|[\x21-\x5a\x5e-\x7e])*\]};
322be77c
RGS
438 my $domain = qr{(?:$dot_atom|$domain_lit)};
439 my $addr_spec = qr{$local\@$domain};
440
441Just match an address against C</^${addr_spec}$/> to see if it follows
442the RFC2822 specification. However, because it is impossible to be
443sure that such a correctly formed address is actually the correct way
444to reach a particular person or even has a mailbox associated with it,
445you must be very careful about how you use this.
c8db1d39 446
322be77c
RGS
447Our best advice for verifying a person's mail address is to have them
448enter their address twice, just as you normally do to change a
449password. This usually weeds out typos. If both versions match, send
450mail to that address with a personal message. If you get the message
451back and they've followed your directions, you can be reasonably
452assured that it's real.
68dc0745 453
c8db1d39
TC
454A related strategy that's less open to forgery is to give them a PIN
455(personal ID number). Record the address and PIN (best that it be a
322be77c 456random one) for later processing. In the mail you send, ask them to
c8db1d39 457include the PIN in their reply. But if it bounces, or the message is
b432a672 458included via a "vacation" script, it'll be there anyway. So it's
c8db1d39
TC
459best to ask them to mail back a slight alteration of the PIN, such as
460with the characters reversed, one added or subtracted to each digit, etc.
46fc3d4c 461
68dc0745 462=head2 How do I decode a MIME/BASE64 string?
463
6a0af2f1
GA
464The MIME-Base64 package (available from CPAN) handles this as well as
465the MIME/QP encoding. Decoding BASE64 becomes as simple as:
68dc0745 466
6a0af2f1 467 use MIME::Base64;
68dc0745 468 $decoded = decode_base64($encoded);
469
26d9b02f 470The MIME-Tools package (available from CPAN) supports extraction with
6a0af2f1
GA
471decoding of BASE64 encoded attachments and content directly from email
472messages.
473
474If the string to decode is short (less than 84 bytes long)
475a more direct approach is to use the unpack() function's "u"
68dc0745 476format after minor transliterations:
477
478 tr#A-Za-z0-9+/##cd; # remove non-base64 chars
479 tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
480 $len = pack("c", 32 + 0.75*length); # compute length byte
481 print unpack("u", $len . $_); # uudecode and print
482
5a964f20 483=head2 How do I return the user's mail address?
68dc0745 484
a6dd486b 485On systems that support getpwuid, the $< variable, and the
68dc0745 486Sys::Hostname module (which is part of the standard perl distribution),
487you can probably try using something like this:
488
489 use Sys::Hostname;
231ab6d1 490 $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
68dc0745 491
5a964f20
TC
492Company policies on mail address can mean that this generates addresses
493that the company's mail system will not accept, so you should ask for
494users' mail addresses when this matters. Furthermore, not all systems
68dc0745 495on which Perl runs are so forthcoming with this information as is Unix.
496
497The Mail::Util module from CPAN (part of the MailTools package) provides a
498mailaddress() function that tries to guess the mail address of the user.
499It makes a more intelligent guess than the code above, using information
500given when the module was installed, but it could still be incorrect.
501Again, the best way is often just to ask the user.
502
c8db1d39 503=head2 How do I send mail?
68dc0745 504
c8db1d39
TC
505Use the C<sendmail> program directly:
506
507 open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
508 or die "Can't fork for sendmail: $!\n";
509 print SENDMAIL <<"EOF";
510 From: User Originating Mail <me\@host>
511 To: Final Destination <you\@otherhost>
512 Subject: A relevant subject line
513
65acb1b1
TC
514 Body of the message goes here after the blank line
515 in as many lines as you like.
c8db1d39
TC
516 EOF
517 close(SENDMAIL) or warn "sendmail didn't close nicely";
518
519The B<-oi> option prevents sendmail from interpreting a line consisting
520of a single dot as "end of message". The B<-t> option says to use the
521headers to decide who to send the message to, and B<-odq> says to put
522the message into the queue. This last option means your message won't
523be immediately delivered, so leave it out if you want immediate
524delivery.
525
d92eb7b0
GS
526Alternate, less convenient approaches include calling mail (sometimes
527called mailx) directly or simply opening up port 25 have having an
528intimate conversation between just you and the remote SMTP daemon,
529probably sendmail.
530
531Or you might be able use the CPAN module Mail::Mailer:
c8db1d39
TC
532
533 use Mail::Mailer;
534
535 $mailer = Mail::Mailer->new();
536 $mailer->open({ From => $from_address,
537 To => $to_address,
538 Subject => $subject,
539 })
540 or die "Can't open: $!\n";
541 print $mailer $body;
542 $mailer->close();
543
544The Mail::Internet module uses Net::SMTP which is less Unix-centric than
545Mail::Mailer, but less reliable. Avoid raw SMTP commands. There
d92eb7b0 546are many reasons to use a mail transport agent like sendmail. These
8305e449 547include queuing, MX records, and security.
c8db1d39 548
575cc754
JH
549=head2 How do I use MIME to make an attachment to a mail message?
550
551This answer is extracted directly from the MIME::Lite documentation.
552Create a multipart message (i.e., one with attachments).
553
554 use MIME::Lite;
555
556 ### Create a new multipart message:
557 $msg = MIME::Lite->new(
558 From =>'me@myhost.com',
559 To =>'you@yourhost.com',
560 Cc =>'some@other.com, some@more.com',
561 Subject =>'A message with 2 parts...',
562 Type =>'multipart/mixed'
563 );
564
565 ### Add parts (each "attach" has same arguments as "new"):
566 $msg->attach(Type =>'TEXT',
567 Data =>"Here's the GIF file you wanted"
568 );
569 $msg->attach(Type =>'image/gif',
570 Path =>'aaa000123.gif',
571 Filename =>'logo.gif'
572 );
573
574 $text = $msg->as_string;
575
576MIME::Lite also includes a method for sending these things.
577
578 $msg->send;
579
197aec24 580This defaults to using L<sendmail> but can be customized to use
575cc754
JH
581SMTP via L<Net::SMTP>.
582
c8db1d39
TC
583=head2 How do I read mail?
584
d92eb7b0 585While you could use the Mail::Folder module from CPAN (part of the
5cd0b561 586MailFolder package) or the Mail::Internet module from CPAN (part
a6dd486b 587of the MailTools package), often a module is overkill. Here's a
d92eb7b0
GS
588mail sorter.
589
590 #!/usr/bin/perl
5cd0b561 591
c8db1d39
TC
592 my(@msgs, @sub);
593 my $msgno = -1;
594 $/ = ''; # paragraph reads
595 while (<>) {
5cd0b561 596 if (/^From /m) {
c8db1d39
TC
597 /^Subject:\s*(?:Re:\s*)*(.*)/mi;
598 $sub[++$msgno] = lc($1) || '';
599 }
600 $msgs[$msgno] .= $_;
d92eb7b0 601 }
c8db1d39
TC
602 for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
603 print $msgs[$i];
604 }
605
d92eb7b0 606Or more succinctly,
c8db1d39
TC
607
608 #!/usr/bin/perl -n00
609 # bysub2 - awkish sort-by-subject
610 BEGIN { $msgno = -1 }
611 $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
612 $msg[$msgno] .= $_;
613 END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
614
a05e4845
RGS
615=head2 How do I find out my hostname, domainname, or IP address?
616X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa,
617gethostbyname, Socket, Net::Domain, Sys::Hostname>
68dc0745 618
a05e4845 619(contributed by brian d foy)
68dc0745 620
a05e4845
RGS
621The Net::Domain module, which is part of the standard distribution starting
622in perl5.7.3, can get you the fully qualified domain name (FQDN), the host
623name, or the domain name.
68dc0745 624
a05e4845 625 use Net::Domain qw(hostname hostfqdn hostdomain);
58103a2e 626
a05e4845
RGS
627 my $host = hostfqdn();
628
629The C<Sys::Hostname> module, included in the standard distribution since
630perl5.6, can also get the hostname.
68dc0745 631
a05e4845 632 use Sys::Hostname;
58103a2e 633
a05e4845 634 $host = hostname();
68dc0745 635
a05e4845
RGS
636To get the IP address, you can use the C<gethostbyname> built-in function
637to turn the name into a number. To turn that number into the dotted octet
638form (a.b.c.d) that most people expect, use the C<inet_ntoa> function
639from the <Socket> module, which also comes with perl.
640
641 use Socket;
58103a2e
RGS
642
643 my $address = inet_ntoa(
a05e4845
RGS
644 scalar gethostbyname( $host || 'localhost' )
645 );
68dc0745 646
647=head2 How do I fetch a news article or the active newsgroups?
648
649Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
a6dd486b 650This can make tasks like fetching the newsgroup list as simple as
68dc0745 651
652 perl -MNews::NNTPClient
653 -e 'print News::NNTPClient->new->list("newsgroups")'
654
655=head2 How do I fetch/put an FTP file?
656
657LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also
658available from CPAN) is more complex but can put as well as fetch.
659
660=head2 How can I do RPC in Perl?
661
b68463f7
RGS
662(Contributed by brian d foy)
663
664Use one of the RPC modules you can find on CPAN (
665http://search.cpan.org/search?query=RPC&mode=all ).
68dc0745 666
500071f4
RGS
667=head1 REVISION
668
ee891a00 669Revision: $Revision: 8539 $
500071f4 670
f449fe8a 671Date: $Date: 2007-01-11 00:07:14 +0100 (Thu, 11 Jan 2007) $
500071f4
RGS
672
673See L<perlfaq> for source control details and availability.
674
68dc0745 675=head1 AUTHOR AND COPYRIGHT
676
ee891a00 677Copyright (c) 1997-2007 Tom Christiansen, Nathan Torkington, and
7678cced 678other authors as noted. All rights reserved.
5a964f20 679
5a7beb56
JH
680This documentation is free; you can redistribute it and/or modify it
681under the same terms as Perl itself.
5a964f20
TC
682
683Irrespective of its distribution, all code examples in this file
684are hereby placed into the public domain. You are permitted and
685encouraged to use this code in your own programs for fun
686or for profit as you see fit. A simple comment in the code giving
687credit would be courteous but is not required.