Debian Codegraph @

upstream/mageia-cauldron/man1/perlfaq9.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLFAQ9 1"
61 .TH PERLFAQ9 1 2025-06-24 "perl v5.42.0" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlfaq9 \- Web, Email and Networking
68 .SH VERSION
69 .IX Header "VERSION"
70 version 5.20250619
71 .SH DESCRIPTION
72 .IX Header "DESCRIPTION"
73 This section deals with questions related to running web sites,
74 sending and receiving email as well as general networking.
75 .SS "Should I use a web framework?"
76 .IX Subsection "Should I use a web framework?"
77 Yes. If you are building a web site with any level of interactivity
78 (forms / users / databases), you
79 will want to use a framework to make handling requests
80 and responses easier.
81 .PP
82 If there is no interactivity then you may still want
83 to look at using something like Template Toolkit <https://metacpan.org/module/Template>
84 or Plack::Middleware::TemplateToolkit
85 so maintenance of your HTML files (and other assets) is easier.
86 .SS "Which web framework should I use?"
87 .IX Xref "framework CGI.pm CGI Catalyst Dancer"
88 .IX Subsection "Which web framework should I use?"
89 There is no simple answer to this question. Perl frameworks can run everything
90 from basic file servers and small\-scale intranets to massive multinational
91 multilingual websites that are the core to international businesses.
92 .PP
93 Below is a list of a few frameworks with comments which might help you in
94 making a decision, depending on your specific requirements. Start by reading
95 the docs, then ask questions on the relevant mailing list or IRC channel.
96 .IP Catalyst 4
97 .IX Item "Catalyst"
98 Strongly object\-oriented and fully\-featured with a long development history and
99 a large community and addon ecosystem. It is excellent for large and complex
100 applications, where you have full control over the server.
101 .IP Dancer2 4
102 .IX Item "Dancer2"
103 Free of legacy weight, providing a lightweight and easy\-to\-learn API.
104 Has a growing addon ecosystem. It is best used for smaller projects and
105 very easy to learn for beginners.
106 .IP Mojolicious 4
107 .IX Item "Mojolicious"
108 Self\-contained and powerful for both small and larger projects,
109 with a focus on HTML5 and real\-time web technologies such as WebSockets.
110 .IP Web::Simple 4
111 .IX Item "Web::Simple"
112 Strongly object\-oriented and minimal, built for speed and intended
113 as a toolkit for building micro web apps, custom frameworks or for tieing
114 together existing Plack\-compatible web applications with one central dispatcher.
115 .PP
116 All of these interact with or use Plack which is worth understanding
117 the basics of when building a website in Perl (there is a lot of useful
118 Plack::Middleware <https://metacpan.org/search?q=plack%3A%3Amiddleware>).
119 .SS "What is Plack and PSGI?"
120 .IX Subsection "What is Plack and PSGI?"
121 PSGI is the Perl Web Server Gateway Interface Specification, it is
122 a standard that many Perl web frameworks use, you should not need to
123 understand it to build a web site, the part you might want to use is Plack.
124 .PP
125 Plack is a set of tools for using the PSGI stack. It contains
126 middleware <https://metacpan.org/search?q=plack%3A%3Amiddleware>
127 components, a reference server and utilities for Web application frameworks.
128 Plack is like Ruby\*(Aqs Rack or Python\*(Aqs Paste for WSGI.
129 .PP
130 You could build a web site using Plack and your own code,
131 but for anything other than a very basic web site, using a web framework
132 (that uses <https://plackperl.org>) is a better option.
133 .SS "How do I remove HTML from a string?"
134 .IX Subsection "How do I remove HTML from a string?"
135 Use HTML::Strip, or HTML::FormatText which not only removes HTML
136 but also attempts to do a little simple formatting of the resulting
137 plain text.
138 .SS "How do I extract URLs?"
139 .IX Subsection "How do I extract URLs?"
140 HTML::SimpleLinkExtor will extract URLs from HTML, it handles anchors,
141 images, objects, frames, and many other tags that can contain a URL.
142 If you need anything more complex, you can create your own subclass of
143 HTML::LinkExtor or HTML::Parser. You might even use
144 HTML::SimpleLinkExtor as an example for something specifically
145 suited to your needs.
146 .PP
147 You can use URI::Find or URL::Search to extract URLs from an
148 arbitrary text document.
149 .SS "How do I fetch an HTML file?"
150 .IX Subsection "How do I fetch an HTML file?"
151 (contributed by brian d foy)
152 .PP
153 The core HTTP::Tiny module can fetch web resources and give their
154 content back to you as a string:
155 .PP
156 .Vb 1
157 \& use HTTP::Tiny;
158 \&
159 \& my $ua = HTTP::Tiny\->new;
160 \& my $html = $ua\->get( "http://www.example.com/index.html" )\->{content};
161 .Ve
162 .PP
163 It can also store the resource directly in a file:
164 .PP
165 .Vb 1
166 \& $ua\->mirror( "http://www.example.com/index.html", "foo.html" );
167 .Ve
168 .PP
169 If you need to do something more complicated, the HTTP::Tiny object can
170 be customized by setting attributes, or you can use LWP::UserAgent from
171 the libwww\-perl distribution or Mojo::UserAgent from the Mojolicious
172 distribution to make common tasks easier. If you want to simulate an
173 interactive web browser, you can use the WWW::Mechanize module.
174 .SS "How do I automate an HTML form submission?"
175 .IX Subsection "How do I automate an HTML form submission?"
176 If you are doing something complex, such as moving through many pages
177 and forms or a web site, you can use WWW::Mechanize. See its
178 documentation for all the details.
179 .PP
180 If you\*(Aqre submitting values using the GET method, create a URL and encode
181 the form using the \f(CW\*(C`www_form_urlencode\*(C'\fR method from HTTP::Tiny:
182 .PP
183 .Vb 1
184 \& use HTTP::Tiny;
185 \&
186 \& my $ua = HTTP::Tiny\->new;
187 \&
188 \& my $query = $ua\->www_form_urlencode([ q => \*(AqDB_File\*(Aq, lucky => 1 ]);
189 \& my $url = "https://metacpan.org/search?$query";
190 \& my $content = $ua\->get($url)\->{content};
191 .Ve
192 .PP
193 If you\*(Aqre using the POST method, the \f(CW\*(C`post_form\*(C'\fR method will encode the
194 content appropriately.
195 .PP
196 .Vb 1
197 \& use HTTP::Tiny;
198 \&
199 \& my $ua = HTTP::Tiny\->new;
200 \&
201 \& my $url = \*(Aqhttps://metacpan.org/search\*(Aq;
202 \& my $form = [ q => \*(AqDB_File\*(Aq, lucky => 1 ];
203 \& my $content = $ua\->post_form($url, $form)\->{content};
204 .Ve
205 .SS "How do I decode or create those %\-encodings on the web?"
206 .IX Xref "URI URI::Escape RFC 2396"
207 .IX Subsection "How do I decode or create those %-encodings on the web?"
208 Most of the time you should not need to do this as
209 your web framework, or if you are making a request,
210 the LWP or other module would handle it for you.
211 .PP
212 To encode a string yourself, use the URI::Escape module. The \f(CW\*(C`uri_escape\*(C'\fR
213 function returns the escaped string:
214 .PP
215 .Vb 1
216 \& my $original = "Colon : Hash # Percent %";
217 \&
218 \& my $escaped = uri_escape( $original );
219 \&
220 \& print "$escaped\en"; # \*(AqColon%20%3A%20Hash%20%23%20Percent%20%25\*(Aq
221 .Ve
222 .PP
223 To decode the string, use the \f(CW\*(C`uri_unescape\*(C'\fR function:
224 .PP
225 .Vb 1
226 \& my $unescaped = uri_unescape( $escaped );
227 \&
228 \& print $unescaped; # back to original
229 .Ve
230 .PP
231 Remember not to encode a full URI, you need to escape each
232 component separately and then join them together.
233 .SS "How do I redirect to another page?"
234 .IX Subsection "How do I redirect to another page?"
235 Most Perl Web Frameworks will have a mechanism for doing this,
236 using the Catalyst framework it would be:
237 .PP
238 .Vb 2
239 \& $c\->res\->redirect($url);
240 \& $c\->detach();
241 .Ve
242 .PP
243 If you are using Plack (which most frameworks do), then
244 Plack::Middleware::Rewrite is worth looking at if you
245 are migrating from Apache or have URL\*(Aqs you want to always
246 redirect.
247 .SS "How do I put a password on my web pages?"
248 .IX Subsection "How do I put a password on my web pages?"
249 See if the web framework you are using has an
250 authentication system and if that fits your needs.
251 .PP
252 Alternatively, look at Plack::Middleware::Auth::Basic,
253 or one of the other Plack authentication <https://metacpan.org/search?q=plack+auth>
254 options.
255 .SS "How do I make sure users can\*(Aqt enter values into a form that causes my CGI script to do bad things?"
256 .IX Subsection "How do I make sure users can't enter values into a form that causes my CGI script to do bad things?"
257 (contributed by brian d foy)
258 .PP
259 You can\*(Aqt prevent people from sending your script bad data. Even if
260 you add some client\-side checks, people may disable them or bypass
261 them completely. For instance, someone might use a module such as
262 LWP to submit to your web site. If you want to prevent data that
263 try to use SQL injection or other sorts of attacks (and you should
264 want to), you have to not trust any data that enter your program.
265 .PP
266 The perlsec documentation has general advice about data security.
267 If you are using the DBI module, use placeholders to fill in data.
268 If you are running external programs with \f(CW\*(C`system\*(C'\fR or \f(CW\*(C`exec\*(C'\fR, use
269 the list forms. There are many other precautions that you should take,
270 too many to list here, and most of them fall under the category of not
271 using any data that you don\*(Aqt intend to use. Trust no one.
272 .SS "How do I parse a mail header?"
273 .IX Subsection "How do I parse a mail header?"
274 Use the Email::MIME module. It\*(Aqs well\-tested and supports all the
275 craziness that you\*(Aqll see in the real world (comment\-folding whitespace,
276 encodings, comments, etc.).
277 .PP
278 .Vb 1
279 \& use Email::MIME;
280 \&
281 \& my $message = Email::MIME\->new($rfc2822);
282 \& my $subject = $message\->header(\*(AqSubject\*(Aq);
283 \& my $from = $message\->header(\*(AqFrom\*(Aq);
284 .Ve
285 .PP
286 If you\*(Aqve already got some other kind of email object, consider passing
287 it to Email::Abstract and then using its cast method to get an
288 Email::MIME object:
289 .PP
290 .Vb 2
291 \& my $abstract = Email::Abstract\->new($mail_message_object);
292 \& my $email_mime_object = $abstract\->cast(\*(AqEmail::MIME\*(Aq);
293 .Ve
294 .SS "How do I check a valid mail address?"
295 .IX Subsection "How do I check a valid mail address?"
296 (partly contributed by Aaron Sherman)
297 .PP
298 This isn\*(Aqt as simple a question as it sounds. There are two parts:
299 .PP
300 a) How do I verify that an email address is correctly formatted?
301 .PP
302 b) How do I verify that an email address targets a valid recipient?
303 .PP
304 Without sending mail to the address and seeing whether there\*(Aqs a human
305 on the other end to answer you, you cannot fully answer part \fIb\fR, but
306 the Email::Valid module will do both part \fIa\fR and part \fIb\fR as far
307 as you can in real\-time.
308 .PP
309 Our best advice for verifying a person\*(Aqs mail address is to have them
310 enter their address twice, just as you normally do to change a
311 password. This usually weeds out typos. If both versions match, send
312 mail to that address with a personal message. If you get the message
313 back and they\*(Aqve followed your directions, you can be reasonably
314 assured that it\*(Aqs real.
315 .PP
316 A related strategy that\*(Aqs less open to forgery is to give them a PIN
317 (personal ID number). Record the address and PIN (best that it be a
318 random one) for later processing. In the mail you send, include a link to
319 your site with the PIN included. If the mail bounces, you know it\*(Aqs not
320 valid. If they don\*(Aqt click on the link, either they forged the address or
321 (assuming they got the message) following through wasn\*(Aqt important so you
322 don\*(Aqt need to worry about it.
323 .SS "How do I decode a MIME/BASE64 string?"
324 .IX Subsection "How do I decode a MIME/BASE64 string?"
325 The MIME::Base64 package handles this as well as the MIME/QP encoding.
326 Decoding base 64 becomes as simple as:
327 .PP
328 .Vb 2
329 \& use MIME::Base64;
330 \& my $decoded = decode_base64($encoded);
331 .Ve
332 .PP
333 The Email::MIME module can decode base 64\-encoded email message parts
334 transparently so the developer doesn\*(Aqt need to worry about it.
335 .SS "How do I find the user\*(Aqs mail address?"
336 .IX Subsection "How do I find the user's mail address?"
337 Ask them for it. There are so many email providers available that it\*(Aqs
338 unlikely the local system has any idea how to determine a user\*(Aqs email address.
339 .PP
340 The exception is for organization\-specific email (e.g. [email protected])
341 where policy can be codified in your program. In that case, you could look at
342 \&\f(CW$ENV\fR{USER}, \f(CW$ENV\fR{LOGNAME}, and getpwuid($<) in scalar context, like so:
343 .PP
344 .Vb 1
345 \& my $user_name = getpwuid($<)
346 .Ve
347 .PP
348 But you still cannot make assumptions about whether this is correct, unless
349 your policy says it is. You really are best off asking the user.
350 .SS "How do I send email?"
351 .IX Subsection "How do I send email?"
352 Use the Email::Stuffer module, like so:
353 .PP
354 .Vb 5
355 \& # first, create your message
356 \& my $message = Email::Stuffer\->from(\*([email protected]\*(Aq)
357 \& \->to(\*([email protected]\*(Aq)
358 \& \->subject(\*(AqHappy birthday!\*(Aq)
359 \& \->text_body("Happy birthday to you!\en");
360 \&
361 \& $message\->send_or_die;
362 .Ve
363 .PP
364 By default, Email::Sender::Simple (the \f(CW\*(C`send\*(C'\fR and \f(CW\*(C`send_or_die\*(C'\fR methods
365 use this under the hood) will try \f(CW\*(C`sendmail\*(C'\fR first, if it exists
366 in your \f(CW$PATH\fR. This generally isn\*(Aqt the case. If there\*(Aqs a remote mail
367 server you use to send mail, consider investigating one of the Transport
368 classes. At the time of writing, the available transports include:
369 .IP Email::Sender::Transport::Sendmail 4
370 .IX Item "Email::Sender::Transport::Sendmail"
371 This is the default. If you can use the \fBmail\fR\|(1) or \fBmailx\fR\|(1)
372 program to send mail from the machine where your code runs, you should
373 be able to use this.
374 .IP Email::Sender::Transport::SMTP 4
375 .IX Item "Email::Sender::Transport::SMTP"
376 This transport contacts a remote SMTP server over TCP. It optionally
377 uses TLS or SSL and can authenticate to the server via SASL.
378 .PP
379 Telling Email::Stuffer to use your transport is straightforward.
380 .PP
381 .Vb 1
382 \& $message\->transport($email_sender_transport_object)\->send_or_die;
383 .Ve
384 .SS "How do I use MIME to make an attachment to a mail message?"
385 .IX Subsection "How do I use MIME to make an attachment to a mail message?"
386 Email::MIME directly supports multipart messages. Email::MIME
387 objects themselves are parts and can be attached to other Email::MIME
388 objects. Consult the Email::MIME documentation for more information,
389 including all of the supported methods and examples of their use.
390 .PP
391 Email::Stuffer uses Email::MIME under the hood to construct
392 messages, and wraps the most common attachment tasks with the simple
393 \&\f(CW\*(C`attach\*(C'\fR and \f(CW\*(C`attach_file\*(C'\fR methods.
394 .PP
395 .Vb 4
396 \& Email::Stuffer\->to(\*([email protected]\*(Aq)
397 \& \->subject(\*(AqThe file\*(Aq)
398 \& \->attach_file(\*(Aqstuff.csv\*(Aq)
399 \& \->send_or_die;
400 .Ve
401 .SS "How do I read email?"
402 .IX Subsection "How do I read email?"
403 Use the Email::Folder module, like so:
404 .PP
405 .Vb 1
406 \& use Email::Folder;
407 \&
408 \& my $folder = Email::Folder\->new(\*(Aq/path/to/email/folder\*(Aq);
409 \& while(my $message = $folder\->next_message) {
410 \& # next_message returns Email::Simple objects, but we want
411 \& # Email::MIME objects as they\*(Aqre more robust
412 \& my $mime = Email::MIME\->new($message\->as_string);
413 \& }
414 .Ve
415 .PP
416 There are different classes in the Email::Folder namespace for
417 supporting various mailbox types. Note that these modules are generally
418 rather limited and only support \fBreading\fR rather than writing.
419 .SS "How do I find out my hostname, domainname, or IP address?"
420 .IX Xref "hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa, gethostbyname, Socket, Net::Domain, Sys::Hostname"
421 .IX Subsection "How do I find out my hostname, domainname, or IP address?"
422 (contributed by brian d foy)
423 .PP
424 The Net::Domain module, which is part of the Standard Library starting
425 in Perl 5.7.3, can get you the fully qualified domain name (FQDN), the host
426 name, or the domain name.
427 .PP
428 .Vb 1
429 \& use Net::Domain qw(hostname hostfqdn hostdomain);
430 \&
431 \& my $host = hostfqdn();
432 .Ve
433 .PP
434 The Sys::Hostname module, part of the Standard Library, can also get the
435 hostname:
436 .PP
437 .Vb 1
438 \& use Sys::Hostname;
439 \&
440 \& $host = hostname();
441 .Ve
442 .PP
443 The Sys::Hostname::Long module takes a different approach and tries
444 harder to return the fully qualified hostname:
445 .PP
446 .Vb 1
447 \& use Sys::Hostname::Long \*(Aqhostname_long\*(Aq;
448 \&
449 \& my $hostname = hostname_long();
450 .Ve
451 .PP
452 To get the IP address, you can use the \f(CW\*(C`gethostbyname\*(C'\fR built\-in function
453 to turn the name into a number. To turn that number into the dotted octet
454 form (a.b.c.d) that most people expect, use the \f(CW\*(C`inet_ntoa\*(C'\fR function
455 from the Socket module, which also comes with perl.
456 .PP
457 .Vb 1
458 \& use Socket;
459 \&
460 \& my $address = inet_ntoa(
461 \& scalar gethostbyname( $host || \*(Aqlocalhost\*(Aq )
462 \& );
463 .Ve
464 .SS "How do I fetch/put an (S)FTP file?"
465 .IX Subsection "How do I fetch/put an (S)FTP file?"
466 Net::FTP, and Net::SFTP allow you to interact with FTP and SFTP (Secure
467 FTP) servers.
468 .SS "How can I do RPC in Perl?"
469 .IX Subsection "How can I do RPC in Perl?"
470 Use one of the RPC modules( <https://metacpan.org/search?q=RPC> ).
471 .SH "AUTHOR AND COPYRIGHT"
472 .IX Header "AUTHOR AND COPYRIGHT"
473 Copyright (c) 1997\-2010 Tom Christiansen, Nathan Torkington, and
474 other authors as noted. All rights reserved.
475 .PP
476 This documentation is free; you can redistribute it and/or modify it
477 under the same terms as Perl itself.
478 .PP
479 Irrespective of its distribution, all code examples in this file
480 are hereby placed into the public domain. You are permitted and
481 encouraged to use this code in your own programs for fun
482 or for profit as you see fit. A simple comment in the code giving
483 credit would be courteous but is not required.