perlfaq9.pod
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 687 行 · 第 1/2 页
POD
687 行
HTTPD::UserAdmin ->new(DB => "/foo/.htpasswd") ->add($username => $password);=head2 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 CGI Meta FAQ http://www.perl.org/CGI_MetaFAQ.html=head2 How do I parse a mail header?For a quick-and-dirty solution, try this solution derivedfrom L<perlfunc/split>: $/ = ''; $header = <MSG>; $header =~ s/\n\s+/ /g; # merge continuation lines %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );That solution doesn't do well if, for example, you're trying tomaintain all the Received lines. A more complete approach is to usethe Mail::Header module from CPAN (part of the MailTools package).=head2 How do I decode a CGI form?(contributed by brian d foy)Use the CGI.pm module that comes with Perl. It's quick,it's easy, and it actually does quite a bit of work toensure things happen correctly. It handles GET, POST, andHEAD requests, multipart forms, multivalued fields, querystring and message body combinations, and many other thingsyou probably don't want to think about.It doesn't get much easier: the CGI module automaticallyparses the input and makes each value available through theC<param()> function. use CGI qw(:standard); my $total = param( 'price' ) + param( 'shipping' ); my @items = param( 'item' ); # multiple values, same field nameIf you want an object-oriented approach, CGI.pm can do that too. use CGI; my $cgi = CGI->new(); my $total = $cgi->param( 'price' ) + $cgi->param( 'shipping' ); my @items = $cgi->param( 'item' );You might also try CGI::Minimal which is a lightweight versionof the same thing. Other CGI::* modules on CPAN might work betterfor you, too.Many people try to write their own decoder (or copy one fromanother program) and then run into one of the many "gotchas"of the task. It's much easier and less hassle to use CGI.pm.=head2 How do I check a valid mail address?(partly contributed by Aaron Sherman)This isn't as simple a question as it sounds. There are two parts:a) How do I verify that an email address is correctly formatted?b) How do I verify that an email address targets a valid recipient?Without sending mail to the address and seeing whether there's a humanon the other end to answer you, you cannot fully answer part I<b>, buteither the C<Email::Valid> or the C<RFC::RFC822::Address> module will doboth part I<a> and part I<b> as far as you can in real-time.If you want to just check part I<a> to see that the address is validaccording to the mail header standard with a simple regular expression,you can have problems, because there are deliverable addresses thataren't RFC-2822 (the latest mail header standard) compliant, andaddresses that aren't deliverable which, are compliant. However, thefollowing will match valid RFC-2822 addresses that do not have comments,folding whitespace, or any other obsolete or non-essential elements.This I<just> matches the address itself: my $atom = qr{[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+}; my $dot_atom = qr{$atom(?:\.$atom)*}; my $quoted = qr{"(?:\\[^\r\n]|[^\\"])*"}; my $local = qr{(?:$dot_atom|$quoted)}; my $domain_lit = qr{\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\]}; my $domain = qr{(?:$dot_atom|$domain_lit)}; my $addr_spec = qr{$local\@$domain};Just match an address against C</^${addr_spec}$/> to see if it followsthe RFC2822 specification. However, because it is impossible to besure that such a correctly formed address is actually the correct wayto reach a particular person or even has a mailbox associated with it,you must be very careful about how you use this.Our best advice for verifying a person's mail address is to have thementer their address twice, just as you normally do to change apassword. This usually weeds out typos. If both versions match, sendmail to that address with a personal message. If you get the messageback and they've followed your directions, you can be reasonablyassured that it's real.A related strategy that's less open to forgery is to give them a PIN(personal ID number). Record the address and PIN (best that it be arandom one) for later processing. In the mail you send, ask them toinclude the PIN in their reply. But if it bounces, or the message isincluded via a "vacation" script, it'll be there anyway. So it'sbest to ask them to mail back a slight alteration of the PIN, such aswith the characters reversed, one added or subtracted to each digit, etc.=head2 How do I decode a MIME/BASE64 string?The MIME-Base64 package (available from CPAN) handles this as well asthe MIME/QP encoding. Decoding BASE64 becomes as simple as: use MIME::Base64; $decoded = decode_base64($encoded);The MIME-Tools package (available from CPAN) supports extraction withdecoding of BASE64 encoded attachments and content directly from emailmessages.If the string to decode is short (less than 84 bytes long)a more direct approach is to use the unpack() function's "u"format after minor transliterations: 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=head2 How do I return the user's mail address?On systems that support getpwuid, the $< variable, and theSys::Hostname module (which is part of the standard perl distribution),you can probably try using something like this: use Sys::Hostname; $address = sprintf('%s@%s', scalar getpwuid($<), hostname);Company policies on mail address can mean that this generates addressesthat the company's mail system will not accept, so you should ask forusers' mail addresses when this matters. Furthermore, not all systemson which Perl runs are so forthcoming with this information as is Unix.The Mail::Util module from CPAN (part of the MailTools package) provides amailaddress() function that tries to guess the mail address of the user.It makes a more intelligent guess than the code above, using informationgiven when the module was installed, but it could still be incorrect.Again, the best way is often just to ask the user.=head2 How do I send mail?Use the C<sendmail> program directly: open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq") or die "Can't fork for sendmail: $!\n"; print SENDMAIL <<"EOF"; From: User Originating Mail <me\@host> To: Final Destination <you\@otherhost> Subject: A relevant subject line 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";The B<-oi> option prevents sendmail from interpreting a line consistingof a single dot as "end of message". The B<-t> option says to use theheaders to decide who to send the message to, and B<-odq> says to putthe message into the queue. This last option means your message won'tbe immediately delivered, so leave it out if you want immediatedelivery.Alternate, less convenient approaches include calling mail (sometimescalled mailx) directly or simply opening up port 25 have having anintimate conversation between just you and the remote SMTP daemon,probably sendmail.Or you might be able use the CPAN module Mail::Mailer: use Mail::Mailer; $mailer = Mail::Mailer->new(); $mailer->open({ From => $from_address, To => $to_address, Subject => $subject, }) or die "Can't open: $!\n"; print $mailer $body; $mailer->close();The Mail::Internet module uses Net::SMTP which is less Unix-centric thanMail::Mailer, but less reliable. Avoid raw SMTP commands. Thereare many reasons to use a mail transport agent like sendmail. Theseinclude queuing, MX records, and security.=head2 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). use MIME::Lite; ### Create a new multipart message: $msg = MIME::Lite->new( From =>'me@myhost.com', To =>'you@yourhost.com', Cc =>'some@other.com, some@more.com', Subject =>'A message with 2 parts...', Type =>'multipart/mixed' ); ### 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' ); $text = $msg->as_string;MIME::Lite also includes a method for sending these things. $msg->send;This defaults to using L<sendmail> but can be customized to useSMTP via L<Net::SMTP>.=head2 How do I read mail?While you could use the Mail::Folder module from CPAN (part of theMailFolder package) or the Mail::Internet module from CPAN (partof the MailTools package), often a module is overkill. Here's amail sorter. #!/usr/bin/perl my(@msgs, @sub); my $msgno = -1; $/ = ''; # paragraph reads while (<>) { if (/^From /m) { /^Subject:\s*(?:Re:\s*)*(.*)/mi; $sub[++$msgno] = lc($1) || ''; } $msgs[$msgno] .= $_; } for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) { print $msgs[$i]; }Or more succinctly, #!/usr/bin/perl -n00 # bysub2 - awkish sort-by-subject BEGIN { $msgno = -1 } $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m; $msg[$msgno] .= $_; END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }=head2 How do I find out my hostname, domainname, or IP address?X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa,gethostbyname, Socket, Net::Domain, Sys::Hostname>(contributed by brian d foy)The Net::Domain module, which is part of the standard distribution startingin perl5.7.3, can get you the fully qualified domain name (FQDN), the hostname, or the domain name. use Net::Domain qw(hostname hostfqdn hostdomain); my $host = hostfqdn();The C<Sys::Hostname> module, included in the standard distribution sinceperl5.6, can also get the hostname. use Sys::Hostname; $host = hostname();To get the IP address, you can use the C<gethostbyname> built-in functionto turn the name into a number. To turn that number into the dotted octetform (a.b.c.d) that most people expect, use the C<inet_ntoa> functionfrom the <Socket> module, which also comes with perl. use Socket; my $address = inet_ntoa( scalar gethostbyname( $host || 'localhost' ) );=head2 How do I fetch a news article or the active newsgroups?Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.This can make tasks like fetching the newsgroup list as simple as perl -MNews::NNTPClient -e 'print News::NNTPClient->new->list("newsgroups")'=head2 How do I fetch/put an FTP file?LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (alsoavailable from CPAN) is more complex but can put as well as fetch.=head2 How can I do RPC in Perl?(Contributed by brian d foy)Use one of the RPC modules you can find on CPAN (http://search.cpan.org/search?query=RPC&mode=all ).=head1 REVISIONRevision: $Revision: 8539 $Date: $Date: 2007-01-11 00:07:14 +0100 (Thu, 11 Jan 2007) $See L<perlfaq> for source control details and availability.=head1 AUTHOR AND COPYRIGHTCopyright (c) 1997-2007 Tom Christiansen, Nathan Torkington, andother authors as noted. All rights reserved.This documentation is free; you can redistribute it and/or modify itunder the same terms as Perl itself.Irrespective of its distribution, all code examples in this fileare hereby placed into the public domain. You are permitted andencouraged to use this code in your own programs for funor for profit as you see fit. A simple comment in the code givingcredit would be courteous but is not required.
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?