Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/1perl/perlfaq9

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLFAQ9 1"
.TH PERLFAQ9 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlfaq9 \- Networking ($Revision: 1.9 $, $Date: 2002/04/07 18:46:13 $)
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
This section deals with questions related to networking, the internet,
and a few on the web.
.Sh "What is the correct form of response from a \s-1CGI\s0 script?"
.IX Subsection "What is the correct form of response from a CGI script?"
(Alan Flavell <[email protected]> answers...)
.PP
The Common Gateway Interface (\s-1CGI\s0) specifies a software interface between 
a program (\*(L"\s-1CGI\s0 script\*(R") and a web server (\s-1HTTPD\s0). It is not specific 
to Perl, and has its own FAQs and tutorials, and usenet group, 
comp.infosystems.www.authoring.cgi 
.PP
The original \s-1CGI\s0 specification is at: http://hoohoo.ncsa.uiuc.edu/cgi/
.PP
Current best-practice \s-1RFC\s0 draft at: http://CGI\-Spec.Golux.Com/
.PP
Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html
.PP
These Perl FAQs very selectively cover some \s-1CGI\s0 issues. However, Perl 
programmers are strongly advised to use the \s-1CGI\s0.pm module, to take care
of the details for them. 
.PP
The similarity between \s-1CGI\s0 response headers (defined in the \s-1CGI\s0
specification) and \s-1HTTP\s0 response headers (defined in the \s-1HTTP\s0
specification, \s-1RFC2616\s0) is intentional, but can sometimes be confusing.
.PP
The \s-1CGI\s0 specification defines two kinds of script: the \*(L"Parsed Header\*(R"
script, and the \*(L"Non Parsed Header\*(R" (\s-1NPH\s0) script. Check your server
documentation to see what it supports. \*(L"Parsed Header\*(R" scripts are
simpler in various respects. The \s-1CGI\s0 specification allows any of the
usual newline representations in the \s-1CGI\s0 response (it's the server's
job to create an accurate \s-1HTTP\s0 response based on it). So \*(L"\en\*(R" written in
text mode is technically correct, and recommended. \s-1NPH\s0 scripts are more
tricky: they must put out a complete and accurate set of \s-1HTTP\s0
transaction response headers; the \s-1HTTP\s0 specification calls for records
to be terminated with carriage-return and line\-feed, i.e \s-1ASCII\s0 \e015\e012
written in binary mode.
.PP
Using \s-1CGI\s0.pm gives excellent platform independence, including \s-1EBCDIC\s0
systems. \s-1CGI\s0.pm selects an appropriate newline representation
($CGI::CRLF) and sets binmode as appropriate.
.Sh "My \s-1CGI\s0 script runs from the command line but not the browser.  (500 Server Error)"
.IX Subsection "My CGI script runs from the command line but not the browser.  (500 Server Error)"
Several things could be wrong.  You can go through the \*(L"Troubleshooting
Perl \s-1CGI\s0 scripts\*(R" guide at
.PP
.Vb 1
\&        http://www.perl.org/troubleshooting_CGI.html
.Ve
.PP
If, after that, you can demonstrate that you've read the FAQs and that 
your problem isn't something simple that can be easily answered, you'll
probably receive a courteous and useful reply to your question if you
post it on comp.infosystems.www.authoring.cgi (if it's something to do
with \s-1HTTP\s0 or the \s-1CGI\s0 protocols).  Questions that appear to be Perl
questions but are really \s-1CGI\s0 ones that are posted to comp.lang.perl.misc
are not so well received.
.PP
The useful FAQs, related documents, and troubleshooting guides are 
listed in the \s-1CGI\s0 Meta \s-1FAQ:\s0
.PP
.Vb 1
\&        http://www.perl.org/CGI_MetaFAQ.html
.Ve
.Sh "How can I get better error messages from a \s-1CGI\s0 program?"
.IX Subsection "How can I get better error messages from a CGI program?"
Use the CGI::Carp module.  It replaces \f(CW\*(C`warn\*(C'\fR and \f(CW\*(C`die\*(C'\fR, plus the
normal Carp modules \f(CW\*(C`carp\*(C'\fR, \f(CW\*(C`croak\*(C'\fR, and \f(CW\*(C`confess\*(C'\fR functions with
more verbose and safer versions.  It still sends them to the normal
server error log.
.PP
.Vb 3
\&    use CGI::Carp;
\&    warn "This is a complaint";
\&    die "But this one is serious";
.Ve
.PP
The following use of CGI::Carp also redirects errors to a file of your choice,
placed in a \s-1BEGIN\s0 block to catch compile-time warnings as well:
.PP
.Vb 6
\&    BEGIN {
\&        use CGI::Carp qw(carpout);
\&        open(LOG, ">>/var/local/cgi-logs/mycgi-log")
\&            or die "Unable to append to mycgi-log: $!\en";
\&        carpout(*LOG);
\&    }
.Ve
.PP
You can even arrange for fatal errors to go back to the client browser,
which is nice for your own debugging, but might confuse the end user.
.PP
.Vb 2
\&    use CGI::Carp qw(fatalsToBrowser);
\&    die "Bad error here";
.Ve
.PP
Even if the error happens before you get the \s-1HTTP\s0 header out, the module
will try to take care of this to avoid the dreaded server 500 errors.
Normal warnings still go out to the server error log (or wherever
you've sent them with \f(CW\*(C`carpout\*(C'\fR) with the application name and date
stamp prepended.
.Sh "How do I remove \s-1HTML\s0 from a string?"
.IX Subsection "How do I remove HTML from a string?"
The most correct way (albeit not the fastest) is to use HTML::Parser
from \s-1CPAN\s0.  Another mostly correct
way is to use HTML::FormatText which not only removes \s-1HTML\s0 but also
attempts to do a little simple formatting of the resulting plain text.
.PP
Many folks attempt a simple-minded regular expression approach, like
\&\f(CW\*(C`s/<.*?>//g\*(C'\fR, but that fails in many cases because the tags
may continue over line breaks, they may contain quoted angle\-brackets,
or \s-1HTML\s0 comment may be present.  Plus, folks forget to convert
entities\*(--like \f(CW\*(C`&lt;\*(C'\fR for example.
.PP
Here's one \*(L"simple\-minded\*(R" approach, that works for most files:
.PP
.Vb 2
\&    #!/usr/bin/perl -p0777
\&    s/<(?:[^>'"]*|(['"]).*?\e1)*>//gs
.Ve
.PP
If you want a more complete solution, see the 3\-stage striphtml
program in
http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz
\&.
.PP
Here are some tricky cases that you should think about when picking
a solution:
.PP
.Vb 1
\&    <IMG SRC = "foo.gif" ALT = "A > B">
.Ve
.PP
.Vb 2
\&    <IMG SRC = "foo.gif"
\&         ALT = "A > B">
.Ve
.PP
.Vb 1
\&    <!-- <A comment> -->
.Ve
.PP
.Vb 1
\&    <script>if (a<b && a>c)</script>
.Ve
.PP
.Vb 1
\&    <# Just data #>
.Ve
.PP
.Vb 1
\&    <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
.Ve
.PP
If \s-1HTML\s0 comments include other tags, those solutions would also break
on text like this:
.PP
.Vb 3
\&    <!-- This section commented out.
\&        <B>You can't see me!</B>
\&    -->
.Ve
.Sh "How do I extract URLs?"
.IX Subsection "How do I extract URLs?"
You can easily extract all sorts of URLs from \s-1HTML\s0 with
\&\f(CW\*(C`HTML::SimpleLinkExtor\*(C'\fR which handles anchors, images, objects,
frames, and many other tags that can contain a \s-1URL\s0.  If you need 
anything more complex, you can create your own subclass of 
\&\f(CW\*(C`HTML::LinkExtor\*(C'\fR or \f(CW\*(C`HTML::Parser\*(C'\fR.  You might even use 
\&\f(CW\*(C`HTML::SimpleLinkExtor\*(C'\fR as an example for something specifically
suited to your needs.
.PP
Less complete solutions involving regular expressions can save 
you a lot of processing time if you know that the input is simple.  One
solution from Tom Christiansen runs 100 times faster than most
module based approaches but only extracts URLs from anchors where the first
attribute is \s-1HREF\s0 and there are no other attributes. 
.PP
.Vb 7
\&        #!/usr/bin/perl -n00
\&        # qxurl - [email protected]
\&        print "$2\en" while m{
\&            < \es*
\&              A \es+ HREF \es* = \es* (["']) (.*?) \e1
\&            \es* >
\&        }gsix;
.Ve
.Sh "How do I download a file from the user's machine?  How do I open a file on another machine?"
.IX Subsection "How do I download a file from the user's machine?  How do I open a file on another machine?"
In the context of an \s-1HTML\s0 form, you can use what's known as
\&\fBmultipart/form\-data\fR encoding.  The \s-1CGI\s0.pm module (available from
\&\s-1CPAN\s0) supports this in the \fIstart_multipart_form()\fR method, which isn't
the same as the \fIstartform()\fR method.
.Sh "How do I make a pop-up menu in \s-1HTML\s0?"
.IX Subsection "How do I make a pop-up menu in HTML?"
Use the \fB<\s-1SELECT\s0>\fR and \fB<\s-1OPTION\s0>\fR tags.  The \s-1CGI\s0.pm
module (available from \s-1CPAN\s0) supports this widget, as well as many
others, including some that it cleverly synthesizes on its own.
.Sh "How do I fetch an \s-1HTML\s0 file?"
.IX Subsection "How do I fetch an HTML file?"
One approach, if you have the lynx text-based \s-1HTML\s0 browser installed
on your system, is this:
.PP
.Vb 2
\&    $html_code = `lynx -source $url`;
\&    $text_data = `lynx -dump $url`;
.Ve
.PP
The libwww-perl (\s-1LWP\s0) modules from \s-1CPAN\s0 provide a more powerful way
to do this.  They don't require lynx, but like lynx, can still work
through proxies:
.PP
.Vb 3
\&    # simplest version
\&    use LWP::Simple;
\&    $content = get($URL);
.Ve
.PP
.Vb 3
\&    # or print HTML from a URL
\&    use LWP::Simple;
\&    getprint "http://www.linpro.no/lwp/";
.Ve
.PP
.Vb 11
\&    # or print ASCII from HTML from a URL
\&    # also need HTML-Tree package from CPAN
\&    use LWP::Simple;
\&    use HTML::Parser;
\&    use HTML::FormatText;
\&    my ($html, $ascii);
\&    $html = get("http://www.perl.com/");
\&    defined $html
\&        or die "Can't fetch HTML from http://www.perl.com/";
\&    $ascii = HTML::FormatText->new->format(parse_html($html));
\&    print $ascii;
.Ve
.Sh "How do I automate an \s-1HTML\s0 form submission?"
.IX Subsection "How do I automate an HTML form submission?"
If you're submitting values using the \s-1GET\s0 method, create a \s-1URL\s0 and encode
the form using the \f(CW\*(C`query_form\*(C'\fR method:
.PP
.Vb 2
\&    use LWP::Simple;
\&    use URI::URL;
.Ve
.PP
.Vb 3
\&    my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
\&    $url->query_form(module => 'DB_File', readme => 1);
\&    $content = get($url);
.Ve
.PP
If you're using the \s-1POST\s0 method, create your own user agent and encode
the content appropriately.
.PP
.Vb 2
\&    use HTTP::Request::Common qw(POST);
\&    use LWP::UserAgent;
.Ve
.PP
.Vb 4
\&    $ua = LWP::UserAgent->new();
\&    my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
\&                   [ module => 'DB_File', readme => 1 ];
\&    $content = $ua->request($req)->as_string;
.Ve
.Sh "How do I decode or create those %\-encodings on the web?"
.IX Subsection "How do I decode or create those %-encodings on the web?"
If you are writing a \s-1CGI\s0 script, you should be using the \s-1CGI\s0.pm module
that comes with perl, or some other equivalent module.  The \s-1CGI\s0 module
automatically decodes queries for you, and provides an \fIescape()\fR
function to handle encoding.
.PP
The best source of detailed information on \s-1URI\s0 encoding is \s-1RFC\s0 2396.
Basically, the following substitutions do it:
.PP
.Vb 1
\&    s/([^\ew()'*~!.-])/sprintf '%%%02x', ord $1/eg;   # encode
.Ve
.PP
.Vb 1
\&    s/%([A-Fa-f\ed]{2})/chr hex $1/eg;            # decode
.Ve
.PP
However, you should only apply them to individual \s-1URI\s0 components, not
the entire \s-1URI\s0, otherwise you'll lose information and generally mess
things up.  If that didn't explain it, don't worry.  Just go read
section 2 of the \s-1RFC\s0, it's probably the best explanation there is.
.PP
\&\s-1RFC\s0 2396 also contains a lot of other useful information, including a
regexp for breaking any arbitrary \s-1URI\s0 into components (Appendix B).
.Sh "How do I redirect to another page?"
.IX Subsection "How do I redirect to another page?"
Specify the complete \s-1URL\s0 of the destination (even if it is on the same
server). This is one of the two different kinds of \s-1CGI\s0 \*(L"Location:\*(R"
responses which are defined in the \s-1CGI\s0 specification for a Parsed Headers
script. The other kind (an absolute URLpath) is resolved internally to
the server without any \s-1HTTP\s0 redirection. The \s-1CGI\s0 specifications do not
allow relative URLs in either case.
.PP
Use of \s-1CGI\s0.pm is strongly recommended.  This example shows redirection
with a complete \s-1URL\s0. This redirection is handled by the web browser.
.PP
.Vb 1
\&      use CGI qw/:standard/;
.Ve
.PP
.Vb 2
\&      my $url = 'http://www.cpan.org/';
\&      print redirect($url);
.Ve
.PP
This example shows a redirection with an absolute URLpath.  This
redirection is handled by the local web server.
.PP
.Vb 2
\&      my $url = '/CPAN/index.html';
\&      print redirect($url);
.Ve
.PP
But if coded directly, it could be as follows (the final \*(L"\en\*(R" is 
shown separately, for clarity), using either a complete \s-1URL\s0 or
an absolute URLpath. 
.PP
.Vb 2
\&      print "Location: $url\en";   # CGI response header
\&      print "\en";                 # end of headers
.Ve
.Sh "How do I put a password on my web pages?"
.IX Subsection "How do I put a password on my web pages?"
That depends.  You'll need to read the documentation for your web
server, or perhaps check some of the other FAQs referenced above.
.Sh "How do I edit my .htpasswd and .htgroup files with Perl?"
.IX Subsection "How do I edit my .htpasswd and .htgroup files with Perl?"
The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
consistent \s-1OO\s0 interface to these files, regardless of how they're
stored.  Databases may be text, dbm, Berkeley \s-1DB\s0 or any database with
a \s-1DBI\s0 compatible driver.  HTTPD::UserAdmin supports files used by the
`Basic' and `Digest' authentication schemes.  Here's an example:
.PP
.Vb 4
\&    use HTTPD::UserAdmin ();
\&    HTTPD::UserAdmin
\&          ->new(DB => "/foo/.htpasswd")
\&          ->add($username => $password);
.Ve
.Sh "How do I make sure users can't enter values into a form that cause my \s-1CGI\s0 script to do bad things?"
.IX Subsection "How do I make sure users can't enter values into a form that cause my CGI script to do bad things?"
See the security references listed in the \s-1CGI\s0 Meta \s-1FAQ\s0
.PP
.Vb 1
\&        http://www.perl.org/CGI_MetaFAQ.html
.Ve
.Sh "How do I parse a mail header?"
.IX Subsection "How do I parse a mail header?"
For a quick-and-dirty solution, try this solution derived
from \*(L"split\*(R" in perlfunc:
.PP
.Vb 4
\&    $/ = '';
\&    $header = <MSG>;
\&    $header =~ s/\en\es+/ /g;      # merge continuation lines
\&    %head = ( UNIX_FROM_LINE, split /^([-\ew]+):\es*/m, $header );
.Ve
.PP
That solution doesn't do well if, for example, you're trying to
maintain all the Received lines.  A more complete approach is to use
the Mail::Header module from \s-1CPAN\s0 (part of the MailTools package).
.Sh "How do I decode a \s-1CGI\s0 form?"
.IX Subsection "How do I decode a CGI form?"
You use a standard module, probably \s-1CGI\s0.pm.  Under no circumstances
should you attempt to do so by hand!
.PP
You'll see a lot of \s-1CGI\s0 programs that blindly read from \s-1STDIN\s0 the number
of bytes equal to \s-1CONTENT_LENGTH\s0 for POSTs, or grab \s-1QUERY_STRING\s0 for
decoding GETs.  These programs are very poorly written.  They only work
sometimes.  They typically forget to check the return value of the \fIread()\fR
system call, which is a cardinal sin.  They don't handle \s-1HEAD\s0 requests.
They don't handle multipart forms used for file uploads.  They don't deal
with \s-1GET/POST\s0 combinations where query fields are in more than one place.
They don't deal with keywords in the query string.
.PP
In short, they're bad hacks.  Resist them at all costs.  Please do not be
tempted to reinvent the wheel.  Instead, use the \s-1CGI\s0.pm or CGI_Lite.pm
(available from \s-1CPAN\s0), or if you're trapped in the module-free land
of perl1 .. perl4, you might look into cgi\-lib.pl (available from
http://cgi\-lib.stanford.edu/cgi\-lib/ ).
.PP
Make sure you know whether to use a \s-1GET\s0 or a \s-1POST\s0 in your form.
GETs should only be used for something that doesn't update the server.
Otherwise you can get mangled databases and repeated feedback mail
messages.  The fancy word for this is ``idempotency''.  This simply
means that there should be no difference between making a \s-1GET\s0 request
for a particular \s-1URL\s0 once or multiple times.  This is because the
\&\s-1HTTP\s0 protocol definition says that a \s-1GET\s0 request may be cached by the
browser, or server, or an intervening proxy.  \s-1POST\s0 requests cannot be
cached, because each request is independent and matters.  Typically,
\&\s-1POST\s0 requests change or depend on state on the server (query or update
a database, send mail, or purchase a computer).
.Sh "How do I check a valid mail address?"
.IX Subsection "How do I check a valid mail address?"
You can't, at least, not in real time.  Bummer, eh?
.PP
Without sending mail to the address and seeing whether there's a human
on the other hand to answer you, you cannot determine whether a mail
address is valid.  Even if you apply the mail header standard, you
can have problems, because there are deliverable addresses that aren't
\&\s-1RFC\-822\s0 (the mail header standard) compliant, and addresses that aren't
deliverable which are compliant.
.PP
Many are tempted to try to eliminate many frequently-invalid
mail addresses with a simple regex, such as
\&\f(CW\*(C`/^[\ew.\-]+\e@(?:[\ew\-]+\e.)+\ew+$/\*(C'\fR.  It's a very bad idea.  However,
this also throws out many valid ones, and says nothing about
potential deliverability, so it is not suggested.  Instead, see
http://www.cpan.org/authors/Tom_Christiansen/scripts/ckaddr.gz ,
which actually checks against the full \s-1RFC\s0 spec (except for nested
comments), looks for addresses you may not wish to accept mail to
(say, Bill Clinton or your postmaster), and then makes sure that the
hostname given can be looked up in the \s-1DNS\s0 \s-1MX\s0 records.  It's not fast,
but it works for what it tries to do.
.PP
Our best advice for verifying a person's mail address is to have them
enter their address twice, just as you normally do to change a password.
This usually weeds out typos.  If both versions match, send
mail to that address with a personal message that looks somewhat like:
.PP
.Vb 1
\&    Dear [email protected],
.Ve
.PP
.Vb 5
\&    Please confirm the mail address you gave us Wed May  6 09:38:41
\&    MDT 1998 by replying to this message.  Include the string
\&    "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
\&    start with "Nik...".  Once this is done, your confirmed address will
\&    be entered into our records.
.Ve
.PP
If you get the message back and they've followed your directions,
you can be reasonably assured that it's real.
.PP
A related strategy that's less open to forgery is to give them a \s-1PIN\s0
(personal \s-1ID\s0 number).  Record the address and \s-1PIN\s0 (best that it be a
random one) for later processing.  In the mail you send, ask them to
include the \s-1PIN\s0 in their reply.  But if it bounces, or the message is
included via a ``vacation'' script, it'll be there anyway.  So it's
best to ask them to mail back a slight alteration of the \s-1PIN\s0, such as
with the characters reversed, one added or subtracted to each digit, etc.
.Sh "How do I decode a \s-1MIME/BASE64\s0 string?"
.IX Subsection "How do I decode a MIME/BASE64 string?"
The MIME\-Base64 package (available from \s-1CPAN\s0) handles this as well as
the \s-1MIME/QP\s0 encoding.  Decoding \s-1BASE64\s0 becomes as simple as:
.PP
.Vb 2
\&    use MIME::Base64;
\&    $decoded = decode_base64($encoded);
.Ve
.PP
The MIME-Tools package (available from \s-1CPAN\s0) supports extraction with
decoding of \s-1BASE64\s0 encoded attachments and content directly from email
messages.
.PP
If the string to decode is short (less than 84 bytes long)
a more direct approach is to use the \fIunpack()\fR function's \*(L"u\*(R"
format after minor transliterations:
.PP
.Vb 4
\&    tr#A-Za-z0-9+/##cd;                   # remove non-base64 chars
\&    tr#A-Za-z0-9+/# -_#;                  # convert to uuencoded format
\&    $len = pack("c", 32 + 0.75*length);   # compute length byte
\&    print unpack("u", $len . $_);         # uudecode and print
.Ve
.Sh "How do I return the user's mail address?"
.IX Subsection "How do I return the user's mail address?"
On systems that support getpwuid, the $< variable, and the
Sys::Hostname module (which is part of the standard perl distribution),
you can probably try using something like this:
.PP
.Vb 2
\&    use Sys::Hostname;
\&    $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
.Ve
.PP
Company policies on mail address can mean that this generates addresses
that the company's mail system will not accept, so you should ask for
users' mail addresses when this matters.  Furthermore, not all systems
on which Perl runs are so forthcoming with this information as is Unix.
.PP
The Mail::Util module from \s-1CPAN\s0 (part of the MailTools package) provides a
\&\fImailaddress()\fR function that tries to guess the mail address of the user.
It makes a more intelligent guess than the code above, using information
given when the module was installed, but it could still be incorrect.
Again, the best way is often just to ask the user.
.Sh "How do I send mail?"
.IX Subsection "How do I send mail?"
Use the \f(CW\*(C`sendmail\*(C'\fR program directly:
.PP
.Vb 6
\&    open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
\&                        or die "Can't fork for sendmail: $!\en";
\&    print SENDMAIL <<"EOF";
\&    From: User Originating Mail <me\e@host>
\&    To: Final Destination <you\e@otherhost>
\&    Subject: A relevant subject line
.Ve
.PP
.Vb 4
\&    Body of the message goes here after the blank line
\&    in as many lines as you like.
\&    EOF
\&    close(SENDMAIL)     or warn "sendmail didn't close nicely";
.Ve
.PP
The \fB\-oi\fR option prevents sendmail from interpreting a line consisting
of a single dot as \*(L"end of message\*(R".  The \fB\-t\fR option says to use the
headers to decide who to send the message to, and \fB\-odq\fR says to put
the message into the queue.  This last option means your message won't
be immediately delivered, so leave it out if you want immediate
delivery.
.PP
Alternate, less convenient approaches include calling mail (sometimes
called mailx) directly or simply opening up port 25 have having an
intimate conversation between just you and the remote \s-1SMTP\s0 daemon,
probably sendmail.
.PP
Or you might be able use the \s-1CPAN\s0 module Mail::Mailer:
.PP
.Vb 1
\&    use Mail::Mailer;
.Ve
.PP
.Vb 8
\&    $mailer = Mail::Mailer->new();
\&    $mailer->open({ From    => $from_address,
\&                    To      => $to_address,
\&                    Subject => $subject,
\&                  })
\&        or die "Can't open: $!\en";
\&    print $mailer $body;
\&    $mailer->close();
.Ve
.PP
The Mail::Internet module uses Net::SMTP which is less Unix-centric than
Mail::Mailer, but less reliable.  Avoid raw \s-1SMTP\s0 commands.  There
are many reasons to use a mail transport agent like sendmail.  These
include queuing, \s-1MX\s0 records, and security.
.Sh "How do I use \s-1MIME\s0 to make an attachment to a mail message?"
.IX Subsection "How do I use MIME to make an attachment to a mail message?"
This answer is extracted directly from the MIME::Lite documentation.
Create a multipart message (i.e., one with attachments).
.PP
.Vb 1
\&    use MIME::Lite;
.Ve
.PP
.Vb 8
\&    ### Create a new multipart message:
\&    $msg = MIME::Lite->new(
\&                 From    =>'[email protected]',
\&                 To      =>'[email protected]',
\&                 Cc      =>'[email protected], [email protected]',
\&                 Subject =>'A message with 2 parts...',
\&                 Type    =>'multipart/mixed'
\&                 );
.Ve
.PP
.Vb 8
\&    ### Add parts (each "attach" has same arguments as "new"):
\&    $msg->attach(Type     =>'TEXT',
\&                 Data     =>"Here's the GIF file you wanted"
\&                 );
\&    $msg->attach(Type     =>'image/gif',
\&                 Path     =>'aaa000123.gif',
\&                 Filename =>'logo.gif'
\&                 );
.Ve
.PP
.Vb 1
\&    $text = $msg->as_string;
.Ve
.PP
MIME::Lite also includes a method for sending these things.
.PP
.Vb 1
\&    $msg->send;
.Ve
.PP
This defaults to using \fIsendmail\fR\|(1) but can be customized to use
\&\s-1SMTP\s0 via Net::SMTP.
.Sh "How do I read mail?"
.IX Subsection "How do I read mail?"
While you could use the Mail::Folder module from \s-1CPAN\s0 (part of the
MailFolder package) or the Mail::Internet module from \s-1CPAN\s0 (also part
of the MailTools package), often a module is overkill.  Here's a
mail sorter.
.PP
.Vb 15
\&    #!/usr/bin/perl
\&    # bysub1 - simple sort by subject
\&    my(@msgs, @sub);
\&    my $msgno = -1;
\&    $/ = '';                    # paragraph reads
\&    while (<>) {
\&        if (/^From/m) {
\&            /^Subject:\es*(?:Re:\es*)*(.*)/mi;
\&            $sub[++$msgno] = lc($1) || '';
\&        }
\&        $msgs[$msgno] .= $_;
\&    }
\&    for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
\&        print $msgs[$i];
\&    }
.Ve
.PP
Or more succinctly,
.PP
.Vb 6
\&    #!/usr/bin/perl -n00
\&    # bysub2 - awkish sort-by-subject
\&    BEGIN { $msgno = -1 }
\&    $sub[++$msgno] = (/^Subject:\es*(?:Re:\es*)*(.*)/mi)[0] if /^From/m;
\&    $msg[$msgno] .= $_;
\&    END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
.Ve
.Sh "How do I find out my hostname/domainname/IP address?"
.IX Subsection "How do I find out my hostname/domainname/IP address?"
The normal way to find your own hostname is to call the \f(CW`hostname`\fR
program.  While sometimes expedient, this has some problems, such as
not knowing whether you've got the canonical name or not.  It's one of
those tradeoffs of convenience versus portability.
.PP
The Sys::Hostname module (part of the standard perl distribution) will
give you the hostname after which you can find out the \s-1IP\s0 address
(assuming you have working \s-1DNS\s0) with a \fIgethostbyname()\fR call.
.PP
.Vb 4
\&    use Socket;
\&    use Sys::Hostname;
\&    my $host = hostname();
\&    my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));
.Ve
.PP
Probably the simplest way to learn your \s-1DNS\s0 domain name is to grok
it out of /etc/resolv.conf, at least under Unix.  Of course, this
assumes several things about your resolv.conf configuration, including
that it exists.
.PP
(We still need a good \s-1DNS\s0 domain name-learning method for non-Unix
systems.)
.Sh "How do I fetch a news article or the active newsgroups?"
.IX Subsection "How do I fetch a news article or the active newsgroups?"
Use the Net::NNTP or News::NNTPClient modules, both available from \s-1CPAN\s0.
This can make tasks like fetching the newsgroup list as simple as
.PP
.Vb 2
\&    perl -MNews::NNTPClient
\&      -e 'print News::NNTPClient->new->list("newsgroups")'
.Ve
.Sh "How do I fetch/put an \s-1FTP\s0 file?"
.IX Subsection "How do I fetch/put an FTP file?"
LWP::Simple (available from \s-1CPAN\s0) can fetch but not put.  Net::FTP (also
available from \s-1CPAN\s0) is more complex but can put as well as fetch.
.Sh "How can I do \s-1RPC\s0 in Perl?"
.IX Subsection "How can I do RPC in Perl?"
A \s-1DCE::RPC\s0 module is being developed (but is not yet available) and
will be released as part of the DCE-Perl package (available from
\&\s-1CPAN\s0).  The rpcgen suite, available from CPAN/authors/id/JAKE/, is
an \s-1RPC\s0 stub generator and includes an \s-1RPC::ONC\s0 module.
.SH "AUTHOR AND COPYRIGHT"
.IX Header "AUTHOR AND COPYRIGHT"
Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington.
All rights reserved.
.PP
This documentation is free; you can redistribute it and/or modify it
under the same terms as Perl itself.
.PP
Irrespective of its distribution, all code examples in this file
are hereby placed into the public domain.  You are permitted and
encouraged to use this code in your own programs for fun
or for profit as you see fit.  A simple comment in the code giving
credit would be courteous but is not required.

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].