perlfaq3.pod

来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 1,055 行 · 第 1/3 页

POD
1,055 行
字号
Pass arrays and hashes by reference, not by value. For one thing, it'sthe only way to pass multiple lists or hashes (or both) in a singlecall/return. It also avoids creating a copy of all the contents. Thisrequires some judgement, however, because any changes will be propagatedback to the original data. If you really want to mangle (er, modify) acopy, you'll have to sacrifice the memory needed to make one.=item * Tie large variables to disk.For "big" data stores (i.e. ones that exceed available memory) considerusing one of the DB modules to store it on disk instead of in RAM. Thiswill incur a penalty in access time, but that's probably better thancausing your hard disk to thrash due to massive swapping.=back=head2 Is it safe to return a reference to local or lexical data?Yes. Perl's garbage collection system takes care of this soeverything works out right.    sub makeone {	my @a = ( 1 .. 10 );	return \@a;    }    for ( 1 .. 10 ) {        push @many, makeone();    }    print $many[4][5], "\n";    print "@many\n";=head2 How can I free an array or hash so my program shrinks?(contributed by Michael Carman)You usually can't. Memory allocated to lexicals (i.e. my() variables)cannot be reclaimed or reused even if they go out of scope. It isreserved in case the variables come back into scope. Memory allocatedto global variables can be reused (within your program) by usingundef()ing and/or delete().On most operating systems, memory allocated to a program can never bereturned to the system. That's why long-running programs sometimes re-exec themselves. Some operating systems (notably, systems that usemmap(2) for allocating large chunks of memory) can reclaim memory thatis no longer used, but on such systems, perl must be configured andcompiled to use the OS's malloc, not perl's.In general, memory allocation and de-allocation isn't something you canor should be worrying about much in Perl.See also "How can I make my Perl program take less memory?"=head2 How can I make my CGI script more efficient?Beyond the normal measures described to make general Perl programsfaster or smaller, a CGI program has additional issues.  It may be runseveral times per second.  Given that each time it runs it will needto be re-compiled and will often allocate a megabyte or more of systemmemory, this can be a killer.  Compiling into C B<isn't going to helpyou> because the process start-up overhead is where the bottleneck is.There are two popular ways to avoid this overhead.  One solutioninvolves running the Apache HTTP server (available fromhttp://www.apache.org/ ) with either of the mod_perl or mod_fastcgiplugin modules.With mod_perl and the Apache::Registry module (distributed withmod_perl), httpd will run with an embedded Perl interpreter whichpre-compiles your script and then executes it within the same addressspace without forking.  The Apache extension also gives Perl access tothe internal server API, so modules written in Perl can do just aboutanything a module written in C can.  For more on mod_perl, seehttp://perl.apache.org/With the FCGI module (from CPAN) and the mod_fastcgimodule (available from http://www.fastcgi.com/ ) each of your Perlprograms becomes a permanent CGI daemon process.Both of these solutions can have far-reaching effects on your systemand on the way you write your CGI programs, so investigate them withcare.See http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/ .=head2 How can I hide the source for my Perl program?Delete it. :-) Seriously, there are a number of (mostlyunsatisfactory) solutions with varying levels of "security".First of all, however, you I<can't> take away read permission, becausethe source code has to be readable in order to be compiled andinterpreted.  (That doesn't mean that a CGI script's source isreadable by people on the web, though--only by people with access tothe filesystem.)  So you have to leave the permissions at the sociallyfriendly 0755 level.Some people regard this as a security problem.  If your program doesinsecure things and relies on people not knowing how to exploit thoseinsecurities, it is not secure.  It is often possible for someone todetermine the insecure things and exploit them without viewing thesource.  Security through obscurity, the name for hiding your bugsinstead of fixing them, is little security indeed.You can try using encryption via source filters (Starting from Perl5.8 the Filter::Simple and Filter::Util::Call modules are included inthe standard distribution), but any decent programmer will be able todecrypt it.  You can try using the byte code compiler and interpreterdescribed later in L<perlfaq3>, but the curious might still be able tode-compile it. You can try using the native-code compiler describedlater, but crackers might be able to disassemble it.  These posevarying degrees of difficulty to people wanting to get at your code,but none can definitively conceal it (true of every language, not justPerl).It is very easy to recover the source of Perl programs.  You simplyfeed the program to the perl interpreter and use the modules inthe B:: hierarchy.  The B::Deparse module should be able todefeat most attempts to hide source.  Again, this is notunique to Perl.If you're concerned about people profiting from your code, then thebottom line is that nothing but a restrictive license will give youlegal security.  License your software and pepper it with threateningstatements like "This is unpublished proprietary software of XYZ Corp.Your access to it does not give you permission to use it blah blahblah."  We are not lawyers, of course, so you should see a lawyer ifyou want to be sure your license's wording will stand up in court.=head2 How can I compile my Perl program into byte code or C?(contributed by brian d foy)In general, you can't do this.  There are some things that may workfor your situation though.  People usually ask this questionbecause they want to distribute their works without giving awaythe source code, and most solutions trade disk space for convenience.You probably won't see much of a speed increase either, since mostsolutions simply bundle a Perl interpreter in the final product(but see L<How can I make my Perl program run faster?>).The Perl Archive Toolkit ( http://par.perl.org/ ) is Perl'sanalog to Java's JAR.  It's freely available and on CPAN (http://search.cpan.org/dist/PAR/ ).There are also some commercial products that may work for you, althoughyou have to buy a license for them.The Perl Dev Kit ( http://www.activestate.com/Products/Perl_Dev_Kit/ )from ActiveState can "Turn your Perl programs into ready-to-runexecutables for HP-UX, Linux, Solaris and Windows."Perl2Exe ( http://www.indigostar.com/perl2exe.htm ) is a command lineprogram for converting perl scripts to executable files.  It targets bothWindows and unix platforms.=head2 How can I get C<#!perl> to work on [MS-DOS,NT,...]?For OS/2 just use    extproc perl -S -your_switchesas the first line in C<*.cmd> file (C<-S> due to a bug in cmd.exe's"extproc" handling).  For DOS one should first invent a correspondingbatch file and codify it in C<ALTERNATE_SHEBANG> (see theF<dosish.h> file in the source distribution for more information).The Win95/NT installation, when using the ActiveState port of Perl,will modify the Registry to associate the C<.pl> extension with theperl interpreter.  If you install another port, perhaps even buildingyour own Win95/NT Perl from the standard sources by using a Windows portof gcc (e.g., with cygwin or mingw32), then you'll have to modifythe Registry yourself.  In addition to associating C<.pl> with theinterpreter, NT people can use: C<SET PATHEXT=%PATHEXT%;.PL> to let themrun the program C<install-linux.pl> merely by typing C<install-linux>.Under "Classic" MacOS, a perl program will have the appropriate Creator andType, so that double-clicking them will invoke the MacPerl application.Under Mac OS X, clickable apps can be made from any C<#!> script using WilSanchez' DropScript utility: http://www.wsanchez.net/software/ .I<IMPORTANT!>: Whatever you do, PLEASE don't get frustrated, and justthrow the perl interpreter into your cgi-bin directory, in order toget your programs working for a web server.  This is an EXTREMELY bigsecurity risk.  Take the time to figure out how to do it correctly.=head2 Can I write useful Perl programs on the command line?Yes.  Read L<perlrun> for more information.  Some examples follow.(These assume standard Unix shell quoting rules.)    # sum first and last fields    perl -lane 'print $F[0] + $F[-1]' *    # identify text files    perl -le 'for(@ARGV) {print if -f && -T _}' *    # remove (most) comments from C program    perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c    # make file a month younger than today, defeating reaper daemons    perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *    # find first unused uid    perl -le '$i++ while getpwuid($i); print $i'    # display reasonable manpath    echo $PATH | perl -nl -072 -e '	s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'OK, the last one was actually an Obfuscated Perl Contest entry. :-)=head2 Why don't Perl one-liners work on my DOS/Mac/VMS system?The problem is usually that the command interpreters on those systemshave rather different ideas about quoting than the Unix shells underwhich the one-liners were created.  On some systems, you may have tochange single-quotes to double ones, which you must I<NOT> do on Unixor Plan9 systems.  You might also have to change a single % to a %%.For example:    # Unix (including Mac OS X)    perl -e 'print "Hello world\n"'    # DOS, etc.    perl -e "print \"Hello world\n\""    # Mac Classic    print "Hello world\n"     (then Run "Myscript" or Shift-Command-R)    # MPW    perl -e 'print "Hello world\n"'    # VMS    perl -e "print ""Hello world\n"""The problem is that none of these examples are reliable: they depend on thecommand interpreter.  Under Unix, the first two often work. Under DOS,it's entirely possible that neither works.  If 4DOS was the command shell,you'd probably have better luck like this:  perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""Under the Mac, it depends which environment you are using.  The MacPerlshell, or MPW, is much like Unix shells in its support for severalquoting variants, except that it makes free use of the Mac's non-ASCIIcharacters as control characters.Using qq(), q(), and qx(), instead of "double quotes", 'singlequotes', and `backticks`, may make one-liners easier to write.There is no general solution to all of this.  It is a mess.[Some of this answer was contributed by Kenneth Albanowski.]=head2 Where can I learn about CGI or Web programming in Perl?For modules, get the CGI or LWP modules from CPAN.  For textbooks,see the two especially dedicated to web stuff in the question onbooks.  For problems and questions related to the web, like "Whydo I get 500 Errors" or "Why doesn't it run from the browser rightwhen it runs fine on the command line", see the troubleshootingguides and references in L<perlfaq9> or in the CGI MetaFAQ:	http://www.perl.org/CGI_MetaFAQ.html=head2 Where can I learn about object-oriented Perl programming?A good place to start is L<perltoot>, and you can use L<perlobj>,L<perlboot>, L<perltoot>, L<perltooc>, and L<perlbot> for reference.A good book on OO on Perl is the "Object-Oriented Perl"by Damian Conway from Manning Publications, or "Intermediate Perl"by Randal Schwartz, brian d foy, and Tom Phoenix from O'Reilly Media.=head2 Where can I learn about linking C with Perl?If you want to call C from Perl, start with L<perlxstut>,moving on to L<perlxs>, L<xsubpp>, and L<perlguts>.  If you want tocall Perl from C, then read L<perlembed>, L<perlcall>, andL<perlguts>.  Don't forget that you can learn a lot from looking athow the authors of existing extension modules wrote their code andsolved their problems.You might not need all the power of XS. The Inline::C module letsyou put C code directly in your Perl source. It handles all themagic to make it work. You still have to learn at least some ofthe perl API but you won't have to deal with the complexity of theXS support files.=head2 I've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong?Download the ExtUtils::Embed kit from CPAN and run `make test'.  Ifthe tests pass, read the pods again and again and again.  If theyfail, see L<perlbug> and send a bug report with the output ofC<make test TEST_VERBOSE=1> along with C<perl -V>.=head2 When I tried to run my script, I got this message. What does it mean?A complete list of Perl's error messages and warnings with explanatorytext can be found in L<perldiag>. You can also use the splain program(distributed with Perl) to explain the error messages:    perl program 2>diag.out    splain [-v] [-p] diag.outor change your program to explain the messages for you:    use diagnostics;or    use diagnostics -verbose;=head2 What's MakeMaker?(contributed by brian d foy)The C<ExtUtils::MakeMaker> module, better known simply as "MakeMaker",turns a Perl script, typically called C<Makefile.PL>, into a Makefile.The unix tool C<make> uses this file to manage dependencies and actionsto process and install a Perl distribution.=head1 REVISIONRevision: $Revision: 10127 $Date: $Date: 2007-10-27 21:40:20 +0200 (Sat, 27 Oct 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 here are in the publicdomain.  You are permitted and encouraged to use this code and anyderivatives thereof in your own programs for fun or for profit as yousee fit.  A simple comment in the code giving credit to the FAQ wouldbe courteous but is not required.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?