Found in /usr/share/perl/5.34/pod/perlfaq2.pod I grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work? Read the INSTALL file, which is part of the source distribution. It describes in detail how to cope with most idiosyncrasies that the "Configure" script can't work around for any given system or architecture. Found in /usr/share/perl/5.34/pod/perlfaq3.pod How can I make my Perl program run faster? The best way to do this is to come up with a better algorithm. This can often make a dramatic difference. Jon Bentley's book *Programming Pearls* (that's not a misspelling!) has some good tips on optimization, too. Advice on benchmarking boils down to: benchmark and profile to make sure you're optimizing the right part, look for better algorithms instead of microtuning your code, and when all else fails consider just buying faster hardware. You will probably want to read the answer to the earlier question "How do I profile my Perl programs?" if you haven't done so already. A different approach is to autoload seldom-used Perl code. See the AutoSplit and AutoLoader modules in the standard distribution for that. Or you could locate the bottleneck and think about writing just that part in C, the way we used to take bottlenecks in C code and write them in assembler. Similar to rewriting in C, modules that have critical sections can be written in C (for instance, the PDL module from CPAN). If you're currently linking your perl executable to a shared *libc.so*, you can often gain a 10-25% performance benefit by rebuilding it to link with a static libc.a instead. This will make a bigger perl executable, but your Perl programs (and programmers) may thank you for it. See the INSTALL file in the source distribution for more information. The undump program was an ancient attempt to speed up Perl program by storing the already-compiled form to disk. This is no longer a viable option, as it only worked on a few architectures, and wasn't a good solution anyway. How can I make my Perl program take less memory? When it comes to time-space tradeoffs, Perl nearly always prefers to throw memory at a problem. Scalars in Perl use more memory than strings in C, arrays take more than that, and hashes use even more. While there's still a lot to be done, recent releases have been addressing these issues. For example, as of 5.004, duplicate hash keys are shared amongst all hashes using them, so require no reallocation. In some cases, using substr() or vec() to simulate arrays can be highly beneficial. For example, an array of a thousand booleans will take at least 20,000 bytes of space, but it can be turned into one 125-byte bit vector--a considerable memory savings. The standard Tie::SubstrHash module can also help for certain types of data structure. If you're working with specialist data structures (matrices, for instance) modules that implement these in C may use less memory than equivalent Perl modules. Another thing to try is learning whether your Perl was compiled with the system malloc or with Perl's builtin malloc. Whichever one it is, try using the other one and see whether this makes a difference. Information about malloc is in the INSTALL file in the source distribution. You can find out whether you are using perl's malloc by typing "perl -V:usemymalloc". Of course, the best way to save memory is to not do anything to waste it in the first place. Good programming practices can go a long way toward this: Don't slurp! Don't read an entire file into memory if you can process it line by line. Or more concretely, use a loop like this: # # Good Idea # while (my $line = <$file_handle>) { # ... } instead of this: # # Bad Idea # my @data = <$file_handle>; foreach (@data) { # ... } When the files you're processing are small, it doesn't much matter which way you do it, but it makes a huge difference when they start getting larger. Use map and grep selectively Remember that both map and grep expect a LIST argument, so doing this: @wanted = grep {/pattern/} <$file_handle>; will cause the entire file to be slurped. For large files, it's better to loop: while (<$file_handle>) { push(@wanted, $_) if /pattern/; } Avoid unnecessary quotes and stringification Don't quote large strings unless absolutely necessary: my $copy = "$large_string"; makes 2 copies of $large_string (one for $copy and another for the quotes), whereas my $copy = $large_string; only makes one copy. Ditto for stringifying large arrays: { local $, = "\n"; print @big_array; } is much more memory-efficient than either print join "\n", @big_array; or { local $" = "\n"; print "@big_array"; } Pass by reference Pass arrays and hashes by reference, not by value. For one thing, it's the only way to pass multiple lists or hashes (or both) in a single call/return. It also avoids creating a copy of all the contents. This requires some judgement, however, because any changes will be propagated back to the original data. If you really want to mangle (er, modify) a copy, you'll have to sacrifice the memory needed to make one. Tie large variables to disk For "big" data stores (i.e. ones that exceed available memory) consider using one of the DB modules to store it on disk instead of in RAM. This will incur a penalty in access time, but that's probably better than causing your hard disk to thrash due to massive swapping. How can I make my CGI script more efficient? Beyond the normal measures described to make general Perl programs faster or smaller, a CGI program has additional issues. It may be run several times per second. Given that each time it runs it will need to be re-compiled and will often allocate a megabyte or more of system memory, this can be a killer. Compiling into C isn't going to help you because the process start-up overhead is where the bottleneck is. There are three popular ways to avoid this overhead. One solution involves running the Apache HTTP server (available from <http://www.apache.org/> ) with either of the mod_perl or mod_fastcgi plugin modules. With mod_perl and the Apache::Registry module (distributed with mod_perl), httpd will run with an embedded Perl interpreter which pre-compiles your script and then executes it within the same address space without forking. The Apache extension also gives Perl access to the internal server API, so modules written in Perl can do just about anything a module written in C can. For more on mod_perl, see <http://perl.apache.org/> With the FCGI module (from CPAN) and the mod_fastcgi module (available from <http://www.fastcgi.com/> ) each of your Perl programs becomes a permanent CGI daemon process. Finally, Plack is a Perl module and toolkit that contains PSGI middleware, helpers and adapters to web servers, allowing you to easily deploy scripts which can continue running, and provides flexibility with regards to which web server you use. It can allow existing CGI scripts to enjoy this flexibility and performance with minimal changes, or can be used along with modern Perl web frameworks to make writing and deploying web services with Perl a breeze. These solutions can have far-reaching effects on your system and on the way you write your CGI programs, so investigate them with care. See also <http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI /> . What's MakeMaker? (contributed by brian d foy) The ExtUtils::MakeMaker module, better known simply as "MakeMaker", turns a Perl script, typically called "Makefile.PL", into a Makefile. The Unix tool "make" uses this file to manage dependencies and actions to process and install a Perl distribution. Found in /usr/share/perl/5.34/pod/perlfaq4.pod Why don't my tied hashes make the defined/exists distinction? This depends on the tied hash's implementation of EXISTS(). For example, there isn't the concept of undef with hashes that are tied to DBM* files. It also means that exists() and defined() do the same thing with a DBM* file, and what they end up doing is not what they do with ordinary hashes. How can I make my hash remember the order I put elements into it? Use the Tie::IxHash from CPAN. use Tie::IxHash; tie my %myhash, 'Tie::IxHash'; for (my $i=0; $i<20; $i++) { $myhash{$i} = 2*$i; } my @keys = keys %myhash; # @keys = (0,1,2,3,...) How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays? Usually a hash ref, perhaps like this: $record = { NAME => "Jason", EMPNO => 132, TITLE => "deputy peon", AGE => 23, SALARY => 37_000, PALS => [ "Norbert", "Rhys", "Phineas"], }; References are documented in perlref and perlreftut. Examples of complex data structures are given in perldsc and perllol. Examples of structures and object-oriented classes are in perlootut. Found in /usr/share/perl/5.34/pod/perlfaq5.pod How do I make a temporary file name? If you don't need to know the name of the file, you can use "open()" with "undef" in place of the file name. In Perl 5.8 or later, the "open()" function creates an anonymous temporary file: open my $tmp, '+>', undef or die $!; Otherwise, you can use the File::Temp module. use File::Temp qw/ tempfile tempdir /; my $dir = tempdir( CLEANUP => 1 ); ($fh, $filename) = tempfile( DIR => $dir ); # or if you don't need to know the filename my $fh = tempfile( DIR => $dir ); The File::Temp has been a standard module since Perl 5.6.1. If you don't have a modern enough Perl installed, use the "new_tmpfile" class method from the IO::File module to get a filehandle opened for reading and writing. Use it if you don't need to know the file's name: use IO::File; my $fh = IO::File->new_tmpfile() or die "Unable to make new temporary file: $!"; If you're committed to creating a temporary file by hand, use the process ID and/or the current time-value. If you need to have many temporary files in one process, use a counter: BEGIN { use Fcntl; use File::Spec; my $temp_dir = File::Spec->tmpdir(); my $file_base = sprintf "%d-%d-0000", $$, time; my $base_name = File::Spec->catfile($temp_dir, $file_base); sub temp_file { my $fh; my $count = 0; until( defined(fileno($fh)) || $count++ > 100 ) { $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e; # O_EXCL is required for security reasons. sysopen $fh, $base_name, O_WRONLY|O_EXCL|O_CREAT; } if( defined fileno($fh) ) { return ($fh, $base_name); } else { return (); } } } How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable. You can then pass these references just like any other scalar, and use them in the place of named handles. open my $fh, $file_name; open local $fh, $file_name; print $fh "Hello World!\n"; process_file( $fh ); If you like, you can store these filehandles in an array or a hash. If you access them directly, they aren't simple scalars and you need to give "print" a little help by placing the filehandle reference in braces. Perl can only figure it out on its own when the filehandle reference is a simple scalar. my @fhs = ( $fh1, $fh2, $fh3 ); for( $i = 0; $i <= $#fhs; $i++ ) { print {$fhs[$i]} "just another Perl answer, \n"; } Before perl5.6, you had to deal with various typeglob idioms which you may see in older code. open FILE, "> $filename"; process_typeglob( *FILE ); process_reference( \*FILE ); sub process_typeglob { local *FH = shift; print FH "Typeglob!" } sub process_reference { local $fh = shift; print $fh "Reference!" } If you want to create many anonymous handles, you should check out the Symbol or IO::Handle modules. Found in /usr/share/perl/5.34/pod/perlfaq6.pod How can I make "\w" match national character sets? Put "use locale;" in your script. The \w character class is taken from the current locale. See perllocale for details. Found in /usr/share/perl/5.34/pod/perlfaq8.pod How do I make a system() exit on control-C? You can't. You need to imitate the "system()" call (see perlipc for sample code) and then have a signal handler for the INT signal that passes the signal on to the subprocess. Or you can check for it: $rc = system($cmd); if ($rc & 127) { die "signal death" } Found in /usr/share/perl/5.34/pod/perlfaq9.pod How do I make sure users can't enter values into a form that causes my CGI script to do bad things? (contributed by brian d foy) You can't prevent people from sending your script bad data. Even if you add some client-side checks, people may disable them or bypass them completely. For instance, someone might use a module such as LWP to submit to your web site. If you want to prevent data that try to use SQL injection or other sorts of attacks (and you should want to), you have to not trust any data that enter your program. The perlsec documentation has general advice about data security. If you are using the DBI module, use placeholder to fill in data. If you are running external programs with "system" or "exec", use the list forms. There are many other precautions that you should take, too many to list here, and most of them fall under the category of not using any data that you don't intend to use. Trust no one. How do I use MIME to make an attachment to a mail message? Email::MIME directly supports multipart messages. Email::MIME objects themselves are parts and can be attached to other Email::MIME objects. Consult the Email::MIME documentation for more information, including all of the supported methods and examples of their use. Email::Stuffer uses Email::MIME under the hood to construct messages, and wraps the most common attachment tasks with the simple "attach" and "attach_file" methods. Email::Stuffer->to('friend AT example.com') ->subject('The file') ->attach_file('stuff.csv') ->send_or_die;
Generated by phpman v3.7.12 Author: Che Dong Under GNU General Public License
2026-06-13 17:45 @216.73.216.196
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)