JETZT ONLINE BESTELLEN
Second Edition Juni 2002
ISBN 978-0-596-00241-1
760 Seiten
EUR32.00
Weitere Informationen zu diesem Buch
Inhaltsverzeichnis | Kolophon |
Inhaltsverzeichnis
- Chapter 1: Introduction to Perl
- InhaltsvorschauComputer languages differ not so much in what they make possible, but in what they make easy. Perl is designed to make the easy jobs easy, without making the hard jobs impossible. Perl makes it easy to manipulate numbers, text, files, directories, computers, networks, and programs. It also makes it easy to develop, modify, and debug your own programs portably, on any modern operating system.Perl is especially popular with systems programmers and web developers, but it also appeals to a much broader audience. Originally designed for text processing, it has grown into a sophisticated, general-purpose programming language with a rich software development environment complete with debuggers, profilers, cross-referencers, compilers, interpreters, libraries, syntax-directed editors, and all the rest of the trappings of a "real" programming language.There are many reasons for Perl's success. For starters, Perl is freely available and freely redistributable. But that's not enough to explain the Perl phenomenon, since many other freeware packages fail to thrive. Perl is not just free; it's also fun. People feel like they can be creative in Perl, because they have freedom of expression.Perl is both a very simple language and a very rich language. It's a simple language in that the types and structures are simple to use and understand, and it borrows heavily from other languages you may already be familiar with. You don't have to know everything there is to know about Perl before you can write useful programs.However, Perl is also a rich language, and there is much to learn about it. That's the price of making hard things possible. Although it will take some time for you to absorb all that Perl can do, somewhere down the line you will be glad that you have access to the extensive capabilities of Perl.Perl has the advantage of being easy to learn if you just want to write simple scripts—thus its appeal to the ever-impatient system administrator and the deadline-driven CGI developer. However, as you become more ambitious, Perl lets you act on those ambitions. Chapter 2 covers how to get and install Perl, and Chapter 3 through Chapter 6 cover the basics of the Perl language, its functions, and how to use the Perl debugger.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- What's Perl Good For?
- InhaltsvorschauPerl has the advantage of being easy to learn if you just want to write simple scripts—thus its appeal to the ever-impatient system administrator and the deadline-driven CGI developer. However, as you become more ambitious, Perl lets you act on those ambitions. Chapter 2 covers how to get and install Perl, and Chapter 3 through Chapter 6 cover the basics of the Perl language, its functions, and how to use the Perl debugger.On top of the Perl language itself, however, are the Perl modules. You can think of modules as add-ons to the Perl language that allow you to streamline tasks by providing a consistent API. Perl itself is fun to use, but the modules lend Perl even more flexibility and enormous power. Furthermore, anyone can write and distribute a Perl module. Some modules are deemed important enough or popular enough to be distributed with Perl itself, but very few are actually written by the core Perl developers themselves. Chapter 7 introduces you to Perl modules, and Chapter 8 covers the standard modules that are distributed with Perl itself.The most popular Perl module is CGI.pm, which gives a simple interface to developing common gateway interface (CGI) applications in Perl. While Perl itself is indispensable for many different tasks, its text-manipulation features make it perfect for CGI development on the Web. In fact, the resurgence of Perl over the past few years must be credited to its popularity as a CGI language. Chapter 10 and Chapter 11 talk about using Perl for CGI, including mod_perl, which merges Perl into the Apache web server.Database interconnectivity is one of the most important functions of any programming language today, and Perl is no exception. DBI is a suite of modules that provide a consistent database-independent interface for Perl. Chapter 12 covers both DBI and DBM (the more primitive but surprisingly effective database interface built directly into Perl).The eXtensible Markup Language (XML) is quickly becoming the de facto way to store electronic information of any kind. Chapter 13 covers the modules designed for Perl and XML processing, and Chapter 14 covers using Perl for managing web services with the XML-based protocol SOAP.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Perl Development
- InhaltsvorschauSoftware doesn't grow on trees. Perl is free because of the donated efforts of several generous people who have devoted large chunks of their spare time to the development, maintenance, and evangelism of Perl.Perl itself was created by Larry Wall, in an effort to produce reports for a bug-reporting system. Larry designed a new scripting language for this purpose and then released it to the Internet, thinking that someone else might find it useful. In the spirit of freeware, other people suggested improvements and even ways to implement them, and Perl transformed from a cute scripting language into a robust programming language.Today, Larry does little actual development himself, but helps to guide several other selfless individuals in the continued development and design of the language. Currently, a team of porters are working (with Larry's guidance) on a complete rewrite of the language from the ground up, which is expected to yield a 21st-century version of the language in form and features. This rewrite will be released as Perl Version 6. At the time of this writing, progress on Perl 6 is steady but still a long way from completion.This second edition of Perl in a Nutshell covers Perl 5.8.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Which Platforms Support Perl?
- InhaltsvorschauWhile Perl was developed on Unix and is closely entwined with Unix culture, it also has a strong following on the Windows and Macintosh platforms. Perl gives Windows 95, Windows NT, Macintosh, and even VMS users the opportunity to take advantage of the scripting power that Unix users take for granted.Most Unix machines will have Perl already installed, since it's one of the first things a Unix system administrator will build for a new machine (and is in fact distributed with the operating system on some versions of Unix, such as Linux and FreeBSD). For Windows NT, Windows 95, and Macintosh, there are binary distributions of Perl that you can download for free. See Chapter 2 for information on installing Perl.Although there is some history of other platforms not being treated seriously by the Perl community, Perl is becoming increasingly friendly to non-Unix platforms. The Win32 ports of Perl are quite stable, and as of Perl 5.8, are integrated wholly with core Perl.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Perl Resources
- InhaltsvorschauParadoxically, the way in which Perl helps you the most has almost nothing to do with Perl itself, and everything to do with the people who use Perl. While people start using Perl because they need it, they continue using Perl because they love it.The result is that the Perl community is one of the most helpful in the world, with CPAN—the Comprehensive Perl Archive Network—as one example. When Perl programmers aren't writing their own programs, they spend their time helping others write theirs. They discuss common problems and help devise solutions. They develop utilities and modules for Perl and give them away to the world at large.The central meeting place for Perl aficionados is Usenet. If you're not familiar with Usenet, it's a collection of special-interest groups (called newsgroups) on the Internet. For most anyone using a modern browser, Usenet access is as simple as a selecting a menu option on the browser. Perl programmers should consider subscribing to the following newsgroups:
- comp.lang.perl.announce
- A moderated newsgroup with announcements about new utilities or products related to Perl
- comp.lang.perl.misc
- The general-purpose newsgroup devoted to non-CGI-related Perl programming questions
- comp.lang.perl.moderated
- A moderated newsgroup intended to be a forum for more controlled, restrained discussions about Perl
- comp.lang.perl.modules
- A newsgroup devoted to using and developing Perl modules
- comp.lang.perl.tk
- A newsgroup concentrating on Perl/Tk, the graphical extension to Perl
- comp.infosystems.www.authoring.cgi
- A newsgroup for CGI questions in general, but mostly for Perl-related questions
At some point, it seems like every Perl programmer subscribes to comp.lang.perl.misc. You may eventually abandon it if the discussion becomes too detailed, too belligerent, or too bizarre for your taste. But you'll likely find yourself coming back from time to time, either to ask a question or just to check out the latest buzz.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 2: Installing Perl
- InhaltsvorschauSome of the best things in life are free. So is Perl. Although bundled Perl distributions are frequently available on CD-ROM, perhaps installed as a core part of your operating system, most people download Perl from an online archive. CPAN, the Comprehensive Perl Archive Network, is the main distribution point for all things Perl .Whether you are looking for Perl itself, for a module, or for documentation about Perl, CPAN (
http://www.cpan.org/) is the place to go. The ongoing development and enhancement of Perl is very much a cooperative effort, and CPAN is the place where the work of many individuals comes together.CPAN represents the development interests of a cross-section of the Perl community. It contains Perl utilities, modules, documentation, and (of course) the Perl distribution itself. CPAN was created by Jarkko Hietaniemi and Andreas König.The home for CPAN ishttp://www.cpan.org/, but CPAN is also mirrored on many other sites around the globe. This ensures that anyone with an Internet connection can have reliable access to CPAN's contents at any time. Since the structure of all CPAN sites is the same, a user searching for the current version of Perl can be sure that the stable.tar.gz file is the same on every site.If you want to use anonymous FTP, the following machines should have the Perl source code plus a copy of the CPAN mirror list:ftp.perl.com
ftp.cs.colorado.edu
ftp.cise.ufl.edu
ftp.funet.fi
ftp.cs.ruu.nlThe location of the top directory of the CPAN mirror differs on these machines, so look around once you get there. It's often something like /pub/perl/CPAN.CPAN materials are grouped into categories, including Perl modules, distributions, documentation, announcements, ports, scripts, and contributing authors. Each category is linked to related categories. For example, links to a graphing module written by an author appear in both the module and the author areas.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The CPAN Architecture
- InhaltsvorschauCPAN represents the development interests of a cross-section of the Perl community. It contains Perl utilities, modules, documentation, and (of course) the Perl distribution itself. CPAN was created by Jarkko Hietaniemi and Andreas König.The home for CPAN is
http://www.cpan.org/, but CPAN is also mirrored on many other sites around the globe. This ensures that anyone with an Internet connection can have reliable access to CPAN's contents at any time. Since the structure of all CPAN sites is the same, a user searching for the current version of Perl can be sure that the stable.tar.gz file is the same on every site.If you want to use anonymous FTP, the following machines should have the Perl source code plus a copy of the CPAN mirror list:ftp.perl.com
ftp.cs.colorado.edu
ftp.cise.ufl.edu
ftp.funet.fi
ftp.cs.ruu.nlThe location of the top directory of the CPAN mirror differs on these machines, so look around once you get there. It's often something like /pub/perl/CPAN.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - How Is CPAN Organized?
- InhaltsvorschauCPAN materials are grouped into categories, including Perl modules, distributions, documentation, announcements, ports, scripts, and contributing authors. Each category is linked to related categories. For example, links to a graphing module written by an author appear in both the module and the author areas.Since CPAN provides the same offerings worldwide, the directory structure has been standardized; files are located in the same place in the directory hierarchy at all CPAN sites. All CPAN sites use CPAN as the root directory, from which the user can select a specific Perl item. From the CPAN directory, you have the following choices:ItemDescriptionCPAN.htmlCPAN info page; some general information about CPANENDINGSDescription of the file extensions, such as .tar, .gz, and .zipMIRRORED BYA list of sites mirroring CPANMIRRORING.FROMA list of sites mirrored by CPANREADMEA brief description of what you'll find on CPANREADME.htmlAn HTML-formatted version of the README fileRECENTRecent additions to the CPAN siteRECENT.htmlAn HTML-formatted list of recent additionsROADMAPEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Installing Perl
- InhaltsvorschauMost likely, your system administrator is responsible for installing and upgrading Perl. But if you are the system administrator, or you want to install Perl on your own system, sooner or later you will find yourself installing a new version of Perl.If you run Perl and plan on upgrading to the latest distribution, be aware that pre-5.005 Perl extensions are not compatible with 5.6 and later. This means that you must rebuild and reinstall any dynamically loaded extensions you built under Perl distributions earlier than 5.005. If you're building under a Unix variant that's running Perl 5.005, choose the Configure option for 5.005 compatibility.Specific installation instructions come in the README and INSTALL files of the Perl distribution kit. If you don't already have the Perl distribution, you can download it from CPAN—the latest Unix distribution is in stable.tar.gz. The information in this section is an overview of the installation process. The gory details are in the INSTALL file, which you should look at before starting, especially if you haven't done an installation before. Note that operating systems other than Unix may have special instructions; if so, follow those instructions instead of what's in this section or in INSTALL. Look for a file named README.xxx, in which xxx represents your operating-system type.In addition to Perl itself, the standard distribution includes a set of core modules that are automatically installed with Perl. See Section 2.4 later in this chapter to learn how to install modules that are not bundled with Perl; Chapter 8 describes the standard modules in some detail.Typically, the Perl kit will be packed as either a tar file or a set of shar (shell archive) scripts; in either case, the file will be in a compressed format. If you got your version of Perl directly from CPAN, it is probably in "tar-gzipped" format; tar and gzip are popular Unix data-archiving formats. In any case, once you've downloaded the distribution, you need to uncompress and unpack it. The filename indicates the kind of compression that was used. AEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Getting and Installing Modules
- InhaltsvorschauAs you'll see when you look at the lists of modules and their authors on CPAN, many users have made their modules freely available. If you find an interesting problem and are thinking of writing a module to solve it, check the modules directory on CPAN first to see if there is a module there that you can use. The chances are good that there is a module that does what you need, or perhaps one that you can extend, rather than starting from scratch.Before you download a module, you might also check your system to see if it's already installed. The following command searches the libraries in the
@INCarray and prints the names of all modules it finds:find `perl -e 'print "@INC"'` -name '*.pm' -print
If you start from the modules directory on CPAN, you'll see that the modules are categorized into three subdirectories:by-authors Modules by author's registered CPAN name by-category Modules by subject matter (see below) by-module Modules by namespace (i.e., MIME)
If you know what module you want, you can go directly to it by clicking on the by-module entry. If you are looking for a module in a particular category, you can find it in the by-category subdirectory. If you know the author, click on by-author. However, if you aren't familiar with the categories and want to find a module that performs a certain task, you might want to get the file 00modlist.long.html, also in the modules directory. This file is the "Perl 5 Modules List." It contains a list of all the modules, by category, with a brief description of the purpose of each module and a link to the author's CPAN directory for downloading.Here is a list of the Perl Module categories, plus two for modules that don't fit anywhere else:02_Perl_Core_Modules 03_Development_Support 04_Operating_System_Interfaces 05_Networking_Devices_IPC 06_Data_Type_Utilities 07_Database_Interface 08_User_Interfaces 09_Language_Interfaces 10_File_Names_Systems_Locking 11_String_Lang_Text_Proc 12_Opt_Arg_Param_Proc 13_Internationalization_Locale 14_Security_and_Encryption 15_World_Wide_Web_HTML_HTTP_CGI 16_Server_and_Daemon_Utilities 17_Archiving_and_Compression 18_Images_Pixmaps_Bitmaps 19_Mail_and_Usenet_News 20_Control_Flow_Utilities 21_File_Handle_Input_Output 22_Microsoft_Windows_Modules 23_Miscellaneous_Modules 24_Commercial_Software_Interfaces 99_Not_In_Modulelist 99_Not_Yet_In_Modulelist
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Documentation
- InhaltsvorschauPerl documentation is written in a language known as pod (plain old documentation). Pod is a set of simple tags that can be processed to produce documentation in the style of Unix manpages. There are also several utility programs available that process pod text and generate output in different formats. Pod tags can be intermixed with Perl commands or can be saved in a separate file, which usually has a .pod extension. The pod tags and the utility programs that are included in the Perl distribution are described in Chapter 4.On Unix, the standard Perl installation procedure generates manpages for the Perl documentation from their pod format, although your system administrator might also choose to install the documentation as HTML files. You can also use this procedure to generate manpages for CPAN modules when you install them. You might need to modify your MANPATH environment variable to include the path to the Perl manpages, but then you should be able to read the documentation with the man command. In addition, Perl comes with its own command, perldoc, which formats the pod documentation and displays it. perldoc is particularly useful for reading module documentation, which might not be installed as manpages; you can also use it for reading the core Perl documentation.The ActiveState Win32 port comes with documentation in HTML format; you can find it in the /docs subdirectory of the distribution. Documentation specific to ActiveState's Perl for Win32 is installed in the /docs/Perl-Win32 subdirectory.Perl comes with lots of online documentation. To make life easier, the manpages are divided into separate sections so you don't have to wade through hundreds of pages of text to find what you are looking for. You can read them with either the man command or perldoc. Run
man perlorperldoc perlto read the top-level page. This page in turn directs you to more specific pages. Or, if you know which page you want, you can go directly there by using:% man perlvar
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 3: The Perl Executable
- InhaltsvorschauThe perl executable is normally installed in /usr/bin or /usr/local/bin on your machine. Some people often refer to perl as the Perl interpreter, but this isn't strictly correct, as you'll learn shortly.Every Perl program must be passed through the Perl executable to be executed. The first line in many Perl programs is something like:
#!/usr/bin/perl
For Unix systems, this#!(hash-bang or shebang) line tells the shell to look for the /usr/bin/perl program and pass the rest of the file to that /usr/bin/perl for execution. Sometimes, you'll see different pathnames to the Perl executable, such as /usr/local/bin/perl. You might see perl5 or perl6 instead of perl on sites that still depend on older versions of Perl.Often, you'll see command-line options tacked on the end of perl, such as the notorious -w switch, which produces warning messages. But almost all Perl programs on Unix start with some variation of#!/usr/bin/perl.If you get a mysterious "Command not found" error on a Perl program, it's often because the path to the Perl executable is wrong. When you download Perl programs off the Internet, copy them from one machine to another, or copy them out of a book (like this one!). The first thing you should do is make sure that the#!line points to the location of the Perl executable on your system. If you're on a Win32 platform, where the shebang path is used only to check for Perl switches, you should make sure that you run pl2bat.bat on the program so you can run it directly from the command line.So what does the Perl executable do? It compiles the program internally into a parse tree and executes it immediately. Because the program is not compiled and executed in separate steps, Perl is commonly known as an interpreted language, but this is not quite true.So do you call something a Perl "script" or a Perl "program"? Typically, the word "program" is used to describe something that needs to be compiled into assembler or bytecode before executing, as in the C language. The word "script" is used to describe something that runs through an executable on your system, such as the Bourne shell. For Perl, you can use either phrase and only offend those Perl programmers who care about semantics more than you do.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Command Processing
- InhaltsvorschauIn addition to specifying a
#!line, you can specify a short script directly on the command line. Here are some of the possible ways to run Perl:- Issue the perl command, writing your script line by line via -e switches on the command line:
perl -e 'print "Hello, world\n"' # Unix perl -e "print \"Hello, world\n\"" # Win32 or Unix perl -e "print qq[Hello, world\n]" # Also Win32
- Issue the perl command, passing Perl the name of your script as the first parameter (after any switches):
perl testpgm
- On Unix systems that support the
#!notation, specify the Perl command on the#!line, make your script executable, and invoke it from the shell (as described above). - Pass your script to Perl via standard input. For example, under Unix:
echo "print 'Hello, world'" | perl - % perl print "Hello, world\n"; ^D
- On Win32 systems, you can associate an extension (e.g., .plx) with a file type and double-click on the icon for a Perl script with that file type. Or, as mentioned earlier, do this:
(open a "DOS" window) C:\> (edit your Perl program in your favorite editor) C:\> pl2bat yourprog.plx C:\> .\yourprog.bat (program output here)
If you are using the ActiveState version of Win32 Perl, the installer normally prompts you to create the association. - On Win32 systems, if you double-click on the icon for the Perl executable, you'll find yourself in a command-prompt window with a blinking cursor. You can enter your Perl commands, indicating the end of your input with Ctrl-Z, and Perl will compile and execute your script.
Perl parses the input file from the beginning, unless you've specified the -x switch (see Section 3.2 later in this chapter). If there is a#!line, it is always examined for switches as the line is being parsed. Thus, switches behave consistently regardless of how Perl was invoked.After locating your script, Perl compiles the entire script into an internal form. If there are any compilation errors, execution of the script is not attempted. If the script is syntactically correct, it is executed. If the script runs off the end without hitting anEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Command-Line Options
- InhaltsvorschauPerl expects any command-line options, also known as switches or flags , to come first on the command line. The next item is usually the name of the script, followed by any additional arguments (often filenames) to be passed into the script. Some of these additional arguments may be switches, but if so, they must be processed by the script, since Perl gives up parsing switches as soon as it sees either a non-switch item or the special
--switch that terminates switch processing.A single-character switch with no argument may be combined (bundled) with the switch that follows it, if any. For example:#!/usr/bin/perl -spi.bak
is the same as:#!/usr/bin/perl -s -p -i.bak
Perl recognizes the switches listed in Table 3-1.Table 3-1: Perl switches SwitchFunction--Terminates switch processing, even if the next argument starts with a minus. It has no other effect.-0[octnum]Specifies the record separator ($/) as an octal number. If octnum is not present, the null character is the separator. Other switches may precede or follow the octal number.-aTurns on autosplit mode when used with -n or -p. An implicitsplitof the@Farray is inserted as the first command inside the implicitwhileloop produced by -n or -p. The default field delimiter is whitespace; a different field delimiter may be specified using -F.-cEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Environment Variables
- InhaltsvorschauEnvironment variables are used to set user preferences. Individual Perl modules or programs are always free to define their own environment variables, and there is also a set of special environment variables used in the CGI environment (see Chapter 9).Perl uses the following environment variables:
- HOME
- Used if
chdirhas no argument. - LOGDIR
- Used if
chdirhas no argument and HOME is not set. - PATH
- Used in executing subprocesses and in finding the script if -S is used.
- PATHEXT
- On Win32 systems, if you want to avoid typing the extension every time you execute a Perl script, you can set the PATHEXT environment variable so that it includes Perl scripts. For example:
C:\> set PATHEXT=%PATHEXT%;.PLX
This setting lets you type:C:\> myscript
without including the file extension. Be careful when setting PATHEXT permanently—it also includes executable file types such as .com, .exe, .bat, and .cmd. If you inadvertently lose those extensions, you'll have difficulty invoking applications and script files. - PERL5LIB
- A colon-separated list of directories in which to look for Perl library files before looking in the standard library and the current directory. If PERL5LIB is not defined, PERLLIB is used. When running taint checks, neither variable is used. The script should instead say:
use lib "/my/directory";
- PERL5OPT
- Command-line options (switches). Switches in this variable are taken as if they were on every Perl command line. Only the -[DIMUdmw] switches are allowed. When running taint checks, this variable is ignored.
- PERLLIB
- A colon-separated list of directories in which to look for Perl library files before looking in the standard library and the current directory. If PERL5LIB is defined, PERLLIB is not used.
- PERL5DB
- The command used to load the debugger code. The default is:
BEGIN { require 'perl5db.pl' } - PERL5SHELL
- On Win32 systems, may be set to an alternative shell for Perl to use internally to execute "backtick" commands or the
systemfunction. - PERL_DEBUG_MSTATS
- Relevant only if your Perl executable was built with -DDEBUGGING_MSTATS. If set, causes memory statistics to be dumped after execution. If set to an integer greater than 1, it also causes memory statistics to be dumped after compilation.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The Perl Compiler
- InhaltsvorschauStarting with Perl 5.005, the Perl compiler became part of the standard Perl distribution. You'll find that with Perl 5.6 and later, the Perl compiler has become far more stable. The compiler allows you to distribute Perl programs in binary form, which enables easy packaging of Perl-based programs without relying on the source machine to have the correct version of Perl and the correct modules installed. After the initial compilation, running a compiled program should be faster because it doesn't have to be recompiled each time it's run. However, you shouldn't expect that the compiled code itself will run faster than the original Perl source or that the executable will be smaller—in reality, the executable file is likely to be significantly bigger.This initial release of the compiler is still considered to be a beta version. It's distributed as an extension module, B, that comes with the following backends:
- Bytecode
- Translates a script into platform-independent Perl bytecode.
- C
- Translates a Perl script into C code.
- CC
- Translates a Perl script into optimized C code.
- Deparse
- Regenerates Perl source code from a compiled program.
- Lint
- Extends the Perl -w option. Named after the Unix Lint program-checker.
- Showlex
- Shows lexical variables used in functions or files.
- Xref
- Creates a cross-reference listing for a program.
Once you've generated the C code with either the C or the CC backend, you run the cc_harness program to compile it into an executable. There is also a byteperl interpreter that lets you run the code you've generated with the Bytecode backend.Here's an example that takes a simple "Hello world" program and uses the CC backend to generate C code:% perl -MO=CC,-ohi.c hi.pl hi.pl syntax OK % perl cc_harness -O2 -ohi hi.c # You may have to provide the full path of where cc_harness lives gcc -B/usr/ccs/bin/ -D_REENTRANT -DDEBUGGING -I/usr/local/include -I/usr/local/lib/perl5/sun4-solaris-thread/5.00466/CORE -O2 -ohi hi.c -L/usr/local/lib /usr/local/lib/perl5/sun4-solaris-thread/5.00466/CORE/libperl.a -lsocket -lnsl -lgdbm -ldl -lm -lposix4 -lpthread -lc -lcrypt % hi Hi there, world!
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Threads
- InhaltsvorschauPerl 5.6 and later also include native multithreading capability, which is distributed with Perl as a set of modules. The threads modules have improved since the 5.005 release, but should still be considered an experimental feature and aren't automatically compiled in with Perl.Pay close attention to Configure when you build Perl so that you don't include threads support if you don't want it.You might want to build a separate version of Perl with threads enabled, if you'd like to test the threads feature under your platform.Chapter 8 describes the individual thread modules. For information on using threads, refer to the perlthrtut manpage (included with more recent distributions of Perl).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 4: The Perl Language
- InhaltsvorschauThis chapter is a quick and merciless guide to the Perl language itself. If you're trying to learn Perl from scratch and would prefer to be taught rather than to have things thrown at you, then you might be better off with Learning Perl, 3rd Edition by Randal L. Schwartz and Tom Phoenix. However, if you already know some other programming languages and just want to learn the particulars of Perl, this chapter is for you. Sit tight, and forgive us for being terse—we have a lot of ground to cover.If you want a more complete discussion of the Perl language and its idiosyncrasies (and we mean complete), see Programming Perl, 3rd Edition by Larry Wall, Tom Christiansen, and Jon Orwant.Perl is a particularly forgiving language, as far as program layout goes. There are no rules about indentation, newlines, etc. Most lines end with semicolons, but not everything has to. Most things don't have to be declared, except for a couple of things that do. Here are the bare essentials:
- Whitespace
- Whitespace is required only between items that would otherwise be confused as a single term. All types of whitespace—spaces, tabs, newlines, etc.—are equivalent in this context. A comment counts as whitespace. Different types of whitespace are distinguishable within quoted strings, formats, and certain line-oriented forms of quoting. For example, in a quoted string, a newline, a space, and a tab are interpreted as unique characters.
- Semicolons
- Every simple statement must end with a semicolon. Compound statements contain brace-delimited blocks of other statements and do not require terminating semicolons after the ending brace. A final simple statement in a block also does not require a semicolon.
- Declarations
- Only subroutines and report formats need to be explicitly declared. All other user-created objects are automatically created with a null or 0 value unless they are defined by some explicit operation such as assignment. The
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Program Structure
- InhaltsvorschauPerl is a particularly forgiving language, as far as program layout goes. There are no rules about indentation, newlines, etc. Most lines end with semicolons, but not everything has to. Most things don't have to be declared, except for a couple of things that do. Here are the bare essentials:
- Whitespace
- Whitespace is required only between items that would otherwise be confused as a single term. All types of whitespace—spaces, tabs, newlines, etc.—are equivalent in this context. A comment counts as whitespace. Different types of whitespace are distinguishable within quoted strings, formats, and certain line-oriented forms of quoting. For example, in a quoted string, a newline, a space, and a tab are interpreted as unique characters.
- Semicolons
- Every simple statement must end with a semicolon. Compound statements contain brace-delimited blocks of other statements and do not require terminating semicolons after the ending brace. A final simple statement in a block also does not require a semicolon.
- Declarations
- Only subroutines and report formats need to be explicitly declared. All other user-created objects are automatically created with a null or 0 value unless they are defined by some explicit operation such as assignment. The -w command-line switch will warn you about using undefined values.You may force yourself to declare your variables by including the
use strictpragma in your programs (see Chapter 8 for more information on pragmas andstrictin particular). This causes an error if you do not explicitly declare your variables. - Comments and documentation
- Comments within a program are indicated by a pound sign (
#). Everything following a pound sign to the end of the line is interpreted as a comment.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Data Types and Variables
- InhaltsvorschauPerl has three basic data types: scalars, arrays, and hashes.Scalars are essentially simple variables. They are preceded by a dollar sign (
$). A scalar is either a number, a string, or a reference. (A reference is a scalar that points to another piece of data. References are discussed later in this chapter.) If you provide a string in which a number is expected or vice versa, Perl automatically converts the operand using fairly intuitive rules.Arrays are ordered lists of scalars accessed with a numeric subscript (subscripts start at 0). They are preceded by an "at" sign (@).Hashes are unordered sets of key/value pairs accessed with the keys as subscripts. They are preceded by a percent sign (%).Perl stores numbers internally as either signed integers or double-precision, floating-point values. Numeric literals are specified by any of the following floating-point or integer formats:-
12345 - Integer
-
-54321 - Negative integer
-
12345.67 - Floating point
-
6.02E23 - Scientific notation
-
0xffff - Hexadecimal
-
0377 - Octal
-
4_294_967_296 - Underline for legibility
Since Perl uses the comma as a list separator, you cannot use a comma for improving the legibility of a large number. To improve legibility, Perl allows you to use an underscore character instead. The underscore works only within literal numbers specified in your program, not in strings functioning as numbers or in data read from somewhere else. Similarly, the leading0xfor hex and0for octal work only for literals. The automatic conversion of a string to a number does not recognize these prefixes—you must do an explicit conversion.Be aware that in Perl 5.8, there are many changes in how Perl deals with integers and floating-point numbers. Regardless of how your system handles numbers and conversion between characters and numbers, Perl 5.8 works around system deficiencies to force more accurate number handling. Furthermore, whereas prior to 5.8 Perl used floating-point numbers exclusively in math operations, Perl 5.8 now uses and stores integers in numeric conversions and in arithmetic operations.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Statements
- InhaltsvorschauA simple statement is an expression evaluated for its side effects. Every simple statement must end in a semicolon, unless it is the final statement in a block.A sequence of statements that defines a scope is called a block. Generally, a block is delimited by braces, or
{ }. Compound statements are built out of expressions and blocks. A conditional expression is evaluated to determine whether a statement block will be executed. Compound statements are defined in terms of blocks, not statements, which means that braces are required.Any block can be given a label. Labels are identifiers that follow the variable-naming rules (i.e., they begin with a letter or underscore and can contain alphanumerics and underscores). They are placed just before the block and are followed by a colon, such asSOMELABELhere:SOMELABEL: { ...statements... }By convention, labels are all uppercase, so as not to conflict with reserved words. Labels are used with the loop control commandsnext,last, andredoto alter the flow of execution in your programs.Theifandunlessstatements execute blocks of code depending on whether a condition is met. These statements take the following forms:if (expression) {block} else {block} unless (expression) {block} else {block} if (expression1) {block} elsif (expression2) {block} ... elsif (lastexpression) {block} else {block}
Section 4.3.1.1: while loops
Thewhilestatement repeatedly executes a block as long as its conditional expression is true. For example:while (<INFILE>) { chomp; print OUTFILE, "$_\n"; }This loop reads each line from the file opened with the filehandle INFILE and prints them to the OUTFILE filehandle. The loop will cease when it encounters an end-of-file.If the wordwhileis replaced by the worduntil, the sense of the test is reversed. The conditional is still tested before the first iteration, though.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Special Variables
- InhaltsvorschauSome variables have a predefined, special meaning in Perl. They use punctuation characters after the usual variable indicator (
$,@, or%), such as$_. The explicit, long-form names are the variables' equivalents when you use the English module by includinguse English;at the top of your program.The most common special variable is$_, which contains the default input and pattern-searching string. For example:foreach ('hickory','dickory','doc') { print; }The first time the loop is executed, "hickory" is printed. The second time around, "dickory" is printed, and the third time, "doc" is printed. That's because in each iteration of the loop, the current string is placed in$_and is used by default byprint. Here are the places where Perl will assume$_, even if you don't specify it:- Various unary functions, including functions such as
ordandint, as well as the all file tests (-f,-d), except for-t, which defaults toSTDIN. - Various list functions such as
printandunlink. - The pattern-matching operations
m//,s///, andtr///when used without an=~operator. - The default iterator variable in a
foreachloop if no other variable is supplied. - The implicit iterator variable in the
grepandmapfunctions. - The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a
whiletest (i.e.,<filehandle>). Note that outside of awhiletest, this does not happen.
The following is a complete listing of global special variables:-
$_ -
$ARG - The default input and pattern-searching space.
-
$. -
$INPUT_LINE_NUMBER -
$NR - The current input line number of the last filehandle that was read. An explicit close on the filehandle resets the line number.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Operators
- InhaltsvorschauTable 4-3 lists all the Perl operators from highest to lowest precedence and indicates their associativity.
Table 4-3: Perl associativity and operators, listed by precedence AssociativityOperatorsLeftTerms and list operators (leftward)Left->(method call, dereference)Nonassociative++ --(autoincrement, autodecrement)Right**(exponentiation)Right! ~ \and unary+and-(logical not, bit-not, reference, unary plus, unary minus)Left=~ !~(matches, doesn't match)Left* / % x(multiply, divide, modulus, string replicate)Left+ -. (addition, subtraction, string concatenation)Left<< >>(left bit-shift, right bit-shift)NonassociativeEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Regular Expressions
- InhaltsvorschauRegular expressions are used several ways in Perl. They're used in conditionals to determine whether a string matches a particular pattern. They're also used to find patterns in strings and replace the match with something else.The ordinary pattern match operator looks like
/pattern/. It matches against the$_variable by default. If the pattern is found in the string, the operator returns true (1); if there is no match, a false value ("") is returned.The substitution operator looks likes/pattern/replace/. This operator searches$_by default. If it finds the specified pattern, it is replaced with the string in replace. If pattern is not matched, nothing happens.You may specify a variable other than$_with the=~binding operator (or the negated!~binding operator, which returns true if the pattern is not matched). For example:$text =~ /sampo/;
The following list defines Perl's pattern-matching operators. Some of the operators have alternative "quoting" schemes and have a set of modifiers that can be placed directly after the operators to affect the match operation in some way.-
m/pattern/gimosxe - Searches a string for a pattern match. Modifiers are :ModifierMeaning
gMatch globally, i.e., find all occurrences.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Subroutines
- InhaltsvorschauSubroutines are declared using one of these forms:
sub name {block} sub name (proto) {block}
Prototypes allow you to put constraints on the arguments you provide to your subroutines.You can also create anonymous subroutines at runtime, which will be available for use through a reference:$subref = sub {block};
The ampersand (&) is the identifier used to call subroutines. Most of the time, however, subroutines can be used in an expression just like built-in functions. To call subroutines directly:name(args); # & is optional with parentheses name args; # Parens optional if predeclared/imported &name; # Passes current @_ to subroutineTo call subroutines indirectly (by name or by reference):&$subref(args); # & is not optional on indirect call &$subref; # Passes current @_ to subroutineAll arguments to a subroutine are passed as a single, flat list of scalars, and return values are returned the same way. Any arrays or hashes passed in these lists will have their values interpolated into the flattened list.Any arguments passed to a subroutine come in as the array@_.You may use the explicitreturnstatement to return a value and leave the subroutine at any point.If you want to pass more than one array or hash into or out of a function and maintain their integrity, you should pass references as arguments. The simplest way to do this is to take your named variables and put a backslash in front of them in the argument list:@returnlist = ref_conversion(\@temps1, \@temps2, \@temps3);
This sends references to the three arrays to the subroutine (and saves you the step of creating your own named references to send to the function). The references to the arrays are passed to the subroutine as the three-member@_array. The subroutine will have to dereference the arguments so that the data values may be used.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - References and Complex Data Structures
- InhaltsvorschauA Perl reference is a fundamental data type that "points" to another piece of data or code. A reference knows the location of the information and the type of data stored there.A reference is a scalar and can be used anywhere a scalar can be used. Any array element or hash value can contain a reference (a hash key cannot contain a reference), which is how nested data structures are built in Perl. You can construct lists containing references to other lists, which can contain references to hashes, and so on.You can create a reference to an existing variable or subroutine by prefixing it with a backslash:
$a = "fondue"; @alist = ("pitt", "hanks", "cage", "cruise"); %song = ("mother" => "crying", "brother" => "dying"); sub freaky_friday { s/mother/daughter/ } # Create references $ra = \$a; $ralist = \@alist; $rsong = \%song; $rsub = \&freaky_friday; # '&' required for subroutine namesReferences to scalar constants are created similarly:$pi = \3.14159; $myname = \"Charlie";
Note that all references are prefixed by a$, even if they refer to an array or hash. All references are scalars; thus, you can copy a reference to another scalar or even reference another reference:$aref = \@names; $bref = $aref; # Both refer to @names $cref = \$aref; # $cref is a reference to $aref
Because arrays and hashes are collections of scalars, you can create references to individual elements by prefixing their names with backslashes:$star = \$alist[2]; # Refers to third element of @alist $action = \$song{mother}; # Refers to the 'mother' value of %songSection 4.8.1.1: Referencing anonymous data
It is also possible to take references to literal data not stored in a variable. This data is called anonymous because it is not bound to any named variable.To create a reference to a scalar constant, simply backslash the literal string or number.To create a reference to an anonymous array, place the list of values in square brackets:$shortbread = [ "flour", "butter", "eggs", "sugar" ];
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Filehandles
- InhaltsvorschauA filehandle is the name for an I/O connection between your Perl process and the operating system. Filehandle names are like label names but use their own namespace. Like label names, the convention is to use all uppercase letters for filehandle names.Every Perl program has three filehandles that are automatically opened: STDIN, STDOUT, and STDERR. By default, the
printandwritefunctions write to STDOUT. Additional filehandles are created using theopenfunction:open (DATA, "numbers.txt");
DATA is the new filehandle that is attached to the external file, which is now opened for reading. You can open filehandles for reading, writing, and appending to external files and devices. To open a file for writing, prefix the filename with a greater-than sign:open(OUT, ">outfile");
To open a file for appending, prefix the filename with two greater-than signs:open(LOGFILE, ">>error_log");
Theopenfunction returns true if the file is successfully opened, and false if it failed to open. Opening a file can fail for any number of reasons, e.g., a file does not exist, is write-protected, or you don't have permission for a file or directory. However, a filehandle that has not been successfully opened can still be read from (giving you an immediate EOF) or written to with no noticeable effects.You should always check the result ofopenimmediately and report an error if the operation does not succeed. Thewarnfunction can report an error to standard error if something goes wrong, anddiecan terminate your program and tell you what went wrong. For example:open(LOGFILE, "/usr/httpd/error_log") || warn "Could not open /usr/httpd/error_log.\n"; open(DATA, ">/tmp/data") || die "Could not create /tmp/data\n.";Once the file is opened, you can access the data using the diamond operator,<filehandle>. This is the line-input operator. When used on a filehandle in a scalar context, it returns a line from a filehandle as a string. Each time it is called, it returns the next line from the filehandle until it reaches the end-of-file. The operator keeps track of the line it is on in the file, unless the filehandle is closed and reopened, which resets the operator to the top-of-file.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Signals
- InhaltsvorschauPerl supports many facilities for Interprocess Communication (IPC), including signals and sockets. Regardless of which IPC form you use with Perl, you'll almost always tangle with signals.Signals can be generated from any source, including key sequences on your keyboard, an event on your system, or from a failed program.For quite some time, Perl has used a simple signal handling module, in which
%SIGwas populated with keys that represented the signal handlers your system supported. You'd invoke one of these handlers when Perl came across$SIG{'whatever_signal_here'}. In fact, even in Perl 5.8, the%SIGinterface is the same, but the behavior of signals is entirely different. More on this shortly.For signals to be useful, they must be trapped and dealt with. However, you shouldn't try to do too much when you trap a signal. Generally, you should only generate a warning and deal with the condition that caused the error. In a way, Perl's%SIGkeeps you from doing too much.%SIGworks like this:$SIG{I_GOT_THIS_SIGNAL} = \&now_call_this_sub_to_handle_it; sub now_call_this_sub_to_handle it { ... }If you need to know which signals Perl is aware of, do a'kill -l'on a Unix system, or use Config.pm:#!/usr/local/bin/perl -w use Config; print "Perl knows about the following signals:\n"; print $Config{sig_name_init}, "\n";Here's a simple snippet that lets you know if someone sent you aHUPsignal:$SIG{HUP} = \&hic_hup; sub hic_hup { my $signal = shift; # Don't die for now. Just warn us. warn "Somebody sent me a SIG${signal}\n"; }Often, the type of signal you encounter in your Perl program will dictate how you should handle it. For example, you should assign'IGNORE'to the'CHLD'signal on many Unix platforms to reduce the possibility of creating zombie processes. Other signals, such asKILLandSTOP, cannot and should not be ignored so easily. For this purpose, Perl lets you use alocal( )statement, which lets you temporarily ignore a signal:sub kill_handler { local $SIG{KILL} = 'IGNORE'; # Inherited by all functions here i_will_settle_for_denial(); } sub i_will_settle_for_denial { # KILL ignored for now. Go in peace. }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Unicode
- InhaltsvorschauUnicode provides a unique number for every character, regardless of the computing platform, program, or programming language. This is particularly important because without a standard such as Unicode, computers would continue to use different encoding classes for characters, many of which would conflict if character classes were used together.Unicode support was introduced to Perl with Perl 5.6. Although it is still not completely adherent in the Unicode spec, Unicode support has matured significantly under Perl 5.8. You can now use Unicode reliably with file I/O and with regular expressions. With regular expressions, the pattern will adapt to the data and will automatically switch to the correct Unicode character scheme.Perl's Unicode implementation falls into the following categories:
- I/O
- There is currently no way in Perl to mark data that's read from or written to a file as being of type Unicode (utf8). Future versions of Perl will support such a feature.
- Regular expressions
- The determination whether to match Unicode characters is made when the pattern is compiled, based on whether the pattern contains Unicode characters and not when matching happens at runtime. This will be changed to match Unicode characters at runtime.
-
use utf8 - The utf8 module is still needed to enable a few Unicode features. The
utf8pragma, as implemented by the utf8 module, implements tables used for Unicode support. You must load theutf8pragma explicitly to enable recognition of UTF-8 encoded literals and identifiers in the source text. - Byte and character semantics
- As of 5.6.0, Perl uses logically wide characters to represent strings internally. This internal representation uses the UTF-8 encoding. Future versions of Perl will work with characters rather than bytes. This was a purposeful decision made so Perl 5.6 could transition from byte semantics to character semantics in programs. Perl will make the decision to switch to character semantics if it finds that the input data has characters on which it can safely operate with UTF-8. You can disable character semantics by using the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Formats
- InhaltsvorschauFormats are a mechanism for generating formatted reports for outputting data and are defined with the
formatkeyword. The general form looks like:format name = ...template lines... ...argument line... .
Most of your format names will be the same as the filehandle names for which they are used. The default format for a filehandle is the one with the same name.The format definition is like a subroutine definition. It doesn't contain immediately executed code and can therefore be placed anywhere in the file with the rest of the program; they are commonly placed near the end of the file with subroutine definitions. To output to a format, use thewritefunction instead ofprint.The template lines contain literal text and fieldholders. Fieldholders contain symbols that describe the size and positioning of the area on the line where data is output. An argument line immediately follows a template line that contains the fields to be replaced by data. The argument line is a list of variables (or expressions), separated by commas, that fill the fields in the previous line in the order they are listed.Here's an example of a template line with two fieldholders and the argument line that follows:Hello, my name is @<<<<<<<<<< and I'm @<< years old. $name, $age
The fieldholders are@<<<<<<<<<<and@<<, which specify left-justified text fields with 11 and 3 characters, respectively.Most fieldholders start with@. The characters following@indicate the type of field, while the number of characters (including@) indicate the field width. The following fieldholder characters determine the positioning of text fields:-
<<<<(left angle brackets) - A left-justified field; if the value is shorter than the field width, it will be padded on the right with spaces.
-
>>>>(right angle brackets) - A right-justified field; if the value is too short, it will be padded on the left with spaces.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Pod
- InhaltsvorschauPod is a simple, but surprisingly capable, text formatter that uses tags to tell a translator how to format the text. The tags serve several purposes:
- They tell the formatter how to lay out text on the page.
- They provide font and cross-reference information.
- They start and stop parsing of code.
The last item is indicative of one of pod's most useful features—that it can be intermixed with Perl code. While it can be difficult to force yourself to go back and write documentation for your code after the fact, with Perl you can simply intermingle the documentation with the code, and do it all at once. It also lets you use the same text as both code documentation and user documentation.A pod translator reads a file paragraph by paragraph, ignoring text that isn't pod, and converting it to the proper format. Paragraphs are separated by blank lines (not just by newlines). The various translators recognize three kinds of paragraphs:- Command
- Commands begin with
=, followed immediately by the command identifier:=cut
They can also be followed by text:=head2 Second-level headA blank line signals the end of the command. - Text
- A paragraph consisting of a block of text, generally filled and possibly justified, depending on the translator. For example, a command such as
=head2will probably be followed with a text paragraph:=head2 Pod Pod is a simple, but surprisingly capable, text formatter that uses tags to tell a translator how to format the text.
- Verbatim
- A paragraph that is to be reproduced as is, with no filling or justification. To create a verbatim paragraph, indent each line of text with at least one space:
Don't fill this paragraph. It's supposed to look exactly like this on the page. There are blanks at the beginning of each line.
The following paragraph tags are recognized as valid pod commands.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 5: Function Reference
- InhaltsvorschauThis chapter gives a brief description of Perl's built-in functions. Each description gives the syntax of the function, with the types and order of its arguments .Required arguments are shown in italics, separated by commas. If an argument must be a specific variable type, that variable's identifier will be used (e.g., a percent sign for a hash,
%hash). Optional arguments are placed in brackets. Do not use the brackets in function calls unless you really want to use an anonymous hash reference.There are different ways to use a built-in function. For starters, any argument that requires a scalar value can be made up of any expression that returns one. For example, you can obtain the square root of the first value in an array:$root = sqrt (shift @numbers);
shiftremoves the first element of@numbersand returns it to be used bysqrt.Many functions take a list of scalars for arguments. Any array variable or other expression that returns a list can be used for all or part of the arguments. For example:chmod (split /,/ FILELIST>); # An expression returns a list chmod 0755, @executables; # Array used for part of arguments
In the first line, thesplitexpression reads a string from a filehandle and splits it into a list. The list provides proper arguments forchmod. The second line uses an array that contains a list of filenames forchmodto act upon.Parentheses are not required around a function's arguments. However, without parentheses, functions are viewed as operators in an expression (the same is true of predeclared subroutines). If you use a function in a complex expression, you may want to use parentheses for clarity. See Chapter 4 for more about precedence in Perl expressions.Here are Perl's functions and function-like keywords, arranged by category. Note that some functions appear in more than one category.- Scalar manipulation
chomp,chop,chr,crypt,hex,index,lc,lcfirst
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Perl Functions by Category
- InhaltsvorschauHere are Perl's functions and function-like keywords, arranged by category. Note that some functions appear in more than one category.
- Scalar manipulation
chomp,chop,chr,crypt,hex,index,lc,lcfirst,length,oct,ord,pack,q//,qq//,reverse,rindex,sprintf,substr,tr///,uc,ucfirst,y///- Regular expressions and pattern matching
m//,pos,qr//,quotemeta,s///,split,study- Numeric functions
abs,atan2,cos,exp,hex,int,log,oct,rand,sin,sqrt,srand- Array processing
pop,push,shift,splice,unshift- List processing
grep,join,map,qw//,reverse,sort,unpack- Hash processing
delete,each,exists,keys,values- Input and output
binmode,close,closedir,dbmclose,dbmopen,die,eof,fileno,flock,format,getc,print,printf,read,readdir,rewinddir,seek,seekdir,select,syscall,sysread,sysseek,syswrite,tell,telldir,truncate,warn,write- Fixed-length data and records
pack,read,syscall,sysread,syswrite,unpack,vec- Filehandles, files, and directories
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - abs
- Inhaltsvorschauabsabs valueReturns the absolute value of its argument (or
$_if omitted).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - accept
- Inhaltsvorschauacceptaccept newsocket, genericsocketReadies a server process to accept socket connections from clients. Execution is suspended until a connection is made, at which time the newsocket filehandle is opened and attached to the newly made connection. The function returns the connected address if the call succeeds or false otherwise (and it puts the error code into
$!). genericsocket must be a filehandle already opened via thesocketfunction and bound to one of the server's network addresses.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - alarm
- Inhaltsvorschaualarmalarm nSends a
SIGALRMsignal to the executing Perl program after n seconds. On some older systems, alarms go off "at the top of the second," so, for instance, analarm 1may go off anywhere between 0 to 1 seconds from now, depending on when in the current second it is. Analarm 2may go off anywhere from 1 to 2 seconds from now. And so on.Each call disables the previous timer, and an argument of0may be supplied to cancel the previous timer without starting a new one. The return value is the number of seconds remaining on the previous timer.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - atan2
- Inhaltsvorschauatan2atan2 y, xReturns the arctangent of y
/xin the range -π to π. A quick way to get an approximate value of π is to say:$pi = atan2(1,1) * 4;
For the tangent operation, you may use thePOSIX::tan( )function, or use the familiar relation:sub tan { sin($_[0]) / cos($_[0]) }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - bind
- Inhaltsvorschaubindbind socket, addressAttaches an address to an already opened socket specified by the socket filehandle. The function returns true for success, false otherwise (and puts the error code into
$!). address should be a packed address of the proper type for the socket.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - binmode
- Inhaltsvorschaubinmodebinmode filehandleArranges for the file to be treated in binary mode on operating systems that distinguish between binary and text files. It should be called after
openbut before any I/O is done on the filehandle. The only way to reset binary mode on a filehandle is to reopen the file.binmodehas no effect under Unix, Plan9, or other systems that use a single\n(newline) character as a line delimiter. On systems such as Win32 or MS-DOS,binmodeis needed to prevent the translation of the line delimiter characters to and from\n.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - bless
- Inhaltsvorschaublessbless $ref, [classname]Looks up the item pointed to by reference ref and tells the item that it is now an object in the classname package—or the current package if no class name is specified. It returns the reference for convenience, since a
blessis often the last thing in a constructor function. (Always use the two-argument version if the constructor doing the blessing might be inherited by a derived class. In such cases, the class you want to bless your object into will normally be found as the first argument to the constructor in question.)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - caller
- Inhaltsvorschaucallercaller [n]Returns information about the stack of current subroutine calls. Without an argument, it returns the package name in a scalar context; in a list context, it returns the package name, filename, and line number from which the currently executing subroutine was called:
($package, $filename, $line) = caller;
With an argument it evaluates n as the number of stack frames to go back before the current one. It also reports some additional information that the debugger uses to print a stack trace:$i = 0; while (($pack, $file, $line, $subname, $hasargs, $wantarray, $evaltext, $is_require) = caller($i++)) { ... }Furthermore, when called from within the DB package,callerreturns more detailed information: it sets the list variable@DB::argsas the argument passed in the given stack frame.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - chdir
- Inhaltsvorschauchdirchdir dirnameChanges the working directory to dirname, if possible. If dirname is omitted, it changes to the home directory. The function returns
1upon success,0otherwise (and puts the error code into$!).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - chmod
- Inhaltsvorschauchmodchmod mode, filelistChanges the permissions of a list of files. The first argument must be the permissions mode given in its octal number representation. The function returns the number of files successfully changed. For example:
$cnt = chmod 0755, 'file1', 'file2';
will set$cntto0,1, or2, depending on how many files got changed (in the sense that the operation succeeded, not in the sense that the bits were different afterward).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - chomp
- Inhaltsvorschauchompchomp $var chomp @listRemoves any line-ending characters of a string in
$var, or each string in@list, that correspond to the current value of$/(not just any last character, aschopdoes).chompreturns the number of characters deleted. If$/is empty (in paragraph mode),chompremoves all newlines from the selected string (or strings, ifchomping a list). If no argument is given, the functionchomps the$_variable.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - chop
- Inhaltsvorschauchopchop $var chop @listChops off the last character of a string contained in the variable
$var (or strings in each element of a@list) and returns the character chopped. Thechopoperator is used primarily to remove the newline from the end of an input record but is more efficient thans/\n$//. If no argument is given, the function chops the$_variable.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - chown
- Inhaltsvorschauchownchown uid, gid, filesChanges the owner and group of a list of files. The first two arguments must be the numerical uid and gid, in that order. The function returns the number of files successfully changed.On most systems, you are not allowed to change the ownership of the file unless you're the superuser, although you should be able to change the group to any of your secondary groups. On insecure systems, these restrictions may be relaxed, but this is not a portable assumption.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- chr
- Inhaltsvorschauchrchr numberReturns the character represented by number in the character set. For example,
chr(65)is "A" in ASCII.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - chroot
- Inhaltsvorschauchrootchroot dirnameChanges the root directory for the current process to dirname—the starting point for pathnames beginning with
/. This directory is inherited acrossexeccalls and by all subprocesses. There is no way to undo achroot. Only the superuser can use this function.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - close
- Inhaltsvorschaucloseclose filehandleCloses the file, socket, or pipe associated with the given filehandle. You don't have to close filehandle if you are immediately going to do another
openon it, since the nextopenwill close it for you. However, an explicitcloseon an input file resets the line counter ($.), while the implicitclosedone byopendoes not. Closing a pipe will wait for the process executing on the pipe to complete and will prevent the script from exiting before the pipeline is finished. Also, closing a pipe explicitly puts the status value of the command executing on the pipe into$?.filehandle may be an expression with a value that gives a real filehandle name. It may also be a reference to a filehandle object returned by some of the object-oriented I/O packages.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - closedir
- Inhaltsvorschauclosedirclosedir dirhandleCloses a directory associated with the given directory handle opened by
opendir.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - connect
- Inhaltsvorschauconnectconnect socket, addressInitiates a connection with another process that is waiting at an
accepton the filehandle socket. The function returns true for success, false otherwise (and puts the error code into$!). address is a packed network address of the proper type for socket.To disconnect a socket, use eithercloseorshutdown.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - cos
- Inhaltsvorschaucoscos numReturns the cosine of num (expressed in radians). For the inverse cosine operation, you may use the
POSIX::acos( )function, or use this relation:sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - crypt
- Inhaltsvorschaucryptcrypt string, saltUsed by the
passwdfunction on Unix systems to produce a unique 13-character string (stored in the system's password file) from the first 8 characters of the given string and the 2-character salt. The Perl function operates the same way and returns a 13-character string with the first 2 characters as the salt.cryptuses a modified version of the Data Encryption Standard, which produces a one-way encryption; the resulting string cannot be decrypted to determine the original string.cryptcan be used to check that a password is correct by comparing the string from the function to the string found in /etc/passwd (if you have permission to do this):if (crypt ($guess, $pass) eq $pass) { # guess is correct }The variable$passis the password string from the password file.cryptmerely uses the first two characters from this string for the saltargument.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - dbmclose
- Inhaltsvorschaudbmclosedbmclose %hashBreaks the binding between a DBM file and a hash.This function is actually just a call to
untiewith the proper arguments, but is provided for backward compatibility with older versions of Perl.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - dbmopen
- Inhaltsvorschaudbmopendbmopen %hash, dbname, modeBinds a DBM file (dbname) to a hash (%hash). dbnameis the name of the database without the .dir or .pag extension. Note that while not deprecated,
dbmopenhas basically been superseded bytie( ). If the database does not exist, and a valid mode is specified, the database is created with the permissions specified by mode (as modified by the umask). To prevent creation of the database if it doesn't exist, you may specify a mode ofundef, and the function will return a false value if it can't find an existing database. If your system supports only the older DBM functions, you may have only onedbmopenin your program.Values assigned to the hash prior to thedbmopenare not accessible. If you don't have write access to the DBM file, you can only read the hash variables, not set them.This function is actually just a call totiewith the proper arguments, but is provided for backward compatibility with older versions of Perl.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - defined
- Inhaltsvorschaudefineddefined exprReturns a Boolean value saying whether the scalar value resulting from expr has a real value. If no argument is given,
definedchecks$_.A scalar that contains no valid string, numeric, or reference value is known as the undefined value, orundef. Many operations return the undefined value under exceptional conditions, such as end-of-file, uninitialized variable, system error, and so on. This function allows you to distinguish between an undefined null string and a defined null string when you're using operators that might return a real null string.You can usedefinedto see if a subroutine exists, that is, if the subroutine definition has been successfully parsed. However, usingdefinedon an array or a hash is not guaranteed to produce intuitive results and should be avoided.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - delete
- Inhaltsvorschaudeletedelete $hash{key} delete @hash{@keys}Deletes the specified key or keys and associated values from the specified hash. (It doesn't delete a file. See unlink for that.) Deleting from
$ENV{}modifies the environment. Deleting from a hash that is bound to a (writable) DBM file deletes the entry from the DBM file.For normal hashes, thedeletefunction returns the value (not the key) that was deleted, but this behavior is not guaranteed for tied hashes, such as those bound to DBM files. To test whether a hash element has been deleted, useexists.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - die
- Inhaltsvorschaudiedie messagePrints message to the standard error output and exits the Perl program with a nonzero exit status. message can be a list value, like the arguments to
print, from which the elements are concatenated into a single string for output. If message does not end with a newline (\n), the current script filename, line number, and input line number (if any) are appended to the message with a newline. With no argument, the function outputs the stringDiedas its default.dieexits the programs with the current value of the$!variable, which contains the text describing the most recent operating system error value. This value can be used in the message to describe what the problem may have been.diebehaves differently inside anevalstatement. It places the error message in the$@variable and aborts theeval, which returns an undefined value. This use ofdiecan raise runtime exceptions that can be caught at a higher level of the program.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - do
- Inhaltsvorschaudodo {block}Executes the sequence of commands in the block and returns the value of the last expression evaluated. When modified by a loop modifier, Perl executes the blockonce before testing the loop condition. (On other statements, the loop modifiers test the conditional first.)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- dump
- Inhaltsvorschaudumpdump labelDuring program execution, causes an immediate core dump after code previous to it has already been executed. Primarily, this is so that you can use the
undumpprogram to turn your core dump into an executable binary after having initialized all your variables at the beginning of the program. Please note that you shouldn't usedump( )orundump( )with the availability of the Perl Compiler (B modules) as part of your Perl distribution. In addition, you're unlikely to have success withdumporundumpon most modern Unix systems (that support dynamic loading fromlibdl).dumparranges for the revived binary, when run, to begin by executing agotolabel (with all the restrictions thatgotosuffers). Think of the operation as agotowith an intervening core dump and reincarnation. If label is omitted, the function arranges for the program to restart from the top. Note that any files opened at the time of the dump will no longer be open when the program is reincarnated. See also the -u command-line switch.As of Perl 5.8,dumpis now largely obsolete, partly because it's difficult to convert a core file into an executable, and because the real compiler backends for generating portable bytecode and compilable C code have superseded it. That's why you should now invoke it as"CORE::dump( )"if you don't want to be warned against a possible typo.Theundumpprogram is not available on all systems and may not be compatible with specific ports of Perl.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - each
- Inhaltsvorschaueacheach %hashReturns a two-element list consisting of the key and value for the next element of a hash. With successive calls to
each, you can iterate over the entire hash. Entries are returned in an indeterminate order. When the hash is entirely read, a null list is returned. The next call toeachafter that will start a new iteration. The iterator can be reset either by reading all the elements from the hash or by calling thekeysfunction in scalar context. You must not add elements to the hash while iterating over it, although you are permitted to usedelete. In a scalar context,eachreturns only the key.There is a single iterator for each hash, shared by alleach,keys, andvaluesfunction calls in the program. This means that after akeysorvaluescall, the nexteachcall will start again from the beginning.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - endgrent
- InhaltsvorschauendgrentendgrentCloses the groups file (usually /etc/group on Unix systems) if open. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- endhostent
- InhaltsvorschauendhostentendhostentCloses the hosts file (usually /etc/hosts on Unix systems) if open. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- endnetent
- InhaltsvorschauendnetentendnetentCloses the networks file (usually /etc/networks on Unix systems) if open. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- endprotoent
- InhaltsvorschauendprotoentendprotoentCloses the prototypes file (usually /etc/prototypes on Unix systems) if open. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- endpwent
- InhaltsvorschauendpwentendpwentCloses the password file (/etc/passwd or equivalent on Unix systems) if open. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- endservent
- InhaltsvorschauendserventendserventCloses the services file (usually /etc/services on Unix systems) if open. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- eof
- Inhaltsvorschaueofeof filehandle eof( )Returns true if the next read on filehandle will return end-of-file, or if filehandle is not open. filehandle may be an expression with a value that gives the real filehandle name. An
eofwithout an argument returns the end-of-file status for the last file read. Empty parentheses( )may be used in connection with the combined files listed on the command line. That is, inside awhile (<>)loop,eof( )will detect the end of only the last of a group of files. Useeof(ARGV)oreof(without parentheses) to test each file in awhile (<>)loop. For example, the following code inserts dashes just before the last line of the last file:while (<>) { if (eof( )) { print "-" x 30, "\n"; } print; }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - eval
- Inhaltsvorschauevaleval string eval {block}Evaluates the expression or code in its argument at runtime as a separate Perl program within the context of the larger script. Any variable settings remain afterward, as do any subroutine or format definitions. The code of the
evalis treated as a block, so any locally scoped variables declared within theevallast only until theevalis done. (See also local and my .) The value returned from anevalis the value of the last expression evaluated. Like subroutines, you may also use thereturnfunction to return a value and exit theeval.Withevalstring, the contents of string are compiled and executed at runtime. For example:$a = 3, $b = 4; $c = '$a * $b'; print (eval "$c"); # Prints 12
The string form ofevalis useful for executing strings produced at runtime from standard or other dynamic input sources. If the string produces an error, either from syntax or at runtime, theevalexits with the undefined value and places the error in$@. If string is omitted, the operator evaluates$_.The block form ofevalis used in Perl programs to handle runtime errors (exceptions). The code in block is compiled only once during the compilation of the main program. If there is a syntax error in the block, it will produce an error at compile time. If the code in block produces a runtime error (or if adiestatement is encountered), theevalexits, and the error is placed in$@. For example, the following code can be used to trap a divide-by-zero error at runtime:eval { $a = 10; $b = 0; $c = $a / $b; # Causes runtime error # Trapped by eval }; print $@; # Prints "Illegal division by 0 at # try.pl line 3"As with any code in a block, a final semicolon is not required.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - exec
- Inhaltsvorschauexecexec commandTerminates the currently running Perl script and executes the program named in command. The Perl program does not resume after the
execunless theexeccannot be run and produces an error. Unlikesystem, the executed command is not forked off into a child process. Anexeccompletely replaces the script in its current process.command may be a scalar containing a string with the name of the program to run and any arguments. This string is checked for shell metacharacters, and if there are any, passes the string to/bin/sh/ -cfor parsing. Otherwise, the string is read as a program command, bypassing any shell processing. The first word of the string is used as the program name, with any remaining words used as arguments.command may also be a list value in which the first element is parsed as the program name and remaining elements as arguments. For example:exec 'echo', 'Your arguments are: ', @ARGV;
Theexecfunction is not implemented for Perl on Win32 platforms.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - exists
- Inhaltsvorschauexistsexists $hash{$key}Returns true if the specified hash key exists, even if the corresponding value is undefined.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- exit
- Inhaltsvorschauexitexit statusExits the current Perl process immediately with that value given by status. This could be the entire Perl script you are running or only a child process created by
fork. Here's a fragment that lets a user exit the program by typingxorX:$ans = <STDIN>; exit 0 if $ans =~ /^[Xx]/;
If status is omitted, the function exits with0. You shouldn't useexitto abort a subroutine if there's any chance that someone might want to trap whatever error happened. Usedieinstead, which can be trapped by aneval.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - exp
- Inhaltsvorschauexpexp numReturns e to the power of num. If num is omitted, it gives
exp($_). To do general exponentiation, use the**operator.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - fcntl
- Inhaltsvorschaufcntlfcntl filehandle, function, argCalls the file control function (with the function-specific arg) to use on the file or device opened with filehandle.
fcntlcalls Unix'sfcntlfunction (not available on Win32 platforms). If the function is not implemented, the program exits with a fatal error.fcntlsets file descriptors for a filehandle. This built-in command is usable when you use the Fcntl module in the standard distribution:use Fcntl;
This module imports the correct functiondefinitions. See the description of the Fcntl module in Chapter 8.The return value offcntl(andioctl) is as follows:System call returnsPerl returns-1Undefined value0String"0 but true"Anything elseThat numberThus Perl returns true on success and false on failure, yet you can still easily determine the actual value returned by the operating system.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - fileno
- Inhaltsvorschaufilenofileno filehandleReturns the file descriptor for a filehandle. (A file descriptor is a small integer, unlike the filehandle, which is a symbol.) It returns
undefif the handle is not open. It's useful for constructing bitmaps forselectand for passing to certain obscure system calls ifsyscallis implemented. It's also useful for double-checking that theopenfunction gave you the file descriptor you wanted.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - flock
- Inhaltsvorschauflockflock filehandle, operationEstablishes or removes a lock on a file opened with filehandle. This function calls one of the Unix functions
flock,lockf, or the locking capabilities offcntl, whichever your system supports. If none of these functions exist on your system,flockwill produce a fatal error.operation is the type of locking function to perform. The number by each operation name is the argument that Perl'sflocktakes by default. You may also use the operation names if you explicitly import them from the Fcntl module withuse Fcntl ":flock".-
LOCK_SH(1) - Establishes a shared lock on the file (read lock).
-
LOCK_EX(2) - Establishes an exclusive lock on the file (write lock).
-
LOCK_UN(8) - Removes a lock from the file.
-
LOCK_NB(4) - Prevents
flockfrom blocking while trying to establish a lock withLOCK_SHorLOCK_EXand instructs it to return immediately.LOCK_NBmust be ored with the other operation as an expression for the operation argument, i.e.,(LOCK_EX |LOCK_NB).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- fork
- InhaltsvorschauforkforkSpawns a child process that executes the code immediately following the
forkcall until the process is terminated (usually with anexit). The child process runs parallel to the parent process and shares all the parent's variables and open filehandles. The function returns the child pid to the parent process and0to the child process on success. If it fails, it returns the undefined value to the parent process, and no child process is created. If youforkyour child processes, you'll have towaiton their zombies when they die. (See the wait function for more information.) Theforkfunction is unlikely to be implemented on any operating system not resembling Unix, unless it purports POSIX compliance.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - formline
- Inhaltsvorschauformlineformline picture, variablesInternal function used by formats, although you may also call it. It formats a list of values (variables) according to the contents of picture, placing the output into the format output accumulator,
$^A. When awriteis done, the contents of$^Aare written to a filehandle, but you can also read$^Ayourself and set$^Aback to "". Note that a format typically does oneformlineper line of form, but theformlinefunction itself doesn't care how many newlines are embedded in the picture. This means that the~and~~tokens will treat the entire picture as a single line. Thus, you may need to use multiple formlines to implement a single-record format, such as the format compiler.Be careful if you put double quotes around the picture, since an@character may be taken to mean the beginning of an array name.formlinealways returns true. See Chapter 4 for more information.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getc
- Inhaltsvorschaugetcgetc filehandleReturns the next byte from the input file attached to filehandle. At end-of-file, it returns a null string. If filehandle is omitted, the function reads from STDIN. This operator is very slow, but is occasionally useful for single-character input from the keyboard.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- getgrent
- InhaltsvorschaugetgrentgetgrentReturns the next entry from the systems group file (usually /etc/group on Unix systems) starting from the top. Returns null when end-of-file is reached. The return value from
getgrentin list context is:($name, $passwd, $gid, $members)
in which$memberscontains a space-separated list of the login names of the members of the group. In scalar context,getgrentreturns only the group name.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getgrgid
- Inhaltsvorschaugetgrgidgetgrgid gidRetrieves a group file (/etc/group) entry by group number gid. The return value in list context is:
($name, $passwd, $gid, $members)
in which$memberscontains a space-separated list of the login names of the members of the group. If you want to do this repeatedly, consider caching the data in a hash usinggetgrent. In scalar context,getgrgidreturns only the group name.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getgrnam
- Inhaltsvorschaugetgrnamgetgrnam nameRetrieves a group file entry by the group name name. The return value in list context is:
($name, $passwd, $gid, $members)
in which$memberscontains a space-separated list of the login names of the members of the group. In scalar context,getgrnamreturns only the numeric group ID.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - gethostbyaddr
- Inhaltsvorschaugethostbyaddrgethostbyaddr address, [addrtype]Retrieves the hostname (and alternate addresses) of a packed binary network address. (addrtype indicates the type of address given. Since
gethostbyaddris used almost solely for Internet IP addresses, addrtype is not needed.) The return value in list context is:($name, $aliases, $addrtype, $length, @addrs)
in which@addrsis a list of packed binary addresses. In the Internet domain, each address is four bytes long and can be unpacked by something like:($a, $b, $c, $d) = unpack('C4', $addrs[0]);In scalar context,gethostbyaddrreturns only the hostname.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - gethostbyname
- Inhaltsvorschaugethostbynamegethostbyname nameRetrieves the address (and other names) of a network hostname. The return value in list context is:
($name, $aliases, $addrtype, $length, @addrs)
in which@addrsis a list of raw addresses. In scalar context,gethostbynamereturns only the host address.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - gethostent
- InhaltsvorschaugethostentgethostentRetrieves the next entry from your system's network hosts file (usually /etc/hosts on Unix). The return value from
gethostentis:($name, $aliases, $addrtype, $length, @addrs)
in which@addrsis a list of raw addresses. Scripts that use this function should not be considered portable.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getlogin
- InhaltsvorschaugetlogingetloginReturns the current login from /etc/utmp (Unix systems only), if any. If null, use
getpwuid. For example:$login = getlogin || getpwuid($<) || "Intruder!!";
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getnetbyaddr
- Inhaltsvorschaugetnetbyaddrgetnetbyaddr address, [addrtype]Retrieves the network name or names of the given network address. (addrtype indicates the type of address. Often, this function is used for IP addresses, in which the type is not needed.) The return value in list context is:
($name, $aliases, $addrtype, $net)
In scalar context,getnetbyaddrreturns only the network name.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getnetbyname
- Inhaltsvorschaugetnetbynamegetnetbyname nameRetrieves the network address of a network name. The return value in list context is:
($name, $aliases, $addrtype, $net)
In scalar context,getnetbynamereturns only the network address.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getnetent
- InhaltsvorschaugetnetentgetnetentRetrieves the next line from your /etc/networks file, or system equivalent. The return value in list context is:
($name, $aliases, $addrtype, $net)
In scalar context,getnetentreturns only the network name.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getpeername
- Inhaltsvorschaugetpeernamegetpeername socketReturns the packed socket address of the other end of the socket connection. For example:
use Socket; $hersockaddr = getpeername SOCK; ($port, $heraddr) = unpack_sockaddr_in($hersockaddr); $herhostname = gethostbyaddr($heraddr, AF_INET); $herstraddr = inet_ntoa($heraddr);
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getpgrp
- Inhaltsvorschaugetpgrpgetpgrp pidReturns the current process group for the specified process ID (pid). Use a pid of
0for the current process. Invokinggetpgrpwill produce a fatal error if used on a machine that doesn't implement thegetpgrpsystem call. If pid is omitted, the function returns the process group of the current process (the same as using a pid of0). On systems implementing this operator with the POSIXgetpgrp(2)system call, pid must be omitted or, if supplied, must be0.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getppid
- InhaltsvorschaugetppidgetppidReturns the process ID of the parent process. On a typical Unix system, if your parent process ID changes to
1, your parent process has died, and you've been adopted by the init program.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getpriority
- Inhaltsvorschaugetprioritygetpriority type, idReturns the current priority for a process, a process group, or a user. type indicates which of these three process types to return. (The type identifiers are system-specific. Consult the manpage for
getpriority.) The id gives the specific ID of the corresponding process type in type: a process ID, a process-group ID, or a user ID. The value0in who gives the priority for the current process, process group, or user.The priority will be an integer value. Lower values indicate higher priority (negative values may be returned on some systems). Invokinggetprioritywill produce a fatal error if used on a machine that doesn't implement thegetprioritysystem call.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getprotobyname
- Inhaltsvorschaugetprotobynamegetprotobyname nameTranslates a protocol name to its corresponding number. The return value in list context is:
($name, $aliases, $protocol_number)
In scalar context,getprotobynamereturns only the protocol number.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getprotobynumber
- Inhaltsvorschaugetprotobynumbergetprotobynumber numberTranslates a protocol number to its corresponding name. The return value in list context is:
($name, $aliases, $protocol_number)
In scalar context,getprotobynumberreturns only the protocol name.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getprotoent
- InhaltsvorschaugetprotoentgetprotoentRetrieves the next line from the /etc/protocols file (on some Unix systems). Returns null at the end of the file. The return value from
getprotoentis:($name, $aliases, $protocol_number)
In scalar context,getprotoentreturns only the protocol name.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getpwent
- InhaltsvorschaugetpwentgetpwentRetrieves the next line from the /etc/passwd file (or its equivalent coming from another server). Returns null at the end of the file. The return value in list context is:
($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell)
Some machines may use the quota and comment fields for other purposes, but the remaining fields will always be the same. To set up a hash for translating login names to uids, do this:while (($name, $passwd, $uid) = getpwent) { $uid{$name} = $uid; }In scalar context,getpwentreturns only the username.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getpwnam
- Inhaltsvorschaugetpwnamgetpwnam nameRetrieves the passwd file entry of a user name. The return value in list context is:
($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell)
If you want to do this repeatedly, consider caching the data in a hash usinggetpwent.In scalar context,getpwnamreturns only the numeric user ID.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getpwuid
- Inhaltsvorschaugetpwuidgetpwuid uidRetrieves the passwd file entry with the user ID uid. The return value in list context is:
($name,$passwd,$uid,$gid,$quota,$comment,$gcos,$dir,$shell)
If you want to do this repeatedly, consider slurping the data into a hash usinggetpwent.In scalar context,getpwuidreturns the username.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getservbyname
- Inhaltsvorschaugetservbynamegetservbyname name, protoTranslates a service (port) name to its corresponding port number. proto is a protocol name such as
tcp. The return value in list context is:($name, $aliases, $port_number, $protocol_name)
In scalar context,getservbynamereturns only the service port number.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getservbyport
- Inhaltsvorschaugetservbyportgetservbyport port, protoTranslates a service (port) number to its corresponding names. proto is a protocol name such as
tcp. The return value in list context is:($name, $aliases, $port_number, $protocol_name)
In scalar context,getservbyportreturns only the service port name.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getservent
- InhaltsvorschaugetserventgetserventRetrieves the next listing from the /etc/services file or its equivalent. Returns null at the end of the file. The return value in list context is:
($name, $aliases, $port_number, $protocol_name)
In scalar context,getserventreturns only the service port name.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - getsockname
- Inhaltsvorschaugetsocknamegetsockname socketReturns the packed socket address of this end of the socket connection.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- getsockopt
- Inhaltsvorschaugetsockoptgetsockopt socket, level, optnameReturns the value of the socket option optname, or the undefined value if there is an error. level identifies the protocol level used by socket. Options vary for different protocols. See also setsockopt .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- glob
- Inhaltsvorschauglobglob exprPerforms filename expansion (globbing) on expr, returning the next successive name on each call. If expr is omitted,
$_isglobbed instead. This is the internal function implementing the<*>operator, except that it may be easier to type this way.Theglobfunction is not related to the Perl notion of typeglobs, other than that they both use a*to represent multiple items.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - gmtime
- Inhaltsvorschaugmtimegmtime exprConverts a time string as returned by the
timefunction to a nine-element list with the time correct for Greenwich Mean Time zone (a.k.a. GMT, UTC, etc.). Typically used as follows:($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);All list elements are numeric and come straight out of a C languagestruct tm. In particular, this means that$monhas the range0..11,$wdayhas the range0..6, and the year has had 1,900 subtracted from it. (You can remember which elements are0-based because you're always using these as subscripts into0-based arrays containing month and day names.) If expr is omitted, it doesgmtime(time). For example, to print the current month in London:$london_month = (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec))[(gmtime)[4]];The Perl library module Time::Local contains a subroutine,timegm( ), that can convert in the opposite direction.In scalar context,gmtimereturns actime(3)-like string based on the GMT time value.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - goto
- Inhaltsvorschaugotogoto label goto &nameFinds the statement labeled with label (or an expression that evaluates to a label) and resumes execution there. It may not be used to go into any construct that requires initialization, such as a subroutine or a
foreachloop. It also can't be used to go into a construct that is optimized away. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but for that purpose, it's usually better to use another construct, such aslastordie.goto&name substitutes a call to the named subroutine for the currently running subroutine. This is used byAUTOLOADsubroutines that wish to load another subroutine and pretend that this subroutine—and not the original one—had been called in the first place (except that any modifications to@_in the original subroutine are propagated to the replacement subroutine). After thegoto, not evencallerwill be able to tell that the original routine was called first.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - grep
- Inhaltsvorschaugrepgrep expr, list grep {block} listEvaluates expr or blockin a Boolean context for each element of list, temporarily setting
$_to each element in turn. In list context, it returns a list of those elements for which the expression is true. Mostly used like Unix grep, in which expr is a search pattern, and list elements that match are returned. In scalar context,grepreturns the number of times the expression was true.For example, presuming@all_linescontains lines of code, this example weeds out comment lines:@code_lines = grep !/^#/, @all_lines;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - hex
- Inhaltsvorschauhexhex hexnumConverts a hexadecimal string hexnum into its equivalent decimal value. If hexnum is omitted, it interprets
$_. The following code sets$numberto 4,294,906,560:$number = hex("ffff12c0");To do the inverse function, use:sprintf "%lx", $number; # That's a letter 'l', not a one
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - index
- Inhaltsvorschauindexindex string, substr, [start]Returns the position of the first occurrence of substr in string. The start, if specified, specifies the position to start looking in the string. Positions are integer numbers based at
0. If the substring is not found, theindexfunction returns-1.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - int
- Inhaltsvorschauintint numReturns the integer portion of num. If num is omitted, the function uses
$_.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ioctl
- Inhaltsvorschauioctlioctl filehandle, function, argCalls the
ioctlUnix system call to perform function (with the function-specific arg) on the file or device opened with filehandle. See fcntl for a description of return values.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - join
- Inhaltsvorschaujoinjoin char, listJoins the separate strings of list into a single string with fields separated by the value of char and returns the string. For example:
$_ = join ':', $login,$passwd,$uid,$gid,$gcos,$home,$shell;
To do the opposite, see split . To join things together into fixed-position fields, see pack .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - keys
- Inhaltsvorschaukeyskeys %hashReturns a list consisting of all the keys of the named hash. The keys are returned in an apparently random order, but it is the same order that either the
valuesoreachfunction produces (assuming that the hash has not been modified between calls).In scalar context,keysreturns the number of elements of the hash (and resets theeachiterator).keyscan be used as an lvalue to increase the number of hash buckets allocated for the hash:keys %hash = 200;Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - kill
- Inhaltsvorschaukillkill sig, processesSends a signal, sig, to a list of processes. You may use a signal name in quotes (without a
SIGon the front). This function returns the number of processes successfully signaled. If the signal is negative, the function kills process groups instead of processes.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - last
- Inhaltsvorschaulastlast labelImmediately exits the loop identified by label. If label is omitted, the command refers to the innermost enclosing loop.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- lc
- Inhaltsvorschaulclc stringReturns a lowercase version of string (or
$_, if omitted). This is the internal function implementing the\Lescape in double-quoted strings.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - lcfirst
- Inhaltsvorschaulcfirstlcfirst stringReturns a version of string (or
$_, if omitted) with the first character lowercased. This is the internal function implementing the\lescape in double-quoted strings.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - length
- Inhaltsvorschaulengthlength valReturns the length in bytes of the scalar value val. If val is omitted, the function returns the length of
$_.Do not try to uselengthto find the size of an array or hash. Usescalar @array for the size of an array, andscalar keys %hashfor the size of a hash.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - link
- Inhaltsvorschaulinklink oldfile, newfileCreates a Unix hard link from a new filename, newfile, to an existing file, oldfile, on the same filesystem. The function returns
1for success,0otherwise (and puts the error code into$!). This function is unlikely to be implemented on non-Unix systems. See also symlink .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - listen
- Inhaltsvorschaulistenlisten socket, queuesizeTells the operating system that you are ready to accept connections on socket and sets the number of waiting connections to queuesize. If the queue is full, clients trying to connect to the socket will be refused connection.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- local
- Inhaltsvorschaulocallocal varsDeclares one or more global variables vars to have temporary values within the innermost enclosing block, subroutine,
eval, or file. The new value is initiallyundeffor scalars and( )for arrays and hashes. If more than one variable is listed, the list must be placed in parentheses, because the operator binds more tightly than a comma. All the listed variables must be legal lvalues, that is, something you can assign to. This operator works by saving the current values of those variables on a hidden stack and restoring them upon exiting the block, subroutine,eval, or file.Subroutines called within the scope of a local variable will see the localized inner value of the variable. The technical term for this process is "dynamic scoping." Usemyfor true private variables.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - localtime
- Inhaltsvorschaulocaltimelocaltime valConverts the value returned by
timeto a nine-element list with the time corrected for the local time zone. It's typically used as follows:($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);All list elements are numeric. The element$mon(month) has the range0..11, and$wday(weekday) has the range0..6. The year has had 1,900 subtracted from it. (You can remember which elements are0-based because you're always using them as subscripts into0-based arrays containing month and day names.) If val is omitted, it doeslocaltime(time). For example, to get the name of the current day of the week:$thisday = (Sun,Mon,Tue,Wed,Thu,Fri,Sat)[(localtime)[6]];
The Perl library module Time::Local contains a subroutine,timelocal( ), that can convert in the opposite direction.In scalar context,localtimereturns actime(3)-like string based on the localtime value.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - log
- Inhaltsvorschauloglog numReturns logarithm (base e) of num. If num is omitted, the function uses
$_.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - lstat
- Inhaltsvorschaulstatlstat fileLike
stat, returns information on file, except that if file is a symbolic link,lstatreturns information about the link;statreturns information about the file pointed to by the link. (If symbolic links are unimplemented on your system, a normalstatis done instead.)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - map
- Inhaltsvorschaumapmap {block} list map expr, listEvaluates the block or exprfor each element of list (locally setting
$_to each element) and returns the list value composed of the results of each evaluation. It evaluates block or exprin a list context, so each element of listmay produce zero, one, or more elements in the returned value. These are all flattened into one list. For instance:@words = map { split ' ' } @lines;splits a list of lines into a list of words. Often, though, there is a one-to-one mapping between input values and output values:@chars = map chr, @nums;
This statement translates a list of numbers to the corresponding characters.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - mkdir
- Inhaltsvorschaumkdirmkdir filename, modeCreates the directory specified by filename, with permissions specified by the numeric mode(as modified by the current umask). If it succeeds, it returns
1; otherwise, it returns0and sets$!(from the value oferrno).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - msgctl
- Inhaltsvorschaumsgctlmsgctl id, cmd, argCalls the
msgctlsystem call, which is used to perform different control operations on IPC message queues. (See themsgctldocumentation on your system for details.) If cmd is&IPC_STAT, then argmust be a variable that will hold the returnedmsqid_dsstructure. The return values work like those offnctl: the undefined value for error,0 buttruefor zero, or the actual return value otherwise. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "msg.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - msgget
- Inhaltsvorschaumsggetmsgget key, flagsCalls the System V IPC
msggetsystem call. See themsggetdocumentation on your system for details. The function returns the message queue ID, or the undefined value if there is an error. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "msg.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - msgrcv
- Inhaltsvorschaumsgrcvmsgrcv id, var, size, type, flagsCalls the System V IPC
msgrcvsystem call to receive a message from message queue id into variable var with a maximum message size of size. When a message is received, the message type will be the first thing in var, and the maximum length of var is sizeplus the size of the message type. The function returns true if successful, or false if there is an error. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "msg.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - msgsnd
- Inhaltsvorschaumsgsndmsgsnd id, msg, flagsCalls the System V IPC
msgsndsystem call to send the message msg to the message queue id. msg must begin with the long integer message type. You can create a message like this:$msg = pack "L a*", $type, $text_of_message;
The function returns true if successful, or false if there is an error. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "msg.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - my
- Inhaltsvorschaumymy varsDeclares one or more private variables to exist only within the innermost enclosing block, subroutine,
eval, or file. The new value is initiallyundeffor scalars and( )for arrays and hashes. If more than one variable is listed, the list must be placed in parentheses, because the operator binds more tightly than a comma. Only simple scalars or complete arrays and hashes may be declared this way. The variable name may not be package-qualified, because package variables are all global, and private variables are not related to any package.Unlikelocal, this operator has nothing to do with global variables, other than hiding any other variable of the same name from view within its scope. (A global variable can always be accessed through its package-qualified form or a symbolic reference, however.) A private variable is not visible until the statement after its declaration. Subroutines called from within the scope of such a private variable cannot see the private variable unless the subroutine is also textually declared within the scope of the variable.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - next
- Inhaltsvorschaunextnext labelImmediately jumps to the next iteration of the loop identified by label or the innermost enclosing loop, if there is no argument. If there is a
continueblock, it will be executed immediately after thenext, before the loop is reiterated.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - no
- Inhaltsvorschaunono Module listEffectively "undoes" the
usefunction. Used to deactivate pragmas (compiler directives) for sections of your program. For instance:no strict 'refs'
allows soft references to the end of the block scope if:use strict 'refs'
was previously invoked.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - oct
- Inhaltsvorschauoctoct ostringInterprets ostring as an octal string and returns the equivalent decimal value. (If ostringhappens to start with
0x, it is interpreted as a hex string instead.) The following will handle decimal, octal, and hex in the standard notation:$val = oct $val if $val =~ /^0/;
If ostring is omitted, the function interprets$_. To perform the inverse function on octal numbers, use:$oct_string = sprintf "%lo", $number;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - open
- Inhaltsvorschauopenopen filehandle, filename open filehandle, mode, filename open filehandle, mode, expr, list (new in 5.8) open filehandle, mode, reference (new in 5.8)Opens the file given by filename and associates it with filehandle. If filehandle is omitted, the scalar variable of the same name as the filehandle must contain the filename. (And you must also be careful to use
or dieafter the statement rather than||die, because the precedence of||is higher than list operators such asopen.)If filename is preceded by either<or nothing, the file is opened for input (read-only). If filename is preceded by>, the file is opened for output. If the file doesn't exist, it will be created; if the file exists, it will be overwritten with output using>. Preceding the filename with>>opens an output file for appending. For both read and write access, use a+before<or>.If you choose to use the three-or-more-arguments form ofopen, you can use separate mode and filename arguments, such asopen($fh, $mode, $filename), in which$moderepresents an open mode or pipe. For example:my $mode = '+<'; my $filename = 'whatever.txt'; open(FH, $mode, $filename) or die("can't open $filename: $!");As covered in Chapter 4, you can build Perl 5.8 and newer with PerlIO support, which offers additional features for your system's I/O (STDIO). This allows you to do neat things, such as specifyutf-8as your default encoding for all of your I/O, or set your default line endings with'crlf'. In addition, you can select piping to or extracting information from an external program with'|-'and'-|', respectively. For example:my $prog = "webster overworked"; open($fh, '-|', $prog) or die("can't open pipe to '$prog': $!");or, similarly:my @prog_info = qw(/usr/contrib/bin/webster overworked); open($fh, '-|', @prog_info) or die(...);A filehandle may also be attached to a process by using a piped command. If the filename begins withEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - opendir
- Inhaltsvorschauopendiropendir dirhandle, directoryOpens a directory for processing by
readdir,telldir,seekdir,rewinddir, andclosedir. The function returns true if successful. Directory handles have their own namespace separate from filehandles.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ord
- Inhaltsvorschauordord exprReturns the numeric ASCII value of the first character of expr. If expr is omitted, it uses
$_. The return value is always unsigned. If you want a signed value, useunpack('c', expr). If you want all the characters of the string converted to a list of numbers, useunpack('C*', expr)instead.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - our
- Inhaltsvorschauourour varsDeclares the listed variables to be valid globals within the enclosing block, file, or
eval. vars must be in parentheses if more than one value is used.our( )has the same scoping rules as a "my" declaration but does not create a local variable. Variables that you create withour( )will be visible across its lexical scope and may cross package boundaries. Unlikeusevars,our( )is not package scoped; the package in which the variable is entered is determined at the point of declaration, not at the time of use. This means the following behavior holds:package Foo; our $bar; # Declares $Foo::bar for rest of lexical scope $bar = 20; package Bar; print $bar; # Prints 20You my use multipleourdeclarations in the same lexical scope if they are in different packages. If they are in the same package, Perl will emit warnings if you have asked for them:use warnings; package Foo; our $bar; # Declares $Foo::bar for rest of lexical scope $bar = 20; package Bar; our $bar = 30; # Declares $Bar::bar for rest of lexical scope print $bar; # Prints 30 our $bar; # Emits warningEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - pack
- Inhaltsvorschaupackpack template, listTakes a list of values and packs it into a binary structure, returning the string containing the structure. templateis a sequence of characters that give the order and type of values, as follows:CharacterMeaning
@Null-fill to absolute position.(Start of a( )group.aAn ASCII string, will be null padded.AAn ASCII string, will be space padded.bA bit string, low-to-high order (such asvec( )).BA bit string, high-to-low order.cA signed char value.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - package
- Inhaltsvorschaupackagepackage namespaceDeclares that the rest of the innermost enclosing block, subroutine,
eval, or file belongs to the indicated namespace. (The scope of apackagedeclaration is thus the same as the scope of alocalormydeclaration.) All subsequent references to unqualified global identifiers will be resolved by looking them up in the declared packages symbol table. Apackagedeclaration affects only global variables—including those you've usedlocalon—but not lexical variables created withmy.Usingpackagewithout an argument is possible, but since its semantics are unclear,package;has been depracated in Perl 5.8. If you intend to disallow variables that aren't fully qualified, usestrict;instead.Typically, you put apackagedeclaration as the first thing in a file that will be included by therequireoruseoperator, but you can put one anywhere that a statement would be legal. When defining a class or a module file, it is customary to name the package the same name as the file, to avoid confusion. (It's also customary to name such packages beginning with a capital letter, because lowercase modules are, by convention, interpreted as pragmas.)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - pipe
- Inhaltsvorschaupipepipe readhandle, writehandleOpens a pair of connected pipes. This call is almost always used right before a
fork, after which the pipes reader should close writehandle, and the writer should close readhandle. (Otherwise, the pipe won't indicate end-of-file to the reader when the writer closes it.) Note that if you set up a loop of piped processes, deadlock can occur unless you are very careful. In addition, note that Perl's pipes use standard I/O buffering, so you may need to set$|on your writehandle to flush after each output command, depending on the application. See select filehandle.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - pop
- Inhaltsvorschaupoppop @arrayTreats an array like a stack, popping and returning the last value of the array and shortening the array by one element. If array is omitted, the function pops
@ARGV(in the main program) or@_(in subroutines).If there are no elements in the array,popreturns the undefined value. See also push and shift . If you want to pop more than one element, usesplice.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - pos
- Inhaltsvorschaupospos $scalarReturns the location in scalar where the last
m//gsearch over scalarleft off. It returns the offset of the character after the last one matched. This is the offset where the nextm//gsearch on that string will start. Remember that the offset of the beginning of the string is0. For example:$grafitto = "fee fie foe foo"; while ($grafitto =~ m/e/g) { print pos $grafitto, "\n"; }prints2,3,7, and11, the offsets of each of the characters following an "e". Theposfunction may be assigned a value to tell the nextm//gwhere to start.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Inhaltsvorschauprintprint [filehandle] listPrints a string or a comma-separated list of strings to the specified filehandle. If no filehandle is given, the function prints to the currently open filehandle (STDOUT initially). The function returns
1if successful,0otherwise. filehandlemay be a scalar variable name (unsubscripted), in which case the variable contains either the name of the actual filehandle or a reference to a filehandle object from one of the object-oriented filehandle packages. filehandle may also be a block that returns either kind of value:print { $OK ? "STDOUT" : "STDERR" } "stuff\n"; print { $iohandle[$i] } "stuff\n";If list is also omitted,$_is printed. Note that becauseprinttakes a list, anything in the list is evaluated in list context.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - printf
- Inhaltsvorschauprintfprintf [filehandle] format, listPrints a formatted string of the elements in list to filehandle or, if omitted, the currently selected output filehandle. This is similar to the C library's
printfandfprintffunctions, except that the*field width specifier is not supported. The function is exactly equivalent to:print filehandle sprintf(format, list);
printfandsprintfuse the same format syntax, butsprintfreturns only a string; it doesn't print to a filehandle. The format string contains text with embedded field specifiers into which the elements of list are substituted in order, one per field. Field specifiers follow the form:%m.nxA percent sign begins each field, and x is the type of field. The optional m gives the minimum field width for appropriate field types (negative m left-justifies). The .n gives the precision for a specific field type, such as the number of digits after a decimal point for floating-point numbers, the maximum length for a string, and the minimum length for an integer.Field specifiers (x) may be the following:CodeMeaning%Percent signcCharacterdDecimal integereEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - prototype
- Inhaltsvorschauprototypeprototype functionReturns the prototype of a function as a string, or
undefif the function has no prototype. function is the name of the function or a reference to it.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - push
- Inhaltsvorschaupushpush @array, listPushes the elements of list onto the end of array. The length of array increases by the length of list. The function returns this new length. See also pop and unshift .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- q/string/
- Inhaltsvorschauq/string/q/string/ qq/string/ qx/string/ qw/strings/Generalized forms of quoting.
q//is equivalent to using single quotes (literal, no variable interpolation).qq//is equivalent to double quotes (literal, interpolated).qx//is equivalent to using backticks for commands (interpolated). Andqw//is equivalent to splitting a single-quoted string on whitespace.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - quotemeta
- Inhaltsvorschauquotemetaquotemeta exprReturns the value of expr (or
$_if not specified) with all non-alphanumeric characters backslashed. This is the internal function implementing the\Qescape in interpolative contexts (including double-quoted strings, backticks, and patterns).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - rand
- Inhaltsvorschaurandrand numReturns a random fractional number between
0and the value of num. (numshould be positive.) If num is omitted, the function returns a value between0and1(including0, but excluding1). See also srand .To get an integral value, combine this withint, as in:$roll = int(rand 6) + 1; # $roll is now an integer between 1 and 6
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - read
- Inhaltsvorschaureadread filehandle, $var, length, [offset]Attempts to read length bytes of data into variable var from the specified filehandle. The function returns the number of bytes actually read, or
0at end-of-file. It returns the undefined value on error. var will grow or shrink to the length actually read. The offset, if specified, says where in the variable to start putting bytes, so that you can do areadinto the middle of a string.To copy data from the filehandle FROM into the filehandle TO, you could say:while (read FROM, $buf, 16384) { print TO $buf; }Note that the opposite ofreadis simplyprint, which already knows the length of the string you want to write and can write a string of any length.Perl'sreadfunction is actually implemented in terms of standard I/O'sfreadfunction, so the actualreadsystem call may read more than length bytes to fill the input buffer, andfreadmay do more than one systemreadto fill the buffer. To gain greater control, specify the real system call usingsysread.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - readdir
- Inhaltsvorschaureaddirreaddir dirhandleReads directory entries from a directory handle opened by
opendir. In scalar context, this function returns the next directory entry, if any; otherwise, it returns an undefined value. In list context, it returns all the rest of the entries in the directory, which will of course be a null list if there are none.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - readline
- Inhaltsvorschaureadlinereadline *filehandleReads a line or lines from the specified filehandle. (A typeglob of the filehandle name should be supplied.) Returns one line per call in a scalar context. Returns a list of all lines until the end-of-file in list context.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- readlink
- Inhaltsvorschaureadlinkreadlink nameReturns the name of a file pointed to by the symbolic link name. nameshould evaluate to a filename, the last component of which is a symbolic link. If it is not a symbolic link, or if symbolic links are not implemented, or if a system error occurs, the undefined value is returned, and you should check the error code in
$!. If name is omitted, the function uses$_.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - readpipe
- Inhaltsvorschaureadpipereadpipe cmdExecutes cmd as a system command and returns the collected standard output of the command. In a scalar context, the output is returned as a single, possibly multiline, string. In list context, a list of output lines is returned.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- recv
- Inhaltsvorschaurecvrecv socket, $var, len, flagsReceives a message on a socket. It attempts to receive len bytes of data into variable var from the specified socket filehandle. The function returns the address of the sender, or the undefined value if there's an error. varwill grow or shrink to the length actually read. The function takes the same flags as the
recv(2)system call.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - redo
- Inhaltsvorschauredoredo [label]Restarts a loop block identified by label without reevaluating the conditional. The
continueblock, if any, is not executed. If the label is omitted, the command refers to the innermost enclosing loop.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ref
- Inhaltsvorschaurefref $varReturns a string indicating the type of the object referenced if var is a reference; returns the null string otherwise. Built-in types include:
REF SCALAR ARRAY HASH CODE GLOB
If the referenced object has been blessed into a package, that package name is returned instead. You can think ofrefas a "typeof" operator.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - rename
- Inhaltsvorschaurenamerename oldname, newnameChanges the name of a file from oldname to newname. It returns
1for success,0otherwise (and puts the error code into$!). It will not work across filesystem boundaries. If there is already a file named newname, it will be destroyed.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - require
- Inhaltsvorschaurequirerequire filename require num require packageAsserts a dependency of some kind depending on its argument. (If an argument is not supplied,
$_is used.)If the argument is a string filename, this function includes and executes the Perl code found in the separate file of that name. This is similar to performing anevalon the contents of the file, except thatrequirechecks to see that the library file has not been included already. The function also knows how to search the include path stored in the@INCarray.Ifrequires argument is a number num, the version number of the currently executing Perl binary (as known by$]) is compared to num. If it is smaller, execution is immediately aborted. Thus, a script that requires Perl version 5.003 can have as its first line:require 5.003;
and earlier versions of Perl will abort.Ifrequire's argument is a package name,requireassumes an automatic .pm suffix, making it easy to load standard modules. This is likeuse, except that it happens at runtime, not compile time, and theimportroutine is not called.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - reset
- Inhaltsvorschauresetreset exprUsed at the top of a loop or in a
continueblock at the end of a loop to clear global variables or reset??searches so they work again. expr is a list of single characters (hyphens are allowed for ranges). All scalar variables, arrays, and hashes beginning with one of those letters are reset to their pristine state. If expr is omitted, one-match searches (?PATTERN?) are reset to match again. The function resets variables or searches for the current package only. It always returns1.Lexical variables (created bymy) are not affected. Use ofresetis vaguely deprecated.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - return
- Inhaltsvorschaureturnreturn exprReturns from a subroutine (or
eval) with the value of expr. (In the absence of an explicitreturn, the value of the last expression evaluated is returned.) Use ofreturnoutside of a subroutine orevalwill result in a fatal error.The supplied expression will be evaluated in the context of the subroutine invocation. That is, if the subroutine was called in a scalar context, expr is also evaluated in scalar context. If the subroutine was invoked in a list context, then expr is also evaluated in list context and can return a list value. A return with no argument returns the undefined value in scalar context and a null list in list context. The context of the subroutine call can be determined from within the subroutine by using the (misnamed)wantarrayfunction.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - reverse
- Inhaltsvorschaureversereverse listReturns a list value consisting of the elements of listin the opposite order. This is fairly efficient because it just swaps the pointers around. In scalar context, the function concatenates all the elements of list together and returns the reverse of this character by character.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- rewinddir
- Inhaltsvorschaurewinddirrewinddir dirhandleSets the current position to the beginning of the directory for the
readdirroutine on dirhandle. The function may not be available on all machines that supportreaddir.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - rindex
- Inhaltsvorschaurindexrindex str, substr, [position]Works just like
indexexcept that it returns the position of the last occurrence of substr in str (a reverseindex). The function returns-1if not found. position, if specified, is the rightmost position that may be returned, i.e., how far in the string the function can search.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - rmdir
- Inhaltsvorschaurmdirrmdir nameDeletes the directory specified by name if it is empty. If it succeeds, it returns
1; otherwise, it returns0and puts the error code into$!. If name is omitted, the function uses$_.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - scalar
- Inhaltsvorschauscalarscalar exprForces an expression expr to be evaluated in scalar context.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- seek
- Inhaltsvorschauseekseek filehandle, offset, whencePositions the file pointer for filehandle, just like the
fseek(3)call of standard I/O. The first position in a file is at offset0, not offset1, and offsets refer to byte positions, not line numbers. The function returns1upon success,0otherwise. For handiness, the function can calculate offsets from various file positions for you. The value of whence specifies which of three file positions your offset is relative to:0, the beginning of the file;1, the current position in the file; or2, the end of the file. offset may be negative for a whence of1or2.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - seekdir
- Inhaltsvorschauseekdirseekdir dirhandle, posSets the current position for the
readdirroutine on dirhandle. posmust be a value returned bytelldir. This function has the same caveats about possible directory compaction as the corresponding system library routine.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - select
- Inhaltsvorschauselectselect filehandleReturns the currently selected output filehandle, and if filehandle is supplied, sets that as the current default filehandle for output. This has two effects. First, a
writeor aprintwithout a filehandle argument will default to this filehandle. Second, special variables related to output will refer to this output filehandle.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - select
- Inhaltsvorschauselectselect rbits, wbits, ebits, timeoutThe four-argument
selectoperator is totally unrelated to the previously describedselectoperator. This operator is for discovering which (if any) of your file descriptors are ready to do input or output, or to report an exceptional condition. It calls theselect(2)system call with the bitmasks you've specified, which you can construct usingfilenoandvec, like this:$rbits = $wbits = $ebits = ""; vec($rbits, fileno(STDIN), 1) = 1; vec($wbits, fileno(STDOUT), 1) = 1; $ein = $rin | $win;
Theselectcall blocks until one or more file descriptors is ready for reading, writing, or reporting an error condition. timeout is given in seconds and tellsselecthow long to wait.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - semctl
- Inhaltsvorschausemctlsemctl id, semnum, cmd, argCalls the System V IPC system call
semctl(2). If cmd is&IPC_STATor&GETALL, then argmust be a variable which will hold the returnedsemid_dsstructure or semaphore value array. The function returns likeioctl: the undefined value for error,0 but truefor zero, or the actual return value otherwise. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "sem.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - semget
- Inhaltsvorschausemgetsemget key, nsems, size, flagsCalls the System V IPC system call
semget(2). The function returns the semaphore ID, or the undefined value if there is an error. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "sem.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - semop
- Inhaltsvorschausemopsemop key, opstringCalls the System V IPC system call
semop(2)to perform semaphore operations such as signaling and waiting. opstring must be a packed array ofsemopstructures. You can make eachsemopstructure by sayingpack('s*', $semnum, $semop, $semflag). The number of semaphore operations is implied by the length of opstring. The function returns true if successful or false if there is an error. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "sem.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - send
- Inhaltsvorschausendsend socket, msg, flags, [dest]Sends a message msg on a socket. It takes the same flags as the system call of the same name (see
send(2)). On unconnected sockets, you must specify a destination dest to send to, in which casesendworks likesendto(2). The function returns the number of bytes sent, or the undefined value if there is an error. On error, it puts the error code into$!.Some non-Unix systems improperly treat sockets as different objects than ordinary file descriptors, which means that you must always usesendandrecvon sockets rather than the standard I/O operators.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sethostent
- Inhaltsvorschausethostentsethostent stayopenOpens the hosts file (usually /etc/hosts on Unix systems) and resets the "current" selection to the top of the file. stayopen, if nonzero, keeps the file open across calls to other functions. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- setgrent
- InhaltsvorschausetgrentsetgrentOpens the groups file (usually /etc/group on Unix systems) and resets the top of the file as the starting point for any read and/or write functions on the file (with the proper permissions). This function will reset the
getgrentfunction back to retrieve group entries from the start of the group file. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - setnetent
- Inhaltsvorschausetnetentsetnetent stayopenOpens the networks file (usually /etc/group) and resets the "current" selection to the top of the file. stayopen, if nonzero, keeps the file open across calls to other functions. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- setpgrp
- Inhaltsvorschausetpgrpsetpgrp pid, pgrpSets the current process group pgrp for the specified pid (use a pidof
0for the current process). Invokingsetpgrpwill produce a fatal error if used on a machine that doesn't implementsetpgrp(2). Some systems will ignore the arguments you provide and always dosetpgrp(0, $$). Fortunately, those are the arguments you usually provide. (For better portability, use thesetpgid( )function in the POSIX module, or if you're really just trying to daemonize your script, consider thePOSIX::setsid( )function as well.)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - setpriority
- Inhaltsvorschausetprioritysetpriority which, who, prioritySets the current priority for a process, a process group, or a user. which must indicate one of these types:
PRIO_PROCESS,PRIO_PGRP, orPRIO_USER. who, therefore, identifies the specific process, process group, or user with its ID. priority is an integer number that will be added to or subtracted from the current priority; the lower the number, the higher the priority. The interpretation of a given priority may vary from one operating system to the next. Seesetpriorityon your system. Invokingsetprioritywill produce a fatal error if used on a machine that doesn't implementsetpriority.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - setprotoent
- Inhaltsvorschausetprotoentsetprotoent stayopenOpens the prototypes file (usually /etc/prototypes) and resets the "current" selection to the top of the file. stayopen, if nonzero, keeps the file open across calls to other functions. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- setpwent
- InhaltsvorschausetpwentsetpwentOpens the password file (usually /etc/passwd) and resets the top of the file as the starting point for any read and/or write functions on the file (with the proper permissions). This function will reset the
getpwentfunction back to retrieve group entries from the start of the group file. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - setservent
- Inhaltsvorschausetserventsetservent stayopenOpens the services file (usually /etc/services) and resets the "current" selection to the top of the file. stayopen, if nonzero, keeps the file open across calls to other functions. Not implemented on Win32 systems.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- setsockopt
- Inhaltsvorschausetsockoptsetsockopt socket, level, optname, optvalSets the socket option requested (optname) to the value optval. The function returns undefined if there is an error. optval may be specified as
undefif you don't want to pass an argument. level specifies the protocol type used on the socket.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - shift
- Inhaltsvorschaushiftshift @arrayRemoves the first value of
@array and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, the function returns the undefined value. If@array is omitted, the function shifts@ARGV(in the main program), or@_(in subroutines). See also unshift , push , pop , and splice . Theshiftandunshiftfunctions do the same thing to the left end of an array thatpopandpushdo to the right end.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - shmctl
- Inhaltsvorschaushmctlshmctl id, cmd, argCalls the System V IPC system call,
shmctl(2), for performing operations on shared memory segments. If cmd is&IPC_STAT, then arg must be a variable that will hold the returnedshmid_dsstructure. The function returns likeioctl: the undefined value for error,"0 but true"for0, or the actual return value otherwise. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "shm.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - shmget
- Inhaltsvorschaushmgetshmget key, size, flagsCalls the System V IPC system call,
shmget(2). The function returns the shared memory segment ID, or the undefined value if there is an error. On error, it puts the error code into$!. Before calling, you should say:require "ipc.ph"; require "shm.ph";
This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - shmread
- Inhaltsvorschaushmreadshmread id, var, pos, sizeReads from the shared memory segment id starting at position pos for size size (by attaching to it, copying out, and detaching from it). var must be a variable that will hold the data read. The function returns true if successful or false if there is an error. On error, it puts the error code into
$!. This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - shmwrite
- Inhaltsvorschaushmwriteshmwrite id, string, pos, sizeWrites to the shared memory segment ID starting at position pos for size size (by attaching to it, copying in, and detaching from it). If string is too long, only size bytes are used; if string is too short, nulls are written to fill out size bytes. The function returns true if successful or false if there is an error. On error, it puts the error code into
$!. This function is available only on machines supporting System V IPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - shutdown
- Inhaltsvorschaushutdownshutdown socket, howShuts down a socket connection in the manner indicated by how. If how is
0, further receives are disallowed. If how is1, further sends are disallowed. If how is2, everything is disallowed.This function will not shut down your system; you'll have to execute an external program to do that. See system .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sin
- Inhaltsvorschausinsin numReturns the sine of num (expressed in radians). If num is omitted, it returns the sine of
$_.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sleep
- Inhaltsvorschausleepsleep nCauses the script to sleep for n seconds, or forever if no argument is given. It may be interrupted by sending the process a
SIGALRM. The function returns the number of seconds actually slept. On some systems, the function sleeps till the "top of the second." So, for instance, asleep 1may sleep anywhere from 0 to 1 second, depending on when in the current second you started sleeping.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - socket
- Inhaltsvorschausocketsocket socket, domain, type, protocolOpens a socket of the specified kind and attaches it to filehandle socket. domain, type, and protocol are specified the same as for
socket(2). Before using this function, your program should contain the line:use Socket;
This setting gives you the proper constants. The function returns true if successful.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - socketpair
- Inhaltsvorschausocketpairsocketpair sock1, sock2, domain, type, prtclCreates an unnamed pair of sockets in the specified domain and of the specified type. domain, type, and protocol are specified the same as for
socketpair(2). Ifsocketpairis unimplemented, invoking this function yields a fatal error. The function returns true if successful.This function is typically used just before afork. One of the resulting processes should close sock1, and the other should close sock2. You can use these sockets bidirectionally, unlike the filehandles created by thepipefunction.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sort
- Inhaltsvorschausortsort [code] listSorts a list and returns the sorted list value. By default (without a code argument), it sorts in standard string comparison order (undefined values sorting before defined null strings, which sort before everything else). code, if given, may be the name of a subroutine or a code block (anonymous subroutine) that defines its own comparison mechanism for sorting elements of list. The routine must return to the
sortfunction an integer less than, equal to, or greater than 0, depending on how the elements of the list will be ordered. (The handy<=>andcmpoperators can be used to perform three-way numeric and string comparisons.)The normal calling code for subroutines is bypassed, with the following effects: the subroutine may not be a recursive subroutine, and the two elements to be compared are passed into the subroutine as$aand$b, not via@_. The variables$aand$bare passed by reference, so don't modify them in the subroutine.Do not declare$aand$bas lexical variables (withmy). They are package globals (though they're exempt from the usual restrictions on globals when you're usingusestrict). However, you do need to make sure yoursortroutine is in the same package, or else you must qualify$aand$bwith the package name of the caller.In versions preceding 5.005, Perl'ssortis implemented in terms of C'sqsort(3)function. Someqsort(3)versions will dump core if your sort subroutine provides inconsistent ordering of values. As of 5.005, however, this is no longer true.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - splice
- Inhaltsvorschausplicesplice @array, pos, [n], [list]Removes n number of elements from
@array starting at position pos, replacing them with the elements of list, if provided. The function returns the elements removed from the array. The array grows or shrinks as necessary. If n is omitted, the function removes everything from posonward.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - split
- Inhaltsvorschausplitsplit /pattern/, string, [limit]Scans a string for delimiters that match pattern and splits the string into a list of substrings, returning the resulting list value in list context, or the count of substrings in scalar context. The delimiters are determined by repeated pattern matching, using the regular expression given in pattern, so the delimiters may be of any size and need not be the same string on every match. If the pattern doesn't match at all,
splitreturns the original string as a single substring. If it matches once, you get two substrings, and so on.If limit is specified and is not negative, the function splits into no more than that many fields. If limit is negative, it is treated as if an arbitrarily large limit has been specified. If limit is omitted, trailing null fields are stripped from the result (which potential users ofpopwould do well to remember). Ifstringis omitted, the function splits the$_string. If patternis also omitted, the function splits on whitespace,/\s+/, after skipping any leading whitespace.If the pattern contains parentheses, then the substring matched by each pair of parentheses is included in the resulting list, interspersed with the fields that are ordinarily returned. Here's a simple case:split /([-,])/, "1-10,20";
This produces the list value:(1, '-', 10, ',', 20)
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sprintf
- Inhaltsvorschausprintfsprintf format, listReturns a string formatted by the
printfconventions. The format string contains text with embedded field specifiers into which the elements of list are substituted, one per field. Field specifiers are roughly of the form:%m.nxin which m and n are optional sizes with interpretation that depends on the type of field, and xis one of the following:CodeMeaning%Percent signcCharacterdDecimal integereExponential format floating-point numberEExponential format floating-point number with uppercase EfFixed-point format floating-point numbergEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sqrt
- Inhaltsvorschausqrtsqrt numReturns the square root of num, or
$_if omitted. For other roots such as cube roots, you can use the**operator to raise something to a fractional power.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - srand
- Inhaltsvorschausrandsrand exprSets the random number seed for the
randoperator so thatrandcan produce a different sequence each time you run your program. If expr is omitted, a default seed is used that is a mix of difficult-to-predict, system-dependent values. If you callrandand haven't calledsrand,randcallssrandwith the default seed.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - stat
- Inhaltsvorschaustatstat fileReturns a 13-element list giving the statistics for a file, indicated by either a filehandle or an expression that gives its name. It's typically used as follows:
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat $filename;Not all fields are supported on all filesystem types. Here are the meanings of the fields:FieldMeaningdevDevice number of filesysteminoInode numbermodeFile mode (type and permissions)nlinkNumber of (hard) links to the fileuidNumeric user ID of file's ownergidNumeric group ID of file's ownerrdevEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - study
- Inhaltsvorschaustudystudy scalarThis function takes extra time to study scalar(
$_if unspecified) in anticipation of doing many pattern matches on the string before it is next modified. You may have only onestudyactive at a time—if you study a different scalar, the first is "unstudied."Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sub
- Inhaltsvorschausubsub name [proto] {block} sub [proto] nameDeclares and defines a subroutine. name is the name given to the subroutine; block is the code that will be executed when the subroutine is called. Without block, this statement declares only a subroutine, which must be defined at a later point in your program. proto is a sequence of symbols that places constraints on the arguments that the subroutine will receive. See Section 4.7.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- substr
- Inhaltsvorschausubstrsubstr string, pos, [n, replacement]Extracts and returns a substring n characters long, starting at character position pos, from a given string. If pos is negative, the substring starts that far from the end of the string instead. If n is omitted, everything to the end of the string is returned. If n is negative, the length is calculated to leave that many characters off the end of the string.You can use
substr( )as an lvalue—replacing the delimited substring with a new string—if string is given as an lvalue. You can also specify a replacement string in the fourth parameter to replace the substring. The original extracted substring is still returned.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - symlink
- Inhaltsvorschausymlinksymlink oldfile, newfileCreates a new filename symbolically linked to the old filename. The function returns
1for success,0otherwise. On systems that don't support symbolic links, it produces a fatal error at runtime. Be careful if you supply a relative symbolic link, since it will be interpreted relative to the location of the symbolic link itself, not your current working directory. See also link and readlink .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - syscall
- Inhaltsvorschausyscallsyscall listCalls the system call specified as the first element of the list, passing the remaining elements as arguments to the system call. The function produces a fatal error if
syscall(2)is unimplemented. The arguments are interpreted as follows: if a given argument is numeric, the argument is passed as a C integer. If not, a pointer to the string value is passed.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sysopen
- Inhaltsvorschausysopensysopen filehandle, filename, mode, [perms]Opens the file given by filename and associates it with filehandle. This function calls
open(2)with the parameters filename, mode, and perms.The possible values and flag bits of the mode parameter are system-dependent; they are available via the Fcntl library module. However, for historical reasons, some values are universal:0means read-only,1means write-only, and2means read/write.If the file named by filename does not exist, andsysopencreates it (typically because mode includes theO_CREATflag), then the value of perms specifies the permissions of the newly created file. If perms is omitted, the default value is0666, which allows read and write for all. This default is reasonable. See umask .The FileHandle module provides a more object-oriented approach tosysopen. See also open .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sysread
- Inhaltsvorschausysreadsysread filehandle, scalar, length, [offset]Reads length bytes of data into variable scalar from the specified filehandle. The function returns the number of bytes actually read, or
0at end-of-file. It returns the undefined value on error. scalar will grow or shrink to the length actually read. The offset, if specified, says where in the string to start putting the bytes so you can read into the middle of a string that's being used as a buffer. You should be prepared to handle the problems (such as interrupted system calls) that standard I/O normally handles for you.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sysseek
- Inhaltsvorschausysseeksysseek filehandle, offset, whenceA variant of
seek( )that sets and gets the file's system read/write position using thelseek(2)system call. It's the only reliable way to seek before asysread( )orsyswrite( ). Returns the new position, orundefon failure. Arguments are the same as forseek.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - system
- Inhaltsvorschausystemsystem listExecutes any program on the system for you. It does exactly the same thing as
execlist except that it does aforkfirst, and then, after theexec, it waits for theexeced program to complete. That is, it runs the program for you and returns when it's done, unlikeexec, which never returns (if it succeeds). Note that argument processing varies depending on the number of arguments, as described forexec. The return value is the exit status of the program as returned by thewait(2)call. To get the actual exit value, divide by 256. (The lower eight bits are set if the process died from a signal.) See exec .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - syswrite
- Inhaltsvorschausyswritesyswrite filehandle, scalar, length, [offset]Writes length bytes of data from variable scalar to the specified filehandle. The function returns the number of bytes actually written, or the undefined value on error. You should be prepared to handle the problems that standard I/O normally handles for you, such as partial writes. The offset, if specified, says where in the string to start writing from, in case you're using the string as a buffer, for instance, or need to recover from a partial write.Do not mix calls to
print(orwrite) andsyswriteon the same filehandle unless you really know what you're doing.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - tell
- Inhaltsvorschautelltell filehandleReturns the current file position (in bytes,
0-based) for filehandle. This value is typically fed to theseekfunction at a future time to get back to the current position. If filehandle is omitted, the function returns the position of the last file read. File positions are only meaningful on regular files. Devices, pipes, and sockets have no file position.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - telldir
- Inhaltsvorschautelldirtelldir dirhandleReturns the current position of the
readdirroutines on a directory handle (dirhandle). This value may be given toseekdirto access a particular location in a directory. The function has the same caveats about possible directory compaction as the corresponding system library routine. This function may not be implemented everywhere thatreaddiris. Even if it is, no calculation may be done with the return value. It's just an opaque value, meaningful only toseekdir.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - tie
- Inhaltsvorschautietie variable, classname, listBinds a variable to a package class, classname, that will provide the implementation for the variable. Any additional arguments (list) are passed to the "new" method of the class (meaning
TIESCALAR,TIEARRAY, orTIEHASH). Typically, these are arguments that might be passed to thedbm_open(3)function of C, but this is package-dependent. The object returned by the "new" method is also returned by thetiefunction, which can be useful if you want to access other methods in classname. (The object can also be accessed through thetiedfunction.)A class implementing a hash should provide the following methods:TIEHASH $class, LIST DESTROY $self FETCH $self, $key STORE $self, $key, $value DELETE $self, $key EXISTS $self, $key FIRSTKEY $self NEXTKEY $self, $lastkeyA class implementing an ordinary array should provide the following methods:TIEARRAY $classname, LIST DESTROY $self FETCH $self, $subscript STORE $self, $subscript, $valueA class implementing a scalar should provide the following methods:TIESCALAR $classname, LIST DESTROY $self FETCH $self, STORE $self, $valueUnlikedbmopen, thetiefunction will notuseorrequirea module for you—you need to do that explicitly yourself.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - tied
- Inhaltsvorschautiedtied variableReturns a reference to the object underlying variable (the same value that was originally returned by the
tiecall that bound the variable to a package). It returns the undefined value if variable isn't tied to a package. So, for example, you can use:ref tied %hash
to find out which package your hash is currently tied to.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - time
- InhaltsvorschautimetimeReturns the number of non-leap seconds since January 1, 1970, UTC. The returned value is suitable for feeding to
gmtimeandlocaltime, for comparison with file modification and access times returned bystat, and for feeding toutime.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - times
- InhaltsvorschautimestimesReturns a four-element list giving the user and system CPU times, in seconds (possibly fractional), for this process and for the children of this process:
($user, $system, $cuser, $csystem) = times;
For example, to time the execution speed of a section of Perl code:$start = (times)[0]; ... $end = (times)[0]; printf "that took %.2f CPU seconds\n", $end - $start;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - truncate
- Inhaltsvorschautruncatetruncate file, lengthTruncates a file (given as a filehandle or by name) to the specified length. The function produces a fatal error if
truncate(2)or an equivalent isn't implemented on your system.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - uc
- Inhaltsvorschauucuc stringReturns an uppercased version of string (or
$_if string is omitted). This is the internal function implementing the\Uescape in double-quoted strings. POSIXsetlocale(3)settings are respected.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ucfirst
- Inhaltsvorschauucfirstucfirst stringReturns a version of string (or
$_if string is omitted) with the first character uppercased. This is the internal function that implements the\uescape in double-quoted strings. POSIXsetlocale(3)settings are respected.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - umask
- Inhaltsvorschauumaskumask exprSets the umask for the process to expr and returns the old one. (The umask tells Unix which permission bits to disallow when creating a file.) If expr is omitted, the function merely returns the current umask. For example, to ensure that the "other" bits are turned on and that the "user" bits are turned off, try something like:
umask((umask( ) & 077) | 7);
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - undef
- Inhaltsvorschauundefundef exprUndefines the value of expr, which must be an lvalue. Use only on a scalar value, an entire array or hash, or a subroutine name (using the
&prefix). Any storage associated with the object will be recovered for reuse (though not returned to the system, for most versions of Unix). Theundeffunction will probably not do what you expect on most special variables. The function always returns the undefined value. This is useful because you can omit the expr, in which case nothing gets undefined, but you still get an undefined value that you could, for instance, return from a subroutine to indicate an error.You may useundefas a placeholder on the left side of a list assignment, in which case the corresponding value from the right side is simply discarded. Apart from that, you may not useundefas an lvalue.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - unlink
- Inhaltsvorschauunlinkunlink listDeletes a list of files. (Under Unix, it will remove a link to a file, but the file may still exist if another link references it.) If list is omitted, it unlinks the file given in
$_. The function returns the number of files successfully deleted. Note thatunlinkwill not delete directories unless you are the superuser and the -U flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict serious damage on your filesystem. Usermdirinstead.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - unpack
- Inhaltsvorschauunpackunpack template, stringTakes a string (string) representing a data structure and expands it into a list value, returning the list value. (
unpackdoes the reverse ofpack.) In a scalar context, it can be used to unpack a single value. The template has much the same format as thepackfunction—it specifies the order and type of the values to be unpacked. See pack for a more detailed description of template.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - unshift
- Inhaltsvorschauunshiftunshift @array, listPrepends the elements of list to the front of the array and returns the new number of elements in the array.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- untie
- Inhaltsvorschauuntieuntie variableBreaks the binding between a variable and a package. See tie .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- use
- Inhaltsvorschauuseuse Module list use version use Module version listIf the first argument is a number, it is treated as a version number. If the version of Perl is less than version, an error message is printed and Perl exits. This provides a way to check the Perl version at compilation time instead of waiting for runtime.If version appears between Module and list, then
usecalls theversionmethod in class Module with version as an argument.Otherwise,useimports some semantics into the current package from the named Module, generally by aliasing certain subroutine or variable names into your package. It is exactly equivalent to the following:BEGIN { require Module; import Module list; }TheBEGINforces therequireandimportto happen at compile time. Therequiremakes sure that the module is loaded into memory if it hasn't been yet. Theimportis not a built-in function—it's just an ordinary static method call into the package named by Module that tells the module to import the list of features back into the current package. The module can implement its import method any way it likes, though most modules just choose to derive their import method via inheritance from the Exporter class defined in the Exporter module.If you don't want your namespace altered, explicitly supply an empty list:use Module ( );This is exactly equivalent to the following:BEGIN { require Module; }Because this is a wide-open interface, pragmas (compiler directives) are also implemented this way. (See Chapter 8 for descriptions of the currently implemented pragmas.) These pseudomodules typically import semantics into the current block scope, unlike ordinary modules, which import symbols into the current package. (The latter are effective through the end of the file.)There's a corresponding declaration,no, that "unimports" any meanings originally imported byusebut have since become less important:no integer; no strict 'refs';
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - utime
- Inhaltsvorschauutimeutime atime, mtime, filesChanges the access time (atime) and modification time (mtime) on each file in a list of files. The first two elements must be the numerical access and modification times, in that order. The function returns the number of files successfully changed. The inode change time of each file is set to the current time. Here's an example of a
utimecommand:#!/usr/bin/perl $now = time; utime $now, $now, @ARGV;
To read the times from existing files, usestat.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - values
- Inhaltsvorschauvaluesvalues %hashReturns a list consisting of all the values of the named hash. The values are returned in an apparently random order, but it is the same order that the
keysoreachfunction would produce on the same hash. To sort the hash by its values, see the example under keys . Note that usingvalueson a hash bound to a very large DBM file will produce a very large list, causing you to have a very large process, and leaving you in a bind. You might prefer to use theeachfunction, which will iterate over the hash entries one by one without reading them all into a single list.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - vec
- Inhaltsvorschauvecvec string, offset, bitsTreats a string as a vector of unsigned integers and returns the value of the element specified by offset and bits. The function may also be assigned to, which causes the element to be modified. The purpose of the function is to provide compact storage of lists of small integers. The integers may be very small—vectors can hold numbers that are as small as one bit, resulting in a bitstring.The offset specifies the number of elements to skip over to find the one you want. bits is the number of bits per element in the vector, so each element can contain an unsigned integer in the range
0..(2**bits)-1. bits must be one of1,2,4,8,16, or32. As many elements as possible are packed into each byte, and the ordering is such thatvec($vectorstring,0,1)is guaranteed to go into the lowest bit of the first byte of the string. To find the position of the byte in which an element will be placed, you have to multiply the offset by the number of elements per byte. When bits is1, there are eight elements per byte. When bits is2, there are four elements per byte. When bits is4, there are two elements (called nybbles) per byte. And so on.Regardless of whether your system is big-endian or little-endian,vec($foo, 0, 8)always refers to the first byte of string$foo. See select for examples of bitmaps generated withvec.Vectors created withveccan also be manipulated with the logical operators|,&,^, and~, which will assume a bit vector operation is desired when the operands are strings. A bit vector (bits== 1) can be translated to or from a string of1s and0s by supplying ab*template tounpackorpack. Similarly, a vector of nybbles (bits== 4) can be translated with anh*template.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - wait
- InhaltsvorschauwaitwaitWaits for a child process to terminate and returns the pid of the deceased process, or
-1if there are no child processes. The status is returned in$?. If you get zombie child processes, you are probably calling either this function orwaitpid. A common strategy to avoid such zombies is:$SIG{CHLD} = sub { wait };If you expected a child and didn't find it, you probably had a call tosystem, a close on a pipe, or backticks between theforkand thewait. These constructs also do await(2)and may have harvested your child process. Usewaitpidto avoid this problem.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - waitpid
- Inhaltsvorschauwaitpidwaitpid pid, flagsWaits for a particular child process pid to terminate and returns the pid when the process is dead, or
-1if there are no child processes or if the flags specify nonblocking and the process isn't dead yet. The status of the dead process is returned in$?. To get valid flag values, do the following:use POSIX "sys_wait_h";
On systems that implement neither thewaitpid(2)nor thewait4(2)system call, flags may be specified only as0. In other words, you can wait for a specific pid, but you can't do it in nonblocking mode.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - wantarray
- InhaltsvorschauwantarraywantarrayReturns true if the context of the currently executing subroutine is looking for a list value. The function returns false if the context is looking for a scalar. May also return
undefif a subroutine's return value will not be used at all.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - warn
- Inhaltsvorschauwarnwarn msgProduces a message on STDERR just like
die, but doesn't try to exit or throw an exception. For example:warn "Debug enabled" if $debug;
If the message supplied is null, the message"Something's wrong"is used. As withdie, a message not ending with a newline will have file and line number information automatically appended. Thewarnoperator is unrelated to the -w switch.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - write
- Inhaltsvorschauwritewrite filehandleWrites a formatted record (possibly multiline) to the specified filehandle, using the format associated with that filehandle (see Section 4.11). By default, the format for a filehandle is the one having the same name as the filehandle.If filehandle is unspecified, output goes to the current default output filehandle, which starts as STDOUT but may be changed by the
selectoperator. If the filehandle is an expression, then the expression is evaluated to determine the actual filehandle at runtime.Note thatwriteis not the opposite ofread. Useprintfor simple string output. If you want to bypass standard I/O, see syswrite .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 6: Debugging
- InhaltsvorschauOf course everyone writes perfect code on the first try, but on those rare occasions when something goes wrong, and you're having trouble with your Perl script, there are several things you can do:
- Run the script with the -w switch, which prints warnings about possible problems in your code.
- Use the Perl debugger.
- Use another debugger, or a profiler such as the Devel::DProf module.
The major focus of this chapter is the Perl debugger, which provides an interactive Perl environment. The chapter also describes the DProf module and the dprofpp program that comes with it; together they can provide you with a profile of your Perl script. If you've ever used any debugger, and you understand concepts such as breakpoints and backtraces, you'll have no trouble learning to use the Perl debugger. Even if you haven't used another debugger, the command descriptions and some experimenting should get you going.To run your script under the Perl source debugger, invoke Perl with the -d switch:perl -d myprogram
This works like an interactive Perl environment, prompting for debugger commands that let you examine source code, set breakpoints, get stack backtraces, change the values of variables, etc. If your program takes any switches or arguments, you must include them in the command:perl -d myprogram myinput
In Perl, the debugger is not a separate program as it is in the typical compiled environment. Instead, the -d flag tells the compiler to insert source information into the parse trees it's about to hand off to the interpreter. This means your code must compile correctly for the debugger to work on it—the debugger won't run until you have fixed all compiler errors.After your code has compiled, and the debugger has started up, the program halts right before the first runtime executable statement (see Section 6.3 regarding compile time statements) and waits for you to enter a debugger command. Whenever the debugger halts and shows you a line of code, it always displays the line it's about to execute, rather than the one it has just executed.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The Perl Debugger
- InhaltsvorschauTo run your script under the Perl source debugger, invoke Perl with the -d switch:
perl -d myprogram
This works like an interactive Perl environment, prompting for debugger commands that let you examine source code, set breakpoints, get stack backtraces, change the values of variables, etc. If your program takes any switches or arguments, you must include them in the command:perl -d myprogram myinput
In Perl, the debugger is not a separate program as it is in the typical compiled environment. Instead, the -d flag tells the compiler to insert source information into the parse trees it's about to hand off to the interpreter. This means your code must compile correctly for the debugger to work on it—the debugger won't run until you have fixed all compiler errors.After your code has compiled, and the debugger has started up, the program halts right before the first runtime executable statement (see Section 6.3 regarding compile time statements) and waits for you to enter a debugger command. Whenever the debugger halts and shows you a line of code, it always displays the line it's about to execute, rather than the one it has just executed.Any command not recognized by the debugger is directly executed as Perl code in the current package. To be recognized by the debugger, the command must start at the beginning of the line; otherwise, the debugger assumes it's for Perl.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Debugger Commands
- InhaltsvorschauThe debugger understands the following commands.
--Lists the previous few lines...Returns debugger pointer to the last-executed line and prints it out./pattern//pattern/Searches forward for pattern; final/is optional.?pattern??pattern?Searches backward for pattern; final?is optional.<< [command]Sets a Perl command to run before every debugger prompt. A multiline command may be entered by backslashing the newlines. With no command, the list of actions is reset.<<<< [command]Adds to the list of Perl commands to run before each debugger prompt.<CR><CR>Repeats lastnorscommand.>> [command]Sets a Perl command to run after the prompt when you've just given a command to return to executing the script. A multiline command may be entered by backslashing the newlines.>>>> [command]Adds to the list of Perl commands to run after each debugger prompt.{{ [commandline]Sets a debugger command to run before each prompt.{{{{ [commandline]Adds to the list of debugger commands to run before each prompt.!! [number]Reruns a previous command (defaults to the last command executed).!! -numberReruns numberth-to-last command.!! patternReruns last command that started with pattern. SeeO recallCommand.!!!! cmdRuns cmd in a subprocess (which reads from DB::IN and writes to DB::OUT). SeeOshellBang.|| dbcmdRuns specified debugger command, piping DB::OUT toEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Using the Debugger
- InhaltsvorschauIf you have any compile time executable statements (code within a
BEGINblock or ausestatement), they are not stopped by the debugger, althoughrequires are.The debugger prompt is something like this:DB<8>
or even this:DB<<17>>
The number in angle brackets is the command number. A csh-like history mechanism lets you access previous commands by number. For example,!17repeats command number 17. The number of angle brackets indicates the depth of the debugger. You get more than one set of brackets, for example, if you're already at a breakpoint and print out the result of a function call that itself also has a breakpoint.If you want to enter a multiline command, such as a subroutine definition with several statements, you can use a backslash to escape the newline that would normally end the debugger command:DB<1> sub foo { \ cont: print "fooline\n"; \ cont: } DB<2> foo foolineYou can maintain limited control over the Perl debugger from within your Perl script. You might do this, for example, to set an automatic breakpoint at a certain subroutine whenever a particular program is run under the debugger. Setting$DB::singleto1causes execution to stop at the next statement, as though you'd used the debugger'sscommand. Setting$DB::singleto2is equivalent to typing thencommand, and the$DB::tracevariable can be set to1to simulate thetcommand.Once you are in the debugger, you can terminate the session by enteringqor Ctrl-D at the prompt. You can also restart the debugger withR.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Customizing the Debugger
- InhaltsvorschauYou can do some customizing by setting up a .perldb file with initialization code. When it starts up, the debugger reads and processes this file. For instance, you can set up aliases such as these:
$DB::alias{'len'} = 's/^len(.*)/p length($1)/'; $DB::alias{'stop'} = 's/^stop (at|in)/b/'; $DB::alias{'ps'} = 's/^ps\b/p scalar /'; $DB::alias{'quit'} = 's/^quit\b.*/exit/';You can also use this file to set options and define a subroutine,&afterinit, to be executed after the debugger is initialized.After the configuration file has been processed, the debugger consults the environment variable PERLDB_OPTS and parses its contents as arguments to theOopt=valdebugger command.While any options can be set in PERLDB_OPTS, the following options can only be specified at startup. If you want to set them in your configuration file, call&parse_options("opt=val").-
TTY - The TTY to use for debugging I/O.
-
noTTY - If set, goes in NonStop mode. On an interrupt, if TTY is not set, it uses the value of
noTTYor /tmp/perldbtty$$ to find the TTY using Term::Rendezvous. The current variant is to have the name of the TTY in this file. -
ReadLine - If false, a dummy
ReadLineis used so you can debug ReadLine applications. -
NonStop - If true, no interaction is performed until an interrupt.
-
LineInfo - File or pipe to print line number information to. If it's a pipe, then a short, emacs-like message is used.
For example, if you create the following .perldb file:&parse_options("NonStop=1 LineInfo=db.out"); sub afterinit { $trace = 1; }your script will run without human intervention, putting trace information into the file db.out .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Perl Profiler
- InhaltsvorschauYou can supply an alternative debugger for Perl to run by invoking your script with the -d:module switch. One of the most popular alternative debuggers for Perl is DProf, the Perl profiler. As of this writing, DProf is not included with the standard Perl distribution, but it is expected to be included soon.Meanwhile, you can fetch the Devel::DProf module from CPAN. Once it has been properly installed on your system, you can use it to profile the Perl program in testpgm by typing:
perl -d:DProf testpgm
As your script runs, DProf gathers profile information. When the script terminates, the profiler dumps the gathered information to a file called tmon.out. A tool such as dprofpp, which is supplied with the Devel::DProf package, can be run to interpret the profile. If you run dprofpp against the tmon.out file created by DProf in the example above, you'll see something like the following:% dprofpp tmon.out Total Elapsed Time = 0.15 Seconds User+System Time = 0.1 Seconds Exclusive Times %Time Seconds # Calls sec/call Name 30.0 0.030 1 0.0300 Text::Wrap::CODE(0x175f08) 20.0 0.020 1 0.0200 main::CODE(0xc7880) 20.0 0.020 1 0.0200 main::CODE(0xfe480) 10.0 0.010 1 0.0100 Text::Wrap::CODE(0x17151c) 10.0 0.010 10 0.0010 Text::Tabs::expand 0.00 0.000 1 0.0000 lib::CODE(0xfe5b8) 0.00 0.000 3 0.0000 Exporter::export 0.00 0.000 1 0.0000 Config::FETCH 0.00 0.000 1 0.0000 lib::import 0.00 0.000 1 0.0000 Text::Wrap::CODE(0x171438) 0.00 0.000 3 0.0000 vars::import 0.00 0.000 3 0.0000 Exporter::import 0.00 0.000 2 0.0000 strict::import 0.00 0.000 1 0.0000 Text::Wrap::CODE(0x171684) 0.00 0.000 1 0.0000 lib::CODE(0xfe4d4)
The output shows the 15 subroutines that use the most time; you can then focus your efforts on those subroutines where tuning the code will have the greatest effect. This output is an example of running theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The perlbug Program
- InhaltsvorschauAs you develop and debug your own code, it's possible that you'll run into a bug in Perl itself. If you do, the best way to report it is with the perlbug program. perlbug is a Perl program designed to automate the process of reporting bugs in the Perl standard distribution and the standard modules. It works interactively, prompting you for the information needed and generating an email message addressed to perlbug@perl.com. (If the bug you found is in one of the nonstandard Perl ports, see the documentation for that port to find out how to report bugs.) When you run perlbug, it prompts you to include all relevant information, making it easier for the Perl developers to reproduce and track down the bug. If you come up with a patch to resolve the problem, include that too.Don't use perlbug to get help debugging your code (for that, see the list of newsgroups and other resources in Chapter 1). But if you believe you've found a bug in Perl itself, perlbug is the way to report it.To run perlbug, simply enter the command with any options you want to include. For example:
% perlbug -t
The possible options are:- -a address
- Email address to send report to. Default is perlbug@perl.com.
- -b body
- Body of report. If not included on the command line or in a file, you are given a chance to edit it.
- -C
- Don't send a copy to your Perl administrator.
- -c address
- Email address where copy should be sent. Default is your Perl administrator.
- -d
- Data mode. (The default if you redirect or pipe input.) Prints your configuration data, without mailing anything. Use with -v to get more complete data.
- -e editor
- Editor to use. Defaults to your default editor or to
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 7: Packages, Modules, and Objects
- InhaltsvorschauOver the years, Perl has evolved from a utilitarian scripting tool into a sophisticated object-oriented programming language. Many people continue to use Perl just for simple scripts, and Perl will continue to make simple tasks easy. However, Perl can also make difficult tasks possible by writing reusable code and using object-oriented programming techniques.This chapter explains what Perl modules are and how to use them in your programs. Modules are written to accomplish tasks that either aren't implemented by Perl's built-in functions, or that could be done better. We say modules are "reusable" because anyone who needs to accomplish the same task can use that module instead of writing the code from scratch. As you write more and more Perl code, you'll undoubtedly find yourself using many of the modules other Perl programmers have provided. You may also find yourself writing modules and making them available for others to use.The remainder of this book describes a significant portion of the functionality that's present in publicly available Perl modules. You'll find that a number of standard or core modules are distributed with Perl; many of these modules are discussed in Chapter 8. Scores of other modules are available on CPAN, and virtually any task you'd like to accomplish in Perl is implemented in a module found there. For unbundled modules, you'll need to install the module on your system and integrate it into your program with the
usefunction.Theusefunction is often the key to working with modules. For example, to bring the functionality of the popular CGI module into your program, you need to install the CGI.pm module (the .pm stands for Perl module) and put this line near the top of your program:use CGI;
Now your program can use the many functions and variables made available by the CGI module.Packages (from which modules are built) are also a mechanism by which Perl's object-oriented features are implemented. But object-oriented programming isn't for everyone, and there's nothing in packages that forces the programmer to work with the object-oriented paradigm.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Namespaces and Packages
- InhaltsvorschauA namespace does what it says: it stores names (or identifiers), including names of variables, subroutines, filehandles, and formats. Each namespace has its own symbol table, which is basically a hash with a key for each identifier.The default namespace for programs is
main, but you can define other namespaces and variables and use them in your program. Variables in different namespaces can even have the same name, but they are completely distinct from one another.In Perl, a namespace is held in a package. By convention, package names start with a capital letter, and you should follow that convention when you create your own packages.Each package starts with apackagedeclaration. Thepackagecall takes one argument: the name of the package. Within the scope of a package declaration, all regular identifiers are created within that package (except formyvariables).From inside one package, you can refer to variables from another package by "qualifying" them with the package name. To do this, place the name of the package followed by two colons (::) before the identifier's name, e.g.,$Package::varname.If the package name is null, themainpackage is assumed. For example,$varand$::varare the same as$main::var.Packages may be nested inside other packages. However, the package name must still be fully qualified. For example, if the packageProvinceis declared inside the packageNation, a variable in the Province package is called as$Nation::Province::var. You cannot use a "relative" package name such as$Province::varwithin theNationpackage for the same thing.The defaultmainnamespace contains all other packages within it .Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Modules
- InhaltsvorschauA module is a package defined in a file with a name that is the same as the package's. Perl locates modules by searching the
@INCarray, which contains a list of library directories. Perl's use of@INCis roughly comparable to the Unix shell's use of the PATH environment variable to locate executable programs.@INCis defined when Perl is built and can be supplemented with the -I command-line option to Perl or withuse libwithin a program.When you refer toModuleNamein your program, Perl searches in the directories listed in@INCfor the module file ModuleName.pm and uses the first one it finds. When you refer to a module embedded in another package, such asParentPackage::ModuleName, Perl looks for a ParentPackage/ subdirectory in the@INCpath, and for a ModuleName.pm file in that subdirectory.Every Perl installation includes a central lib directory. The actual pathname of this directory varies from system to system, but it's commonly /usr/lib/perl or /usr/local/lib/perl. Looking at the central lib directory for your Perl distribution, you'll see something like this:% ls -aF /usr/local/lib/perl ./ I18N/ bigfloat.pl less.pm ../ IO/ bigint.pl lib.pm AnyDBM_File.pm IPC/ bigrat.pl locale.pm AutoLoader.pm Math/ blib.pm look.pl AutoSplit.pm Net/ cacheout.pl man/ Benchmark.pm Pod/ chat2.pl newgetopt.pl Bundle/ Search/ complete.pl open2.pl CGI/ SelectSaver.pm constant.pm open3.pl CGI.pm SelfLoader.pm ctime.pl perl5db.pl CPAN/ Shell.pm diagnostics.pm pod/ CPAN.pm Symbol.pm dotsh.pl pwd.pl Carp.pm Sys/ dumpvar.pl shellwords.pl ...When you request theAnyDBM_Filemodule, it uses AnyDBM_File.pm. When you request theMath::Complexmodule, it looks for Math/Complex.pm.A module can be included in your program withuseorrequire. BothEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Object-Oriented Perl
- InhaltsvorschauIn Perl circles, modules and object-oriented programming are often spoken of in the same breath, but the connection is misleading. The implementation of modules in Perl is object-oriented, but that doesn't mean that the actual modules are objectified. Perl modules don't necessarily involve objects just because the Perl programmer has encapsulated their code in a module.Generally, an object is an instance of a class. So in Perl terms, the object is created by calling a constructor, and will be used to create a new object and a reference to it. (Often, the constructor is named
new, butCreateis also used in Win32 classes.) This reference is a regular scalar variable, except that it refers to an underlying object that knows which class it belongs to. In your programs, you will use the reference to manipulate the object.Methods are subroutines that expect an object reference as a first argument, such as:sub in_class { my $class = shift; # object reference my ($this, $that) = @_; # params }Methods may be invoked like this:PackageName->constructor(args)->method_name(args);
or:$object = PackageName->constructor(args); $object->method_name(args);
Objects have a specific set of available methods within their class, but they also inherit methods from their parent class, if they have one.Objects are destroyed when the last reference to them goes away. You can control this capture before the object is destroyed with theDESTROYmethod. TheDESTROYmethod should be defined somewhere in the class. You do not callDESTROYexplicitly; it will be called at an appropriate time. Object references contained in the current object will be freed when the current object is freed. Most of the time, you won't need to explicitly destroy an object, but there are occasions when you should, such as when you are done with a socket object.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Object Syntax
- InhaltsvorschauPerl uses two forms of syntax for invoking methods on objects. For both types of syntax, the object reference or class name is given as the first argument. A method that takes a class name is called a class method, and one that takes an object reference is called an instance method.Class methods provide functionality for the entire class, not just for a single object that belongs to the class. Class methods expect a class name as their first argument. Following this explanation, a constructor is an example of a class method:
sub new { my $self = {}; bless $self; return $self; }On the other hand, an instance method expects an object reference as its first argument. An instance method will shift the first argument and use this argument as a reference:sub instance_method { my $self = shift; my($one, $two, $three) = @_; # do stuff }Here is an example of a constructor creating a new object and returning a reference:$tri = Triangle::Right->new(side1 => 3, side2 => 4);
This example creates a new right-triangle object and references it with$tri. The parameters are given as a hash-style list. This is common for constructors, since they set initial parameters for an object that is probably just a hash. Now that we have an object, we can invoke a method on it. Suppose Triangle::Right defines a method,hypot, that returns the length of the hypotenuse for a given right-triangle object. It would be used like this:$h = $tri->hypot; print "The hypotenuse is: $h.\n";
In this particular example, there happens to be no additional arguments to thehypotmethod, but there could have been.With the arrow (->) notation, the left side of the arrow must be an object reference or a class name, while the right side of the arrow must be a method defined for that object. Any arguments must follow the method inside of parentheses. For example:$obj->method(args) CLASS->method(args)
You have to use parentheses because this form can't be used as a list operator, although the first type of method syntax can.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 8: Standard Modules
- InhaltsvorschauWe've talked about the extent to which Perl benefits from user contributions. In fact, many contributed modules are so generally useful that they are now distributed with Perl itself. This chapter describes these "standard modules"; if you are running Perl 5.005, all these modules are already available to you. If you are running an earlier version of Perl, and you find that a module you want isn't on your system, or if you simply don't find what you need among the modules in this chapter, check CPAN for one that does what you want.While this chapter primarily covers standard Perl modules called at execution time from your program, it also covers the "pragmatic" modules that affect the compilation phase. (A pragma is a compiler directive that provides hints to the compiler.) By convention, the names of the pragmatic modules are all lowercase, while the names of other modules begin with an uppercase letter and are of mixed case.The Win32-specific modules are not included in this chapter, but are described in Chapter 19.The following table provides a quick look at the standard modules and what they do:ModuleFunctionAnyDBM_FileProvides framework for multiple DBMsAttribute::HandlersSimpler definition of attribute handlers (new in 5.8)attributesSets or gets attributes of a subroutineattrsSets or gets attributes of a subroutine (deprecated)AutoLoaderLoads functions only on demandAutoSplitSplits a module for autoloadingEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- AnyDBM_File
- InhaltsvorschauProvides a single Database Manager (DBM) interface regardless of the DBM implementation you use. The module inherits from the various DBM packages; by default, it inherits from NDBM_File. If it doesn't find NDBM_File, the default search order is: DB_File, GDBM_File, SDBM_File (which comes with Perl), and finally, ODBM_File. You can override this default order by redefining
@ISA:@AnyDBM_File::ISA = qw(DB_File GDBM_File NDBM_File);
However, an explicitusetakes priority over the@ISAordering.Perl'sdbmopenfunction simply callstieto bind a hash to AnyDBM_File. The effect is to bind the hash to one of the specific DBM classes that AnyDBM_File inherits from.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Attribute::Handlers
- InhaltsvorschauImplements a simpler definition of attribute handlers. When inherited by a package, Attribute::Handlers allows that package's class to define handler subroutines for specific attributes. When inherited by a package, these handlers will be called by the same names as the original attribute-handling subroutines. Attribute handlers will be called at one of the following compilation phases: BEGIN, CHECK, INIT, or END blocks. Note that Attribute::Handlers is shipped with the Perl source kit as of Version 5.8.Handlers are defined as subroutines and named as the desired attribute. In the following example, the attribute is
:ATTR, which lives in a subroutine that's calledNate1()in the HandlerBing class:package HandlerBing; use Attribute::Handlers; sub Nate1 :ATTR { my(@attrs) = @_; # We simply want to test by dumping the attributes print "attributes: \n", join("\n", @attrs), "\n"; } # true. 1;This stub for the HandlerBing class creates a handler for the attribute:Nate1. When you want to use this handler while within HandlerBing, you can do the following:sub Nate2 :Nate1 { my (@stuff) = @_; print STDERR "in Nate2 ", join("\n", @stuff), "\n"; }When you callNate2, it invokes theNate1handler and passes the following elements into the@_array:-
0 - The name of the package in which the handler was declared
-
1 - A reference to the symbol table entry (a typeglob) that contains the subroutine
-
2 - A reference to the subroutine
-
3 - The name of the attribute itself
-
4 - Any data associated with that attribute
-
5 - The name of the compilation phase in which the handler was invoked
The same holds true for declaring any variables with the:Nate1attribute within HandlerBing:my $monica :Nate1; my $phoebe :Nate1;
Attribute::Handlers also supports typed lexicals. This is a nice feature, since you can invoke a handler from a package that defines another one from whatever package you're in (or writing!). For example:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- attributes
- InhaltsvorschauReplacement for attrs.pm that sets or gets the attributes of subroutines. Attributes are set at compile time. If an attribute is unrecognized, it will result in a fatal error. While the error is trappable, it will stop the compilation within an
eval. You must be careful about naming your attributes; an attribute that's all lowercase and not a built-in attribute will result in a warning (unless you use warnings "reserved"). An example of attributes is:sub foo : method ; use attributes ( ); # Optional, to get subroutine declarations my @attrlist = attributes::get(\&foo);The built-in attributes are:-
locked - Setting this attribute is meaningful only when the subroutine or method will be called by multiple threads. When set on a method subroutine (i.e., one marked with the
methodattribute), Perl ensures that any invocation of it implicitly locks its first argument before execution. When set on a non-method subroutine, Perl ensures that a lock is taken on the subroutine itself before execution. The semantics of the lock are exactly those of one explicitly taken with the "lock" operator immediately after the subroutine is entered. -
method - Indicates that the referenced subroutine is a method. This has a meaning when taken together with the
lockedattribute. It also means that a subroutine so marked will not trigger the "Ambiguous call resolved as CORE::%s" warning. -
lvalue - Indicates that the referenced subroutine is a valid lvalue and can be assigned to. The subroutine must return a modifiable value such as a scalar variable, as described in the perlsub manpage.
There are no built-in attributes for anything other than subroutines.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- attrs
- InhaltsvorschauSets or gets the attributes of subroutines. Attributes are set for a subroutine at compile time; therefore, setting an invalid attribute results in a compile-time error. Note that attrs has been deprecated. You should use the attributes form instead. During execution, when you call
attrs::geton a subroutine reference or name, it returns the list of attributes that are set. Note thatattrs::getis not exported. The old usage of attrs is as follows:sub test { use attrs qw(locked method); ... } @a = attrs::get(\test);You should use a form like the following instead:sub test : locked method { }You can read more about attributes in the next section.The valid attributes are:-
locked - Meaningful only when the subroutine or method will be called by multiple threads. When set on a subroutine that also has the method attribute set, invoking that subroutine implicitly locks its first argument before execution. On a non-method subroutine, a lock is taken on the subroutine itself before execution. The lock semantics are identical to one taken explicitly with the
lockoperator immediately after entering the subroutine. -
method - The invoking subroutine is a method.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- AutoLoader
- InhaltsvorschauDelays the loading of functions until they are used. Each function is placed in a file that has the same name as the function, with an .al extension. The files are stored in a subdirectory of the auto/ directory that is named after the package. For example, the function
GoodStuff::whateveris loaded from the file auto/GoodStuff/whatever.al. Should always beused and notrequired.A module using the AutoLoader has the special marker,_ _END_ _prior to the declarations for the subroutine to be autoloaded. Any code before this marker is loaded and compiled when the module is used, but at the marker, Perl stops parsing the file.Later, during execution, when a subroutine that isn't yet in memory is called, theAUTOLOADfunction attempts to find it in a directory relative to the location of the module file. For example, if POSIX.pm is in the directory /usr/local/lib/perl5, then AutoLoader looks for POSIX subroutines in /usr/local/lib/perl5/auto/POSIX/*.al.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - AutoSplit
- InhaltsvorschauSplits a program or module into files that the AutoLoader can handle. It can be called from a program or from the command line:
# From a program use AutoSplit; autosplit_modules(@ARGV) # From the command line perl -MAutoSplit -e 'autosplit(FILE, DIR, KEEP, CHECK, MODTIME)' ... # Another interface perl -MAutoSplit -e 'autosplit_lib_modules(@ARGV)' ...AutoSplit is used by MakeMaker as well as by the standard Perl libraries. It operates on a file, splitting off subroutines that come after the_ _END_ _marker and storing them as described above for AutoLoader, creating any necessary directories along the way. AutoSplit has two functions.autosplitautosplit (file, dir, keep, check, modtime)Splits the module into files. Each file is given the name of the subroutine it contains, with .al appended.autosplitalso creates the file autosplit.ix, which serves as both a forward declaration of all package routines and as a timestamp showing when the hierarchy was last updated. Takes the following arguments:- file
- Filename of program or module to be split.
- dir
- Name of directory hierarchy in which to store the split files.
- keep
- If false, preexisting .al files in the auto directory that are no longer part of the module are deleted.
- check
- If true, checks to be sure the module being split includes a
use AutoLoaderstatement. If the statement is missing,autosplitdoesn't process the module. - modtime
- If true, splits the module only if it is newer than autosplit.ix.
autosplit_lib_modulesautosplit_lib_modules (@ARGV)Takes a list of modules that are assumed to be in a lib subdirectory of the current directory, processes them as described above forautosplit, and stores the resulting file in the directory lib/auto. Used in building Perl.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - autouse
- InhaltsvorschauPragma for postponing the loading of a module from compile time to execution time. The module isn't loaded until one of its subroutines is used; the subroutines all have to be exported by the module:
use autouse module => qw(sub1 [sub2 ...])
Use with care, since problems that might otherwise be found during compilation won't crop up until your program is already executing.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B
- InhaltsvorschauThe Perl compiler. To use the compiler, you don't need to use this module. See the O module, which is the user frontend to the compiler; see also the compiler section of Chapter 3. The B module provides the classes for implementing backends for the compiler. If you plan to write a new backend, read the B manpage for the details of the module.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- B::Asmdata
- InhaltsvorschauContains autogenerated data about Perl ops; used to generate bytecode. Any changes made to this file will be lost.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- B::Assembler
- InhaltsvorschauAssembles Perl bytecode.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- B::Bblock
- InhaltsvorschauWalks the basic blocks of a program. Invoked as:
perl -MO=Bblock[,options] filename
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::Bytecode
- InhaltsvorschauThe bytecode backend for the Perl compiler. Takes Perl source code and generates platform-independent bytecode that can be run with the byteperl executable or can be loaded via the
byteload_fhfunction in the B module. Compiling with the bytecode backend won't speed up execution of your program, but it may improve start-up time. Invoke as:perl -MO=Bytecode[,options] program
in which program is the name of the Perl script to compile. Any non-option arguments are treated as the names of objects to be saved; the main program is assumed if there are no extra arguments. Possible options are:- --
- Forces end of options.
- -Dopts
- Debug options, which can be concatenated or specified separately. Possible options are:
-
a - Tells the bytecode assembler to include assembler source in its output as bytecode comments
-
b - Prints debugging information about bytecompiler progress
-
C - Prints each CV from the final walk through the symbol tree
-
o - Prints each OP as it's processed
-
- -fopt
- Forces individual optimizations on or off. Preceding an optimization with
no-turns that option off (e.g.,no-compress-nullops). Possible values of opt are:-
bypass-nullops - If
op->op_nextever points to a NULLOP, replaces theop_nextfield with the first non-NULLOP in the path of execution. -
compress-nullops - Fills in only the necessary fields of ops that have been optimized away by Perl's internal compiler.
-
omit-sequence-numbers - Leaves out the code to fill in the
op_seqfield for all ops that are used only by Perl's internal compiler. -
strip-syntax-tree
-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::C
- InhaltsvorschauThe C backend for the Perl compiler. Generates C source code from Perl source; the generated code corresponds to Perl's internal structures for running the program. Compiling with the C backend won't speed up execution of your program, but it may improve start-up time. Invoke as:
perl -MO=C[,options ] program
in which program is the name of the Perl script to compile. Any non-option arguments are treated as the names of objects to be saved; the main program is assumed if there are no extra arguments. Possible options are:- --
- Forces end of options.
- -Dopts
- Debug options, which can be concatenated or specified separately. Possible options are:
-
A - Prints AV information on saving
-
c - Prints COPs as they are processed, including file and line number
-
C - Prints CV information on saving
-
M - Prints MAGIC information on saving
-
o - Prints each OP as it's processed
-
- -fopt
- Forces individual optimizations on or off. Possible values of opt are:
-
cog - Copy-on-grow. PVs are declared and initialized statically.
-
no-cog - No copy-on-grow.
-
- -ofilename
- Sends output to filename instead of to STDOUT.
- -O[ n ]
- Sets optimization level, in which n is an integer. n defaults to
1. Currently, values of1and higher setcog. - -uPackname
- Forces apparently unused subroutines from package Packname to be compiled, letting programs use
eval "foo( )"even if subroutinefooisn't seen to be used at compile time. You can specify multiple
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::CC
- InhaltsvorschauThe CC backend for the Perl compiler. Generates optimized C source code that corresponds to your program's flow. The initial version included in Perl 5.005 actually includes few optimizations, but this will change. Programs compiled with this backend may start up and execute slightly faster. Invoke as:
perl -MO=C[,options ] program
program is the name of the Perl script to compile. Any non-option arguments are treated as the names of objects to be saved; the main program is assumed if there are no extra arguments. Possible options are:- --
- Forces end of options.
- -Dopts
- Debug options, which can be concatenated or specified separately. Possible options are:
-
l - Outputs the filename and line number of each original line of Perl code as it is processed
-
O - Outputs each OP as it is compiled
-
p - Outputs the contents of the shadow pad of lexicals as it is loaded for each sub or for the main program
-
q - Outputs the name of each fake PP function in the queue as it's about to be processed
-
r - Writes debugging output to STDERR instead of as comments in the C output
-
s - Outputs the contents of the shadow stack at each OP
-
t - Outputs timing information of the stages of compilation
-
- -fopt
- Forces individual optimizations on or off. Possible values of opt are:
-
freetmps-each-bblock - Runs FREETMPS at the end of each basic block instead of at the end of each statement.
freetmps-each-loopandfreetmps-each-bblockare mutually exclusive.
-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::Concise
- InhaltsvorschauA module that walks the Perl syntax tree, printing concise info about the internal OPs of a Perl program's syntax tree. The format of the information displayed is customizable. Its function is similar to that of Perl's -Dx debugging flag or the B::Terse module, but it is more sophisticated and flexible. Invoke as:
perl -MO=Concise[,options] program
program is the name of the Perl script to compile. Any non-option arguments are treated as the names of objects to be saved; the main program is assumed if there are no extra arguments. Possible options are:- -basic
- Prints OPs in the order they appear in the OP tree (a preorder traversal, starting at the root). Default.
- -exec
- Prints OPs in the order they would normally execute. For the majority of constructs, this is a postorder traversal of the tree, ending at the root.
- -tree
- Prints OPs in a text approximation of a tree, with the root of the tree at the left and "left-to-right" order of children transformed into "top-to-bottom". Unsuitable for large programs.
- -compact
- Uses a tree format in which the minimum amount of space is used for the lines connecting nodes (one character in most cases).
- -loose
- Uses a tree format that uses longer edges to separate OP nodes. Default.
- -vt
- Uses tree-connecting characters drawn from the VT100 line-drawing set.
- -ascii
- Draws the tree with standard ASCII characters such as
+and|. Default. - -main
- Includes the main program in the output, even if subroutines were also specified.
- -basen
- Prints OP sequence numbers in base n, with n <= 62. The default is 36.
- -bigendian
- Prints sequence numbers with the most significant digit first. Default.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::Debug
- InhaltsvorschauWalks the Perl syntax tree, printing debug information about ops. Invoke as:
perl -MO=Debug[,exec] filenameIfexecis specified, walks in execution order rather than in syntax order.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::Deparse
- InhaltsvorschauPerl compiler backend that generates Perl source code from the internal compiled structure of a program. The output won't be exactly the same as the original program, but it will be close. Invoke as:
perl -MO=Deparse[,options] program
program is the name of the program that will be deparsed. The options are comma-separated and follow normal backend option conventions. The possible options are:- -l
- Adds
#linedeclarations to the output based on line and file locations of the original code. - -p
- Prints parentheses wherever they are legal, not just where they are required. Useful for seeing how Perl is parsing your expressions.
- -sletters
- Provides style options for the output. In this initial release, the only style option provided is
C, which "cuddles"else,elsif, andcontinueblocks so that, for example, you would get:} else {instead of:} else {The default is to not cuddle. - -uPackage
- Deparses subroutines in package Package as well as the main program, subroutines called by the main program, and subroutines in the main program. Multiple -u arguments can be given, separated by commas.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::Disassembler
- InhaltsvorschauDisassembles Perl bytecode.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- B::Lint
- InhaltsvorschauProvides program checking for Perl programs. Equivalent to running Perl with the -w option. Named after the Unix lint program for checking C programs. Invoked as:
perl -MO=Lint[,options] program
program is the name of the Perl program that will be checked. The options are separated by commas and follow normal backend option conventions. Most of the options are lint-check options, in which each option is a word specifying one lint check. Preceding an option withno-turns off that option. Options specified later override earlier options. There is also one non-lint-check option, -u. Here is the list of available options:- all
- Turns all warnings on.
- context
- Warns whenever an array is used in implicit scalar context.
- dollar-underscore
- Warns whenever
$_is explicitly used anywhere or whenever it is used as the implicit argument of aprintstatement. - implicit-read
- Warns whenever an operation implicitly reads a Perl special variable.
- implicit-write
- Warns whenever an operation implicitly writes to a Perl special variable.
- none
- Turns off all warnings.
- private-names
- Warns whenever any variable, subroutine, or method name lives in a non-current package but begins with an underscore (
_). Doesn't warn about an underscore as a single-character name, e.g.,$_. - regexp-variables
- Warns whenever one of the regular expression variables
$',$&, or$'is used. - -u Package
- Normally checks only the main program code and all subroutines defined in package
main. -u lets you specify other packages to be checked. - undefined-subs
- Warns whenever an undefined subroutine is invoked.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::Showlex
- InhaltsvorschauShows lexical variables used in functions or files. Invoke as:
perl -MO=Showlex[,sub] filename
If sub is provided and is the name of a subroutine in file filename, B::Showlex prints the lexical variables used in that subroutine. Otherwise, it prints the file-scope lexicals in filename.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::Stackobj
- InhaltsvorschauServes as a helper module for the CC backend.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- B::Terse
- InhaltsvorschauWalks the Perl syntax tree, printing terse information about the ops. Invoke as:
perl -MO=Terse[,exec] filenameIfexecis specified, walks the tree in execution order instead of syntax order.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - B::Xref
- InhaltsvorschauPerl compiler backend that generates a cross-reference listing of variables, subroutines, and formats in a Perl program. Results are grouped by file, then subroutine, then package, then objects within the package with line numbers. The line numbers are given as a comma-separated list. A line number may be preceded by one of the following code letters:CodeMeaning
%Subroutine or method callfFormat definitioniIntroduction, e.g., a lexical defined withmysSubroutine definitionInvoke B::Xref like this:perl -MO=Xref[,options] program
program is the Perl program whose cross-reference you want. Options are separated by commas and follow normal backend option conventions. The possible options are:- -D
- Specifies internal debug options. Most useful if specified with -r option. Debug options are:
-
O - Prints each operator as it's being processed, in the execution order of the program
-
t - Prints the object on the top of the stack as it is being tracked
-
- -ofilename
- Sends output to filename instead of to STDOUT.
- -r
- Produces raw output in machine-readable form for each definition or use of a variable, subroutine, or format.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - base
- InhaltsvorschauProvides a shortcut for setting up
@ISA. You can say:use base qw(A B);
instead of:BEGIN { require Foo; require Bar; push @ISA, qw(Foo Bar); }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Benchmark
- InhaltsvorschauProvides routines for timing the execution of your code and formatting the results. Inherits only from the Exporter class. It has the following functions.newnew BenchmarkReturns the current time. By getting the current time before and after running the code, you can calculate the time it takes the code to run.clearallcacheclearallcacheClears the entire cache. Exported on request.clearcacheclearcache (count)Clears the cached time for count rounds of the null loop. Exported on request.debugBenchmark->debug(flag)Enables or disables debugging by setting the
$Benchmark::Debugflag.disablecachedisablecacheDisables use of the cache. Exported on request.enablecacheenablecacheResumes caching. Exported on request.timedifftimediff (t1, t2)Calculates the difference between two times and returns the difference as a Benchmark object suitable for passing totimestr. Always exported.timeittimeit (count, code)Runs code and reports the time it took. Always exported. Takes the following arguments:- count
- The number of times to run the loop
- code
- The code to run, specified as either a code reference or a string
timestrtimestr (timediff[, style[, format]])Converts times to printable strings. Always exported. Takes the following arguments:- timediff
- The object containing the times to be formatted.
- style
- The output format. The possible values of style are:
-
all - Shows all of the following times: wallclock, user, system, user time of children, and system time of children
-
auto - Like
all, except that if the children times are both0, it acts likenoc -
noc - Shows all except the two children times
-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - bigint
- InhaltsvorschauProvides big-integer support for Perl. Prior to 5.8, and for 32-bit architectures, Perl supported whatever numbers your platform supported. This wasn't always the best solution when dealing with large numbers. Thus, the integer-related math modules were born, including Math::BigInt and bigint. Math::BigInt and bigint override all of the core Perl math functions and still support large integers. As of Perl 5.8, bigint.pm is shipped with the Perl source kit.For example:
#!/usr/local/bin/perl -w use bigint; my $num1 = 4; my $num2 = 1024; print $num1 ** $num2, "\n"; # Prints a very large number
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - bignum
- InhaltsvorschauSupports whatever big numbers you give it, including large integers and floats. In addition, bignum lets you specify options for the accuracy and precision of numbers that you'll calculate with it.For example:
#!/usr/local/bin/perl -w use bignum; my $num1 = 4; my $num2 = 5; my $mult = $num1 * $num2; print sqrt($mult),"\n"; # Yup
For a number that would be large, you can use bignum's accuracy option,a, to set the number of places after the decimal:perl -Mbignum=a,50 -le 'print sqrt(20), "\n";'
If you wish to use rounding with bignum, you can use the precision option,p, with a0or1value to round up a value:perl -Mbignum=p,0 -le 'print sqrt(24), "\n";' # Gives 5
To enable tracing for bignum, use thetortraceoptions:/usr/local/perl5.8-prerc1/bin/perl5.7.3 -Mbignum=p,0,t -le 'print sqrt(24)' MBI import Math::BigInt::Trace :constant upgrade Math::BigFloat::Trace lib Calc MBF import Math::BigFloat::Trace :constant downgrade Math::BigInt::Trace MBI new '24' => '24' (Math::BigInt::Trace) MBF new '24' => '24' (Math::BigFloat) MBF new '4' => '4' (Math::BigFloat) MBF new '1E-4' => '0' (Math::BigFloat) MBI new '2' => '2' (Math::BigInt::Trace) MBF new '2' => '2' (Math::BigInt::Trace) MBI new '38' => '38' (Math::BigInt::Trace) MBI new '38' => '38' (Math::BigInt::Trace)
Thel, orlib, option lets you specify a different math library:perl -Mbignum=l,new_math_lib -e 'print $this ** $that'
Thev, orversion, option shows you the version of all modules used by bignum and then exits.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - bigrat
- InhaltsvorschauImplements big rational support for Perl. For example, if you want to add the fractions 1/2 + 3/8, you can use bigrat to calculate the result and display it in fractional form: 7/8. Or in Perl terms:
#!/usr/local/bin/perl -w use bigrat; my $frac1 = 1/2; my $frac2 = 3/8; print $frac1 + $frac2, "\n"; # Prints 7/8
As of Perl 5.8, bigrat is shipped with the Perl source kit.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - blib
- InhaltsvorschauPragma for testing programs against a package before the package has been installed. Given a directory path,
blibstarts looking for ablibdirectory structure in that directory; if it doesn't find one there, it works its way back up five levels. If no path is specified, it starts looking in the current directory.blibis meant to be used from the command line:perl -Mblib script [args...] perl -Mblib=dir script [args...]
However, you can also call it from a Perl program:use blib; use blib 'dir';
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - bytes
- InhaltsvorschauThe
use bytespragma disables character semantics for the rest of the lexical scope in which it appears.no bytescan reverse the effect ofuse byteswithin the current lexical scope. Perl normally assumes character semantics in the presence of character data (i.e., data from a source marked as being of a particular character encoding). Whenuse bytesis in effect, the encoding is temporarily ignored, and each string is treated as a series of bytes.bytesis used as follows:$x = chr(400); print "Length is ", length $x, "\n"; # "Length is 1" printf "Contents are %vd\n", $x; # "Contents are 400" { use bytes; print "Length is ", length $x, "\n"; # "Length is 2" printf "Contents are %vd\n", $x; # "Contents are 198.144" }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ByteLoader
- InhaltsvorschauByteLoader is used to load byte-compiled Perl code. It uses the source filter mechanism to read the bytecode and insert it into the compiled code at the appropriate point. You will probably never interact with ByteLoader programatically.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Carp
- InhaltsvorschauProvides routines for generating error messages. Its subroutines generally report errors from the perspective of the calling program. It has the following functions.carpcarp msgWarns of an error; reports the error as having occurred in the calling routine, not in the routine that contains the
carp.Use Carp; carp "text of error message";cluckcluck msgWarns of errors and prints a stack backtrace; reports the error as having occurred in the calling routine. Not exported by default.use Carp qw(cluck); cluck "text of error message";confessconfess msgDies and prints a stack backtrace. Reports the error as having occurred at the point whereconfesswas called.croakcroak msgDies and reports error as having occurred in the calling routine.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CGI
- InhaltsvorschauThe Common Gateway Interface (CGI) library permits object-oriented web form creation and processing. The CGI.pm module contains the bulk of functionality for CGI programming. Four subclasses provide interfaces to various server environments and additional features. They are described below. For complete information on how CGI works and a description of CGI.pm, see Chapter 9 and Chapter 10.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- CGI::Apache
- InhaltsvorschauSets up the environment for using CGI.pm with the Perl-Apache API. The
newconstructor for this class creates an Apache::CGI class object that interfaces to the API.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CGI::Carp
- InhaltsvorschauCreates Carp-like CGI routines for writing error messages to the HTTPD or other error log. Exports functions for
warn,die,carp,confess, andcroak. The functions write timestamped error messages to your server log or other output that you specify. See Section 8.32 for details on the Carp functions.Two other functions are provided by this module. Neither are automatically exported, so you must explicitly import them inuse:use CGI::Carp qw(carpout fatalsToBrowser);
carpoutcarpout \*fhSends error messages to the filehandle fh. You should provide a reference to the filehandle glob, although you can also just use the filehandle's name for this function.fatalsToBrowserfatalsToBrowserWhen this routine is imported viause, fatal errors, such as those produced bydieandconfess, send error messages to the browser as well as the error log. A simple HTTP response is created with the error message, followed by a request to send mail to the web administrator.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CGI::Cookie
- InhaltsvorschauProvides an interface to Netscape (HTTP/1.1) cookies that can be used in conjunction with CGI.pm or independently. To use CGI::Cookie, create a new cookie object with the constructor
new. You can then send the cookie to the browser in one of the following ways:- From a CGI script, create a Set-Cookie field in the HTTP header for each cookie you want to send (
$cis the cookie object):print "Set-Cookie: $c0";
- With CGI.pm (see Chapter 10), use the
headermethod with a-cookieargument:print header(-cookie=>$c);
- Using mod_perl (see Chapter 11), use the request object's
header_outmethod:$r->header_out('Set-Cookie',$c);The following methods are provided for CGI::Cookie.
new$c = new CGI::Cookie(attribs)Constructor. Creates a new cookie. Attributes are:-
-domain =domain_name - Optional. Points to domain name or fully qualified hostname to which cookie will be returned. If missing, browser will return cookie only to the server that set it.
-
-expires =date - Optional expiration date in any of the date formats recognized by CGI.pm. If missing, cookie expires at the end of this browser session.
-
-name =name - Required. Scalar value with the cookie name.
-
-path =path - Optional. Points to a partial URL on the current server; cookies will be returned to any URL beginning with this path. Defaults to
/. -
-secure =boolean - Optional. If true, browser will return cookie only if a cryptographic protocol is in use.
-
-value =value - Required. The value of the cookie; can be a scalar, an array reference, or a hash reference.
as_string$c->as_stringTurns internal representation of cookie into RFC-compliant text. Called internally by overloading the "" operator, or can be called directly.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CGI::Fast
- InhaltsvorschauCGI interface for FastCGI. FastCGI is a type of gateway for web servers that improves performance by loading scripts as persistently running processes. CGI::Fast provides a
newconstructor to create a CGI object that runs in this environment. FastCGI requires both a server and a version of Perl that are FastCGI-enabled. Seewww.fastcgi.comfor more information.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CGI::Pretty
- InhaltsvorschauAllows users of CGI to output nicely formatted HTML code by adding carriage returns and indentations to HTML markup for easy readability. For example, the following code:
#!/usr/local/bin/perl -w use CGI qw(:all); my $query = CGI->new( ); print $query->start_html( ); print $query->table( TR( td( "foo" ) ) ); print $query->end_html( );
outputs the following HTML:<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><head><title>Untitled Document</title> </head><body><table><tr><td>foo</td></tr></table></body></html>which is ugly. You can make it prettier with CGI::Pretty:#!/usr/local/bin/perl -w use CGI::Pretty qw( :html3 ); my $query = CGI->new( ); print $query->start_html( ); # Print a table with a single data element print $query->table( TR( td( "foo" ) ) ); print $query->end_html( );
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CGI::Push
- InhaltsvorschauProvides an interface to do server push operations, letting you rewrite pages with content that changes regularly. A server push operation automatically sends updates to a page on a push-capable browser. CGI::Push exports the function
do_pushto implement page redraws. This method can be used on a CGI::Push object or on its own:$q = new CGI::Push; $q->do_push(-next_page => \&sub);
or:do_push (-next_page => \&sub);
do_pushrequires one argument: a reference to a subroutine that will draw the next page. You may optionally specify a subroutine that draws the last page and the interval between page updates. Additional parameters todo_pushare those that can be used with a CGI::headers object.do_pushdo_push (params)Implements a server push operation, which updates a page at specific intervals. Parameters are:-
-delay =>n - Specifies the number of seconds, n, to wait before the next call to the page-drawing subroutine.
-
-last_page =>\&sublast - Runs the subroutine sublast to draw the last page update of a server push operation. The
-last_pageroutine is invoked when the-next_pageroutine returns false. A reference to a subroutine glob should be provided for this parameter, but the name of the subroutine is also acceptable. -
-next_page =>\&sub - sub is the name of the subroutine responsible for redrawing the page and counting the number of iterations (if you want repeated updating). The
do_pushroutine ends when sub returns false (or when the-last_pagesubroutine is invoked). A reference to a subroutine glob should be provided for this parameter, but the name of the subroutine is also acceptable. -
-type =string - Specifies the content type of the pushed data. The default value is
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- CGI::Switch
- InhaltsvorschauProvides a
newmethod that tries to callnewin each of the Apache::CGI, CGI::XA, and CGI classes, returning the first CGI object that it successfully gets.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - charnames
- InhaltsvorschauPragma to provide support for
\N{charname}escapes. Options are:-
:full - Searches for charnames in the list of standard Unicode character names
-
:short - Searches for charnames in the specified script, with the
\Nescape expected to be of the form\N{script:charname} - scriptname
- Searches for all charnames in script scriptname
For example:#!/usr/local/bin/perl -w use charnames ':short'; print "\N{greek:Sigma} is an upper-case sigma.\n";Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Class::ISA
- InhaltsvorschauAllows you to scan
@ISA—in order and without duplicates—for names of classes that Perl would scan to find a method. This is important when using classes that are derived from other classes, which are themselves derived from other classes, and so forth. Class::ISA is bundled with the Perl 5.8 source kit.Let's say that you calledSomeClass->method(). Perl searches formethod()first in SomeClass, but will search its superclasses formethod()if it doesn't find it in SomeClass. For example:@SomeClass::ISA = qw(SomeOther SomeOtherOther SomeOtherOtherOther); use Class::ISA; print "SomeClass::ISA path is:\n ", join(", ", Class::ISA::super_path(`SomeClass')), "\n";This prints:SomeOther, SomeOtherOther, SomeOtherOtherOther
Class::ISA doesn't export anything. If classes erroneously inherit from each other; i.e., if there's a loop (or cycle) between what's inherited between classes, Perl throws an error, and Class::ISA itself will ignore the loop. If Perl can't find the method in the@ISAtree, it looks in UNIVERSAL, but Class::ISA does not. You may do something like the following to search in UNIVERSAL as well:@supers = (Class::Tree::super_path($CLASS), `UNIVERSAL');
Here are the Class::ISA methods.self_and_super_pathClass::ISA::self_and_super_path($CLASS)Identical tosuper_path, except that$CLASSis included as the first element.self_and_super_versionsClass::ISA::self_and_super_versions($CLASS)Returns a hash with keys that are$CLASS(and its superclasses) and values that are the contents of the$VERSIONof each class. If$VERSIONdoes not exist,sel_and_super_versionsreturnsundef.super_pathClass::ISA::super_path(class)Returns an ordered list of names of classes that Perl would search through to find a method. Note that no duplicates will be allowed in the list; nor will class be included in the list. UNIVERSAL is not included in the list, but if you need it, you should add it to the end of the list.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Class::Struct
- InhaltsvorschauFormerly named Class::Template; exports a single function,
struct.structtakes a list of element names and types, and optionally a class name, and creates a Perl class that implements a struct-like data structure. It also creates a constructor method,new, for creating objects of the class (so a class created this way must not itself define anewmethod).Each element in the struct data has an accessor method, which is used to assign to the element and to fetch its value. The default accessor can be overridden by declaring a sub of the same name in the package. Each element's type can be scalar, array, hash, or class.structstruct (paramlist)Creates a class, with object methods for each element of the class. The parameter list paramlist can take one of three forms:struct( CLASS_NAME => [ ELEMENT_LIST ]); # Object is array-based struct( CLASS_NAME => { ELEMENT_LIST }); # Object is hash-based struct( ELEMENT_LIST ); # Class name is current, and package name # object is array-basedThe array-based element lists are faster and smaller, but the hash-based list is more flexible. The class that is created can be a subclass of the UNIVERSAL class, but not of any other class.Element listThe items in the ELEMENT_LIST are of the form:NAME => TYPE, ...
in which eachNAME=>TYPEpair declares one element of thestruct. Each element name is defined as an accessor method, unless a method is explicitly defined with that name. (In that case, a warning is issued if the -w flag is set.)Element types and accessor methodsThere are four possible element types, each represented by a string. Each string may start with an asterisk (*), indicating that a reference to the element will be returned. The type of an element determines the accessor method provided. The following list shows the element types, the strings that represent them, and the accessor:-
array (
@or*@) - The element is an array, initialized to
( ). With no argument, the accessor returns a reference to the element's whole array. With one or two arguments, the first argument is an index specifying one element of the array; the second argument, if present, is the value that will be assigned to that array element.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
array (
- Config
- InhaltsvorschauUsed to access configuration information. When Perl is built, the Configure script obtains and saves this information in a hash,
%Config, in Config.pm itself. Config checks to be sure it's running with the same Perl version as the one that created the hash.The index into the hash is the shell variable name.%Configis always exported; the following three functions are exported on request.config_shconfig_shReturns all Perl configuration information.use Config(qw(config_sh)); print config_sh( );
returns:archlibexp='sun4-solaris' cc='cc' ccflags='-I/usr/local/include/sfio -I/usr/local/include' ...
config_varsconfig_vars (names)Returns the name/value pairs for the requested configuration variables. Prints the results to STDOUT.use Config(qw(config_vars)); print config_vars(qw(osname ccflags));
returns:osname='solaris' ccflags='-I/usr/local/include/sfio -I/usr/local/include'
myconfigmyconfigReturns a summary of the major Perl configuration values.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - constant
- InhaltsvorschauA Perl pragma that declares compile-time constants with a given scalar or list value. By default, the value is evaluated in list context, but you can override the default by specifying
scalar:use constant NAME1 => value1; use constant NAME2 => scalar value2;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CPAN
- InhaltsvorschauLets you access CPAN; search for a module, a bundle, an author, or a distribution; download a module or distribution; install it; and
makeit. The CPAN module can be used either interactively from the command line or programmatically:perl -MCPAN -eshell; # Run from the command line
or:use CPAN; my $obj = CPAN::Shell->install('ExtUtils::MakeMaker');This section describes the use of the CPAN module from a program. See Chapter 2 for information on using it interactively and for details of the available commands. These commands, available interactively from the shell, are methods of the class CPAN::Shell. From a program, they are available both as methods (e.g.,CPAN::Shell->install(...)) and as functions in the calling package (e.g.,install(...)).Each of the commands that produce listings of modules (r,autobundle, andu) returns a list of the IDs of all modules within the list. The IDs of all objects available within a program are strings that can be expanded to the corresponding real objects with theCPAN::Shell->expand("Module",@things)method.expandreturns a list of CPAN::Module objects according to the@thingsarguments. In scalar context, it returns only the first element of the list.The CPAN module contains a session manager, which keeps track of objects that have been fetched, built, and installed in the current session. No status is retained between sessions.There is also a cache manager, which keeps track of disk space used and deletes extra space. The cache manager keeps track of the build directory,$CPAN::Config->{build_dir}, and uses a simple FIFO mechanism to delete directories belowbuild_dirwhen they grow bigger than$CPAN::Config->{build_cache}.The original distribution files are kept in the directory$CPAN::Config->{keep_source_where}. This directory is not covered by the cache manager but must be controlled by the user. If the same directory is used as bothbuild_dirandkeep_source_where, your sources are deleted with the same FIFO mechanism.The CPAN module recognizes a bundle as a Perl module in the namespace Bundle:: that does not define any functions or methods and usually contains only pod documentation. It starts like a Perl module with a package declaration and aEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CPAN::FirstTime
- InhaltsvorschauThe CPAN::FirstTime module has one function,
init, which is an initialization routine called automatically the first time a user uses the CPAN module. It asks the user a series of questions and writes the answers into aCPAN::Configfile.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CPAN::Nox
- InhaltsvorschauA wrapper for CPAN.pm that prevents the use of any compiled extensions while it's executing. Run it in interactive mode if you have upgraded Perl but your extensions aren't working:
perl -MCPAN::Nox -eshell;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Cwd
- InhaltsvorschauThe Cwd module provides three functions that get the pathname of the current working directory. Using these functions instead of the pwd command will make your code more portable, because not all systems have pwd.cwdcwdGets the current working directory. This is the safest way to get it.fastcwdfastcwdA faster way to get the directory, but somewhat more dangerous because of the way it works internally.getcwdgetcwdDoes the same thing as
cwdby reimplementing the C library functionsgetcwd(3)orgetwd(3)in Perl.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Data::Dumper
- InhaltsvorschauConverts Perl data structures into strings that can be printed or used with
evalto reconstruct the original structures. Takes a list of scalars or reference variables and writes out their contents in Perl syntax. Several interfaces to Data::Dumper are provided:- Simple procedural interface:
print Dumper($foo, $bar);
- Extended usage with names:
print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
- Object-oriented interface:
$d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]); ... print $d->Dump;
By default, references are identified as$VARn, in which n is a numeric suffix. References to substructures within$VARn are labeled using arrow notation. In the extended usage form, references can be given user-specified names. See the Data::Dumper manpage for examples of the module's use.Several configuration variables can be used to control the output generated using the procedural interface. These variables control the default state of the object created by the new method. Each variable has a corresponding method that can be used later to query or modify the object. In the following list, each variable is followed by the corresponding method:-
$Data::Dumper::Bless -
$obj->Bless([newval]) - Can be set to a string that specifies an alternative to the
blessbuilt-in operator used to create objects. A function with the specified name should exist and should accept the same arguments as the built-in. Default isbless. -
$Data::Dumper::Deepcopy -
$obj->Deepcopy([newval]) - If set to a Boolean value, enables deep copies of structures; cross-referencing is then done only when absolutely essential. Default is
0. -
$Data::Dumper::Indent -
$obj->Indent([newval]) - Controls the style of indentation for the output. Can be set to:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - DB
- InhaltsvorschauThe DB module abstracts and provides all of the hooks into Perl internal debugging functionality, so that various implementations of Perl debuggers (or packages that want simply to get at the "privileged" debugging data) can all benefit from the development of this common code. The following "public" global names can be read by clients of this API, but should be considered read-only:
-
$DB_HASH - Stores key/data pairs in data files; equivalent to other hashing packages such as DBM, NDBM, ODBM, GDBM, and SDBM.
-
$DB::sub - Name of current executing subroutine.
-
%DB::sub - The keys of this hash are the names of all the known subroutines. Each value is an encoded string that has the
sprintfformat("%s:%d-%d", filename,fromline, toline). -
$DB::single - Single-step flag. Will be true if the API will stop at the next statement.
-
$DB::signal - Signal flag. Will be true if a signal was caught.
-
$DB::trace - This flag is set to true if the API is tracing through subroutine calls.
-
@DB::args - Contains the arguments of current subroutine, or the
@ARGVarray if in the toplevel context. -
@DB::dbline - List of lines in currently loaded file.
-
%DB::dbline - Actions in current file (keys are line numbers). The values are strings that have the
sprintfformat("%s\000%s", breakcondition, actioncode). -
$DB::package - Package namespace of currently executing code.
-
$DB::filename - Currently loaded filename.
-
$DB::subname - Fully qualified name of currently executing subroutine.
-
$DB::lineno - Line number that will be executed next.
The following are methods in the DB base class. A client must access these methods by inheritance, since the API keeps track of clients through the inheritance mechanism.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- DB_File
- InhaltsvorschauTies a Perl hash to one of the Berkeley DB database types and lets you use functions provided in the DB API:
[$X =] tie %hash, "DB_File", $filename [, $flags, $mode, $DB_HASH]; [$X =] tie %hash, "DB_File", $filename, $flags, $mode, $DB_BTREE; [$X =] tie @array, "DB_File", $filename, $flags, $mode, $DB_RECNO;
The types are:-
$DB_HASH - Stores key/data pairs in data files. Equivalent to other hashing packages such as DBM, NDBM, ODBM, GDBM, and SDBM.
-
$DB_BTREE - Stores key/data pairs in a binary tree.
-
$DB_RECNO - Uses a record (line) number to access fixed-length and variable-length flat text files through the same key/value-pair interface as in
$DB_HASHand$DB_BTREE.
After you'vetied a hash to a database:$db = tie %hash, "DB_File", "filename";
you can access the Berkeley DB API functions:$db->put($key, $value, R_NOOVERWRITE); # Invoke the DB "put" function
All the functions defined in the dbopen(3) manpage are available exceptcloseanddbopenitself. The constants defined in the dbopen manpage are also available.The following are the functions available (the comments note only the differences from the equivalent C function).del$X->del(key[, flags])Removes key/value pairs from the database. flags is optional.fd$X->fdReturns a file descriptor that represents the underlying database. No difference from the equivalent C function.get$X->get(key, value[, flags])Retrieves data from the database by key. flags is optional. The value associated with key is returned in value.put$X->put(key, value[, flags])Stores a key/value pair in the database. flags is optional. IfR_IAFTERorR_IBEFOREis set, then key is set to the record number of the inserted key/value pair.seq$X->seq(key, value[, flags])Returns the next sequential key/value pair from the database. flags is optional. Both key and value are set.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Devel::DProf
- InhaltsvorschauDevel::DProf is a Perl code profiler. It collects information on the execution time of a Perl script and of the subroutines in that script. To profile a Perl script, run perl with the -d debugging switch:
perl -d:DProf test.pl
When the script terminates (or when the output buffer is filled) the profiler will dump the profile information to a file called tmon.out. A tool such as dprofpp can be used to interpret the information. The following command will print the top 15 subroutines that used the most time:dprofpp
To print an execution graph of the subroutines in the script, use the following command:dprofpp -T
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Devel::PPPort
- InhaltsvorschauAllows you to write Perl code that's as compatible as possible with the widest range of Perl interpreters. Devel::PPPort ships with ppport.h, with which you can incorporate some of the newest features of Perl with your older Perl releases. Devel::PPPort is important for developing modules, since newer Perl versions do not have as many issues with namespace pollution that older Perl versions had.To use Devel::PPPort, copy ppport.h to wherever you're doing your development work, and use the
WriteFile()method when you're ready to generate the necessary code.WriteFile()is used to write a C header file for XS modules. ppport.h contains a series of macros that allow XS to be built under older versions of Perl. For example:my $port_file = '/users1/nvp/Perl/XS/Projects/ppport.h'; Devel::PPPort::WriteFile($port_file);
This generates ppport.h in /users1/nvp/Perl/XS/Projects.WriteFile()takes an optional parameter representing the filename of the ppport header file. If empty, ppport.h is generated in the current directory.WriteFile()returns true if the write was successful, and false otherwise.ppport.h provides access to the Perl API.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Devel::SelfStubber
- InhaltsvorschauGenerates stubs in a module that uses the SelfLoader, either printing the necessary stubs or generating the whole module with the stubs inserted in the correct location before the
_ _DATA_ _token. The default is to simply print the stubs.stubstub (module[, dir])Generates the stubs. Takes the following arguments:- module
- Name of the module, in the form Devel::SelfStubber (with no .pm at the end).
- dir
- Library directory that contains the module. Defaults to the current directory.
To simply print the stubs:use Devel::SelfStubber; Devel::SelfStubber->stub(module, dir);
To generate the whole module, with the stubs inserted correctly, set the variable$Devel::SelfStubber::JUST_STUBSto0:use Devel::SelfStubber; $Devel::SelfStubber::JUST_STUBS = 0; Devel::SelfStubber->stub(module, dir);
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - diagnostics
- InhaltsvorschauProvides more descriptive diagnostics than those generated by the Perl compiler and interpreter. Uses the longer, more explanatory error messages found in the perldiag manpage. Can be used as a pragma or as a standalone program, splain . When used as a pragma, diagnostics affects the compilation phase of your program as well as the execution phase. As a standalone module, it is used to post-process errors after execution has completed.The splain program links to diagnostics.pm to act on the standard error output of a Perl program. The program's output can be sent to a file, which is then used as input to splain, or it can be piped directly to splain. Output from splain is directed to STDOUT.
- -p
- Sets the variable
$diagnostics::PRETTYto true - -v
- Prints the perldiag manpage introduction, then any diagnostic messages
As a pragma:use diagnostics [-verbose]
enables the use of diagnostics in your program (and enables Perl's -w flag). Compilation is then subject to the enhanced diagnostics, which are issued to STDERR. Set thediagnostics::PRETTYvariable in a BEGIN block to provide nicer escape sequences for pagers, so your output looks better. The-verboseoption prints the perldiag manpage introduction, then any diagnostic messages. Functions are:-
enable - Turns diagnostics on at runtime
-
disable - Turns diagnostics off at runtime
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Digest
- InhaltsvorschauThe Digest modules (Digest::MD2, Digest::MD5, Digest::SHA1, and Digest::-HMAC) calculate a digest of data that they encounter. These digests are often referred to as "fingerprints," "hashes," or "sums." The Digest modules return a small, fixed-length string, depending on how you've requested your data. If you change your data and regenerate the digest, the digest will be different each time the data itself changes. As of Perl 5.8, the Digest modules are bundled with the Perl source kit.The Digest modules both a functional interface and an object-oriented interface. If you use the object-oriented inteface, you have the benefit of being able to send data of arbitrary length. You can also tell the Digest module to read files directly.Digest delivers the hashed data in one of three formats: binary, hex, or base64. The following example uses Digest and calculates an MD5 sum of a string,
$text, that represents the data. The data is output in hexadecimal form.#!/usr/local/bin/perl -w use Digest; my $text = 'Be the ball, Danny!'; my $md5 = Digest->MD5; $md5->add($text); my $hashed = $md5->hexdigest; print "The sum of \$text is [$hashed].\n";
This gives you:The sum of $text is [6eec91414372ad157fc9d3d15b496d93].
Digest implements the following functions for the object-oriented interface. These functions are available to all of the Digest modules.resetreset()Alias fornew.addadd(data, ...)Appends data to the message for which you calculate the digest.addreturns the Digest object itself.addfileaddfile(io_handle)Reads io_handle until end-of-file and, likeadd, appends the content to the message for which you calculate the digest.addfilereturns the Digest object itself.b64digestb64digest()Same asdigest, but returns the digest in base64-encoded form.digestdigest()Returns the binary digest for the message. Note thatdigestis a destructive operation, in that the Digest object is reset so it can be used to create another value.hexdigesthexdigest()Same asdigest, but returns digest in hexadecimal form.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Digest::MD5
- InhaltsvorschauThe Digest::MD5 module allows simpler creation of MD5 hashes. MD5 takes as input a message of arbitrary length and creates a 128-bit fingerprint, or digest, of the input. Like the Digest module, Digest::MD5 implements both a functional and object-oriented interface, which offer the same benefits. Digest::MD5 also outputs binary (16 bytes long), hexadecimal (32 characters long), and base64 (22 characters long) data.To rewrite the example in Section 8.57:
#!/usr/local/bin/perl -w # Yes, functional interface use Digest::MD5 qw(md5_hex); my $text = `Be the ball, Danny!'; my $hexed = md5_hex($text); print "The sum of \$text is [$hexed].\n";
You can use the object-oriented interface like so:#!/usr/local/bin/perl -w use Digest::MD5; my $text = `Be the ball, Danny!'; my $md5 = Digest::MD5->new(); $md5->add($text); my $sum = $md5->hexdigest; print "The sum of \$text is [$sum].\n";
Digest::MD5 implements (and exports) the following functions.newnew()Constructor. Returns a new Digest::MD5 object. You can add data to$objectand retrieve the digest itself. If you cannewmore than once, it will reset the existing digest and create a new Digest::MD5 object.resetreset()An alias fornew.addadd(data, ...)Appends data to the message for which you calculate the digest.addreturns the Digest object itself. For example:open(FILE, ...) or ... while (<FILE>) { $md5->add($_); } close(FILE);addfileaddfile(io_handle)Reads io_handle until end-of-file and appends the content to the message for which you calculate the digest.addfilereturns the Digest object itself. For example:open(FILE, $file) or ... print Digest::MD5->new->addfile(*FILE)->hexdigest, " $file\n"; close(FILE);
b64digestb64digest()Same asdigest, but returns the digest in base64-encoded form.digestdigest()Returns the binary digest for the message. Note thatdigestis a destructive operation, in that the Digest object is reset so it can be used to create another value.hexdigesthexdigest()Same asdigest, but returns digest in hexadecimal form.The following functions are implemented by the functional interface.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - DirHandle
- InhaltsvorschauProvides methods for accessing Perl's directory functions, avoiding namespace pollution. Creates anonymous glob to hold a directory handle and closes the dirhandle automatically when the last reference goes out of scope. The following methods are provided.new$dh = new DirHandle [dirname]Constructor. Creates a new directory handle. The optional directory name, dirname, defaults to the current directory.close$dh->close( )Closes a directory handle; equivalent to the
closedirfunction.open$dh->open(dirname)Opens directory dirname; equivalent to theopendirfunction.read$dh->read( )Reads directory entries. Equivalent to thereaddirfunction. In scalar context, reads the next directory entry; in list context, reads all entries.rewind$dh->rewind( )Sets current position to beginning of directory; equivalent to therewinddirfunction.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Dumpvalue
- InhaltsvorschauThe Dumpvalue module is used to provide a screen dump of Perl data. Whether you're trying to look at global variables or you'd like to dump the symbol table so that you can examine it, Dumpvalue will prove useful to you. Here's an example that dumps the symbol table of CGI.pm:
#!/usr/local/bin/perl -w use Dumpvalue; use CGI qw(:all); my $dumper = Dumpvalue->new('DumpPackages' => 1); $dumper->dumpvars('CGI');Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - DynaLoader
- InhaltsvorschauThe standard Perl interface to the dynamic linking mechanisms available on many platforms.Use DynaLoader like this:
package Module; require DynaLoader; @ISA = qw(... DynaLoader ...); bootstrap Module;
Thebootstrapmethod calls your module's bootstrap routine directly if the module is statically linked into Perl. Otherwise, the module inherits thebootstrapmethod from DynaLoader, which loads in your module and calls itsbootstrapmethod.If you want to extend DynaLoader to a new architecture, you need to know about its internal interface. The variables it uses are:-
$dl_debug - Enables internal debugging messages on the Perl side of the DynaLoader; by default, is set to
$ENV{'PERL_DL_DEBUG'}if that is defined. A similar debugging variable is added to the C code (see dlutils.c) and enabled if Perl was built with the -DDEBUGGING flag, or it can be set via the PERL_DL_DEBUG environment variable. Set to1for minimal information or higher for more detail. -
@dl_library_path - Default list of directories to search for libraries; initialized to hold the list of directories in
$Config{'libpth'}. Should also be initialized with other directories that can be determined from the environment at runtime. -
@dl_resolve_using - List of additional libraries or other shared objects for resolving undefined symbols. Required only on platforms without automatic handling for dependent libraries.
-
@dl_require_symbols - List of one or more symbol names in the library/object file to be dynamically loaded. Only required on some platforms.
Of the following subroutines,bootstrapanddl_findfileare standard across all platforms and are defined in DynaLoader.pm. The others are defined in the .xs file that supplies the implementation for the platform.bootstrapbootstrap (modulename)Normal entry point for automatic dynamic loading in Perl.dl_errordl_errorGets error message text from the last failed DynaLoader function:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- encoding
- InhaltsvorschauAlthough Perl 5.6.0 introduced Unicode support, it was not complete until Perl 5.8. With encoding.pm, you can write any Perl script with whatever encoding type you want. If you're a show off and worship anime movies, and want to write your Perl program in Kanji, use
encoding, and be our guest:# Cute example, slightly modified from the encoding.pm doc #!/usr/local/bin/perl -w use encoding 'euc-jp'; # Note that we support only one encoding my $book = 'Camel'; my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji $book =~ s/\bCamel\b/$Rakuda/;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - English
- InhaltsvorschauProvides aliases for the Perl built-in special variables. Everything else about the variables and their use remains the same. Be aware, though, that using the English module significantly slows down a program for regular expressions.Some of the Perl variables match some awk built-in variables. For those cases, you'll find two English names: a short version (which is the awk name) and a longer version. For example, you can use either
$ERRNO(the awk name) or$OS_ERRORto refer to the Perl variable$!.Here is the list of variables and their English alternatives:PerlEnglishPerlEnglish@_@ARG$?$CHILD_ERROR$_$ARG$!$OS_ERROR$%$MATCH$!Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Env
- InhaltsvorschauLets your program treat environment variables as simple variables instead of having to access them from the
%ENVpseudo-hash where they are kept. (Note that pseudo-hashes will disappear as of Perl 6.)use Env; use Env qw(var1 var2 ...);
Internally, Env uses animportfunction that ties suitably named environment variables to global Perl variables with the same names. By default, it ties all variables yielded bykeys %ENV. A "suitable" environment has a name that begins with an alphabetic character and contains only alphanumeric characters or underscores.Whenuse Envis invoked with arguments, the arguments are interpreted as a list of environment variables totie, but the variables don't have to exist yet. After a variable has been tied, you can use it like a normal variable, accessing or changing its value.You untie a variable by setting its value toundef.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Errno
- InhaltsvorschauProvides system errno constants from errno.h include file. Defines and conditionally exports all the error constants defined in errno.h. There is one export tag, :POSIX, which exports all POSIX-defined error numbers.The file Errno.pm is automatically generated and shouldn't be updated. Any changes made to the file will be lost.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Exporter
- InhaltsvorschauImplements a default import method for other modules to inherit if they don't want to define their own. If you are writing a module, you can do the following:
package Module; use Exporter ( ); @ISA = qw(Exporter); @EXPORT = qw(...); @EXPORT_OK = qw(...); %EXPORT_TAGS = (tag => [...]);in which@EXPORTis a list of symbols to export by default,@EXPORT_OKis a list of symbols to export on request, and%EXPORT_TAGSis a hash that defines names for sets of symbols. Names in%EXPORT_TAGSmust also appear in@EXPORTor@EXPORT_OK.Then Perl programs that want to use your module just say:use Module; # Import default symbols use Module qw(...); # Import listed symbols use Module ( ); # Do not import any symbols
The Exporter can handle specialized import lists. An import list is the list of arguments passed to theimportmethod. If the first entry begins with!, :, or/, the list is treated as a series of specifications that add to or delete from the list. A leading!means delete, rather than add.SymbolMeaning[!]nameThis name only[!]:DEFAULTAll names in@EXPORT[!]:tagAll names in$EXPORT_TAGS{tag}anonymous list[!]/pattern/Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::Command
- InhaltsvorschauProvided with the standard Win32 port to replace common Unix commands in MakeFiles. Includes subroutines for the following commands.catcat file... [> destination]Concatenates all specified files into destination file or to STDOUT.chmodchmod mode files...Sets Unix-like permissions on all files specified. mode gives the permissions to set.cpcp source... destinationCopies a single source file source to destination. Multiple source files can be specified if destination is an existing directory.eqtimeeqtime source destinationSets the "modified time" of destination to that of source.mkpathmkpath directory...Creates directory, including any parent directories.mvmv source... destinationMoves sourcefile source to destination. Multiple sourcefiles are allowed if destination is an existing directory.rm_frm_f files....Removes files, even if they are read-only.rm_rfrm_rf directories....Removes directories recursively, even if they are read-only.test_ftest_f fileTests for the existence of file.touchtouch file....Makes sure file exists and sets the current timestamp.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::Command::MM
- InhaltsvorschauSets commands for MakeMaker to use in Makefiles. ExtUtils::Command::MM encapsulates code that would otherwise have to be done with large one-liners. This module is shipped with the Perl 5.8 source kit.Everything is read from
@ARGV, unless otherwise noted. For example:test_harness($verbose, @test_libs);
runs the tests on@ARGVvia Test::Harness passing through the$verboseflag. Any@test_libswill be unshifted onto the test's@INC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::Constant
- InhaltsvorschauGenerates XS code to import C header constants, allowing Perl modules to AUTOLOAD constants defined in C library header files. Generally, you should not touch ExtUtils::Constant functions, since they are already implemented by h2xs.For example:
use ExtUtils::Constant qw (WriteConstants); WriteConstants( NAME => `Nate', NAMES => [qw(Nate Nathan Nathaniel)], # not Nat ); # Generates wrapper code to make the values of the constants # Nate Nathan Nathaniel available to perlCurrently, this module understands the following types, although h2xs may only know a subset. The sizes of the numeric types are chosen by the Configure script at compile time.-
IV - Signed integer. At least 32 bits.
-
UV - Unsigned integer. The same size as
IV. -
NV - Floating-point type. Probably
double. Possiblylong double. -
PV NUL[L] - Terminated string. Length will be determined with
strlen. -
PVN - A fixed-length thing, given as a pointer, length pair. If you know the length of a string at compile time, you can use this instead of
PV. -
SV - A mortal SV.
-
YES - Truth (
PL_sv_yes). The value is not needed (and is ignored). -
NO - Defined falsehood (
PL_sv_no). The value is not needed (and is ignored). -
UNDEF - The value of the macro is not needed.
ExtUtils::Constant implements the following functions.assignassign indent, type, pre, post, value ...Returns a suitable assignment clause. If type is aggregate (e.g.,PVNexpects both pointer and length), then there should be multiple values for the components. pre and post, if defined, give snippets of C code to proceed and follow the assignment. preis at the start of a block, so variables may be defined in it.autoloadautoload package, version, autoloaderEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- ExtUtils::Embed
- InhaltsvorschauGenerally called from the Makefile that builds your application to provide initialization functions for embedding Perl code in C or C++ applications. For example:
perl -MExtUtils::Embed -e xsinit perl -MExtUtils::Embed -e ldopts
Uses the configuration information kept in Config.pm (see the Config module above). Exports the following functions.ccdlflagsccdlflagsPrints$Config{ccdlflags}.ccflagsccflagsPrints$Config{ccflags}.ccoptsccoptsCombinesperl_inc,ccflags, andccdlflags.ldoptsldoptsOutputs arguments for linking the Perl library and extensions to your application. When invoked as:perl -MExtUtils::Embed -e ldopts -
the following options are recognized:- -std
- Outputs arguments for linking the Perl library and any extensions linked with the current Perl.
- -I <path1:path2>
- Search path for ModuleName.a archives. Default is
@INC. - -- <list of linker args>
- Additional linker arguments to be considered.
Any additional arguments found before the -- token are taken as the names of modules to generate code for. Can also be called with parameters:'ldopts($std,[@modules],[@link_args],$path)'
When called this way, returns the argument string rather than printing it to STDOUT. The optional parameters are:-
$std - Boolean, equivalent to the -std option.
-
[@modules] - Array reference. Equivalent to adding module names before the -- token.
-
[@link_args] - Array reference. Equivalent to adding linker arguments after the -- token.
-
$path - Equivalent to the -I option.
perl_incperl_incFor including Perl header files. For example, if you say:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::Install
- InhaltsvorschauUsed by MakeMaker for handling the platform-dependent installation and deinstallation of modules; not meant to provide general-purpose tools. Exports the following functions.installinstall (\hashref, verbose, nonono)Installs files. Takes the following arguments:
-
\hashref - Reference to a hash, in which each key is a directory to copy from and the value is the directory to copy into. The whole tree below the "from" directory is copied, with timestamps and permissions preserved.The hash has two additional keys:
readandwrite. After copying everything,installwrites the list of target files to the file named by$hashref->{write}. If there is another file named by$hashref->{read}, its contents are merged into the written file. -
verbose - Verbose switch.
-
nonono - Don't-really-do-it switch.
install_defaultinstall_default ([fullext])Callsinstallwith the same arguments as the MakeMaker defaults. Takes zero or one argument. With no argument, it treats$ARGV[0]as the argument. If present, the argument contains the value of MakeMaker's FULLEXT key.pm_to_blibpm_to_blib (\hashref[, dir])Takes a hash reference as the first argument and copies all the keys of the hash to the corresponding values. Filenames with the .pm extension are autosplit. The optional second argument is the autosplit directory.uninstalluninstall (packlistfile, verbose, nonono)Uninstalls files. Takes the following arguments:- packlistfile
- Name of file containing filenames to be unlinked
- verbose
- Verbose switch
- nonono
- No-don't-really-do-it-now switch
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- ExtUtils::Installed
- InhaltsvorschauProvides inventory management for installed modules, based on the contents of the .packlist files that are created during installation. It also permits classifying the installed files and extracting directory information from the .packlist files.new
$inst = ExtUtils::Installed->new( )Searches for all installed .packlists on the system and stores their contents. Takes no parameters; uses ExtUtils::Packlist to read the .packlist files.directories$inst->directories(module[, string[, dir[,...]]])Returns list of directories. Returns only directories that contain files from the specified module. Parameters are:- module
- Required. The name of a module; returns a list of all directories in the package.
- string
- Optional. Possible values are
prog,man, orallto return program directories, manual directories, or all directories, respectively. - dir
- Optional. One or more directories. If specified, only directories under the specified directories are returned.
directory_tree$inst->directory_tree(module[, string[, dir[,...]]])Likedirectories, but includes all intermediate directories.files$inst->files(module[, string[, dir[,...]]])Returns list of filenames. Parameters are:- module
- Required. The name of a module; returns a list of all filenames in the package. For a list of core files, use the special module name Perl.
- string
- Optional. Possible values are
prog,man, orallto return program files, manual files, or all files, respectively. - dir
- Optional. One or more directories. If specified, only filenames under the specified directories are returned.
modules$inst->modules( )Returns list of names of all the installed modules. Calls the Perl "core" by the special name Perl.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::Liblist
- InhaltsvorschauUsed for building a Makefile for a Perl module. Takes a list of libraries and returns platform-appropriate lines that can be included in the Makefile.
require ExtUtils::Liblist; ExtUtils::Liblist::ext($potential_libs[, $verbose]);
The input list$potential_libs is in the form -llib1 -llib2 -llib3. Additional library paths may be included in the form -L/another/path, which affects searches for all subsequent libraries. If the Boolean$verbose is specified, verbose output messages are provided. Returns a list of four scalar values:- EXTRALIBS
- List of libraries that need to be linked with ld when linking a Perl binary that includes a static extension
- LDLOADLIBS
- List of static or dynamic libraries that can or must be linked when creating a shared library using ld
- LD_RUN_PATH
- Colon-separated list of the directories in LDLOADLIBS
- BSLOADLIBS
- List of libraries that are needed but can be linked in dynamically with the DynaLoader at runtime
The Win32 version (in the standard Perl distribution) is different from the Unix-OS/2 version in several ways:- -l and -L are not required on the library and path specifications.
- Entries must be libraries, not plain object files.
- If
$potential_libs is empty, the return value is also empty. - The specified libraries can include both static and import libraries.
- LDLOADLIBS and EXTRALIBS are always identical; BSLOADLIBS and LD_RUN_PATH are always empty.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::MakeMaker
- InhaltsvorschauWrites a Makefile for module installation. Provides a function,
WriteMakefile, which creates an object with attributes that are set from various sources and that actually write the Makefile. See Chapter 2 for information about the using the Makefile and MakeMaker during module installation. This section explains the details of actually creating the Makefile with MakeMaker. It assumes an understanding of make and Makefiles.If you are a Perl programmer writing a module, you should run h2xs to generate the template for your module. Among other things, h2xs creates a file called Makefile.PL, and it's Makefile.PL that runs MakeMaker. On the other hand, if you are installing a module, you can usually just run the Makefile.PL that came with the module, perhaps adding a PREFIX argument if you are installing the module locally (see Chapter 2). In either case, you shouldn't need to run ExtUtils::MakeMaker directly unless you have special requirements.A typical call to MakeMaker might look like this example from the CGI distribution:use ExtUtils::MakeMaker; WriteMakefile( NAME => "CGI", DISTNAME => "CGI-modules", VERSION => "2.76", linkext => { LINKTYPE => '' }, dist => {COMPRESS=>'gzip -9f', SUFFIX => 'gz'}, );MakeMaker attributes can be passed as arguments toWriteMakefile, as in the example, or they can be passed as name=value pairs on the command line:perl Makefile.PL PREFIX=/home/mydir/Perl/Modules
To see what MakeMaker is doing, you can say:perl Makefile.PL verbose
The following attributes can be specified:- C
- Reference to array of *.c filenames. Initialized from a directory scan and the values portion of the XS attribute hash. Not currently used by MakeMaker but may be handy in Makefile.PLs.
- CCFLAGS
- String to be included in the compiler call command line between the INC and OPTIMIZE arguments.
- CONFIG
- An array reference containing a list of attributes to get from
%Config. The following values are always added to CONFIG:ar cc cccdlflags ccdlflags dlext dlsrc ld lddlflags ldflags libc lib_ext obj_ext ranlib sitelibexp sitearchexp so
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::Manifest
- InhaltsvorschauProvides utilities for maintaining and using a MANIFEST file. The MANIFEST file is essentially a packing list, included with a module, so the user who installs the module can be sure that all the files are actually present. The file created by ExtUtils::Manifest is a list of filenames, one per line, with an optional comment on each line.ExtUtils::Manifest optionally uses a file called MANIFEST.SKIP, which contains regular expressions specifying files that are not to be included in MANIFEST. Manifest also defines two global variables that are used by several of the functions:
-
$ExtUtils::Manifest::MANIFEST - The name of the MANIFEST file. Changing the value results in different MANIFEST and different MANIFEST.SKIP files. Default is MANIFEST.
-
$ExtUtils::Manifest::Quiet - If true, the functions work silently. Default is
0.
Provides six functions, which are exportable on request.filecheckfilecheckFinds files below the current directory that are not mentioned in the MANIFEST file. Consults MANIFEST.SKIP for files that shouldn't be included.fullcheckfullcheckDoes bothmanicheckandfilecheck.manicheckmanicheckChecks whether all files in current directory's MANIFEST file really exist.manicopymanicopy (read, target, how)Copies files to a target directory. Takes the following arguments:- read
- Hash with keys that are the names of the files to be copied. Typically returned by
maniread. - target
- Target directory into which files are to be copied.
- how
- Can be used to specify a different method of "copying." Values are:
-
cp - Copy the files.
-
ln - Create hard links.
-
best - Link the files, but copy any symbolic link to make a tree with no symbolic links (the default).
-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- ExtUtils::Miniperl
- InhaltsvorschauGenerates a file, perlmain.c, that contains the bootstrap code to make the modules associated with the libraries available from within Perl. ExtUtils::Miniperl itself is generated automatically from a script called minimod.PL when Perl is built; typically, it is used from within a Makefile generated by ExtUtils::MakeMaker rather than being called directly. The module exports one subroutine.writemainwritemain (dirs)Takes an argument list of directories that contain archive libraries needed by Perl modules and writes the file to be compiled as perlmain.c to STDOUT.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::Mkbootstrap
- InhaltsvorschauTypically called from a module's Makefile. It writes a *.bs file that is needed by some architectures to do dynamic loading.
use ExtUtils::Mkbootstrap; mkbootstrap( );
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::Mksymlists
- InhaltsvorschauProduces option files used by some operating systems' linkers during creation of shared libraries for dynamic extensions. Normally called from a Makefile when a module is built; it exports one function.MksymlistsMksymlists (varlist)Creates the linker option file. The varlist argument is a list of key/value pairs. For example:
use ExtUtils::Mksymlists; Mksymlists({ NAME => $name, DL_VARS => [$var1, $var2, $var3], DL_FUNCS => [$pkg1 => [$func1, $func2], $pkg2 => [$func3]});Valid keys are:-
DLBASE - The name by which the linker knows the module. If not specified, it is derived from the NAME attribute. Currently used only by OS/2.
-
DL_FUNCS - Identical to the MakeMaker DL_FUNCS attribute and usually taken from it. Its value is a reference to a hash, in which each key is a package name, and each value is a reference to an array of function names to be exported by the module.
-
DL_VARS - Identical to the MakeMaker DL_VARS attribute, and usually taken from it. Its value is a reference to an array of variable names to be exported by the extension.
-
FILE - The name of the linker option file (minus the OS-specific extension) if you don't want to use the default value (the last word of the NAME attribute).
-
FUNCLIST - An alternate way of specifying function names to be exported from the module. Its value is a reference to an array of function names to be exported, which are passed unaltered to the linker options file.
-
NAME - The name of the module for which the linker option file is to be produced. Should always be specified.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- ExtUtils::MM
- InhaltsvorschauExtUtils::MM is an OS-adjusted ExtUtils::MakeMaker subclass. For internal use only. For example:
require ExtUtils::MM; my $mm = MM->new(...);
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::MM_Any
- InhaltsvorschauPerforms platform-agnostic MM methods. ExtUtils::MM_Any is a superclass for the ExtUtils::MM_ set of modules. For internal use only.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::MM_BeOS
- InhaltsvorschauProvides methods to override Unix behavior in ExtUtils::MakeMaker. Essentially, this module works the same way as ExtUtils::MM_Unix, but allows override for BeOS. For internal use only.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::MM_DOS
- InhaltsvorschauProvides methods to override Unix behavior in ExtUtils::MakeMaker. Essentially, this module works the same way as ExtUtils::MM_Unix, but allows override for MS-DOS. For internal use only.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::MM_NW5
- InhaltsvorschauProvides methods to override Unix behavior in ExtUtils::MakeMaker. Essentially, this module works in the same way as ExtUtils::MM_Unix, but allows override for Netware 5. For internal use only.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::MM_OS2
- InhaltsvorschauProvides methods for use with MakeMaker for OS2 systems. Used internally by MakeMaker if needed. (See ExtUtils::MM_Unix for documentation of the methods provided there.) Overrides the implementation of the methods, not the interface.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::MM_Unix
- InhaltsvorschauProvides methods for MakeMaker to handle portability issues. You never need to
requirethis module, but you might want to if you are working on improving MakeMaker's portabilityProvides methods for both Unix and non-Unix systems; on non-Unix systems, they can be overridden by methods defined in other MM_* modules. The methods are the following.catdircatdir listConcatenates a list of directory names to form a complete path ending with a directory. On Unix, joins the names with/.catfilecatfile listConcatenates one or more directory names and a filename to form a complete path ending with a filename. On Unix, joins the names with/.dir_targetdir_target arrayTakes an array of required directory names and returns a Makefile entry to create an .exists file in the directories. Returns nothing if the entry has already been processed.file_name_is_absolutefile_name_is_absolute filenameTakes a path as argument and returns true if it is an absolute path.find_perlfind_perl version, \names, \dirs, traceSearches for an executable Perl. Takes the following arguments:- version
- The executable must be at least the version given by version.
- \names
- Array reference. The name of the executable must be an entry in the array.
- \dirs
- Array reference. The executable must be in a directory that is one of the entries in the array.
- trace
- If true, prints debugging information.
guess_nameguess_nameGuesses the name of the package based on the working directory's name. Called only if the NAME attribute is missing.has_link_codehas_link_codeReturns true if there are C, XS, MYEXTLIB, or similar objects in this object that need a compiler. Does not descend into subdirectories.libscanlibscan filenameEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::MM_UWIN
- InhaltsvorschauProvides methods to override Unix behavior in ExtUtils::MakeMaker. Essentially, this module works the same way as ExtUtils::MM_Unix, but allows override for the U/WIN emulator. For internal use only.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::MM_VMS
- InhaltsvorschauProvides methods for use with MakeMaker for VMS systems. Used internally by MakeMaker if needed. (See ExtUtils::MM_Unix for documentation of the methods provided there.) Overrides the implementation of the methods, not the interface.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::MM_Win32
- InhaltsvorschauProvides methods for use with MakeMaker for Win32 systems. Used internally by MakeMaker in the standard Win32 Perl distribution if needed. (See ExtUtils::MM_Unix for a documentation of the methods provided there.) Overrides the implementation of these methods, not the interface.catfilecatfileConcatenates one or more directory names and a filename to form a complete path, ending with a filename.constantsconstantsInitializes constants, .SUFFIXES, and .PHONY.dynamic_bsdynamic_bsDefines targets for bootstrap files.dynamic_libdynamic_libDefines how to produce the *.so (or equivalent) files.canonpathcanonpathPerforms a logical cleanup of a path.dist_cidist_ciChanges command-line quoting (same as MM_Unix version).dist_coredist_coreChanges command-line quoting (same as MM_Unix version).manifypodsmanifypodsDisables manpage process.pasthrupasthruDefines the string that is passed to recursive make calls in subdirectories.perl_scriptperl_script filenameTakes one argument, a filename, and returns the filename if the argument is likely to be a Perl script.pm_to_blibpm_to_blibDefines a target that copies all files in the hash PM to their destination and autosplits them. See ExtUtils::Install.static_libstatic_libDefines how to produce the *.a (or equivalent) files.test_via_harnesstest_via_harnessHelper method to write the test targets.tool_autosplittool_autosplitUse Win32-style quoting on command line.tools_othertools_otherWin32 overrides. Defines SHELL, LD, TOUCH, CP, MV, RM_F, RM_RF, CHMOD, and UMASK_NULL in the Makefile. Also defines the Perl programs MKPATH, WARN_IF_OLD_PACKLIST, MOD_INSTALL, DOC_INSTALL, and UNINSTALL.top_targetstop_targetsDefines the targets
all,subdirs,config, andO_FILES.xs_oxs_oDefines suffix rules to go from XS to object files directly.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::MY
- InhaltsvorschauAllows ExtUtils::MakeMaker subclass for customization. For internal use only.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- ExtUtils::Packlist
- InhaltsvorschauManages .packlist files. Supports an extended .packlist format. The original format is a list of absolute pathnames, one pathname per line. In the extended format, each line can also contain a list of attributes as key/value pairs, which are used by the installperl script. For example:
/usr/local/bin/perl from=/usr/local/pbeta/bin/perl5.005 type=link /usr/local/bin/perl5.005 type=file /usr/local/lib/perl5/5.005/AnyDBM_File.pm type=file
Also see ExtUtils::Installed.new$pl = ExtUtils::Packlist->new([plfile])Constructor. Takes the name of a .packlist as the optional parameter and returns a reference to a hash that has an entry for each line in the .packlist. The value associated with each key isundeffor oldstyle .packlists. For files in the extended format, the value for each key is a hash containing the key/value pairs on the line associated with that key.packlist_file$pl->packlist_file( )Returns the name of the associated .packlist file.read$pl->read([plfile])Reads the .packlist specified by the plfile parameter if given; otherwise, reads the file associated with$pl. CallsCarp::croakif the file doesn't exist.validate$pl->validate([arg])Checks that each file in the .packlist exists. An optional argument can be specified; if the argument is present and evaluates to true, missing files are removed from the internal hash. Returns a list of missing files, or an empty list if the files all exist.write$pl->write([plfile])Writes to a .packlist. Optionally takes the name of the .packlist to be written; otherwise, overwrites the .packlist associated with$pl. If the value associated with a hash key is a scalar, the entry written to the .packlist is a simple filename. If the value is a hash, the entry written is the filename followed by the key/value pairs from the hash.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ExtUtils::testlib
- InhaltsvorschauUsed for testing a module after it's been built and before it's been installed, when you don't want to (or can't) run make test. Adding:
use ExtUtils::testlib;
to your test program causes the intermediate directories used by make to be added to@INC, allowing you to run the test.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Fatal
- InhaltsvorschauProvides a way to replace functions that return false on failure with equivalents that die instead, so you can use the functions without having to test the return values explicitly. Fatal reports errors via
die; you can trap them with$SIG{_ _DIE_ _}if you want to take action before the program exits. You can use Fatal for both user-defined functions and Perl core operators exceptexecandsystem.importimport Fatal functionWraps function in an equivalent function that willdieon failure.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Fcntl
- InhaltsvorschauA translation of the C fcntl.h program that uses h2xs (which builds a Perl extension from a C header file) and the C compiler to translate
#definesymbols and make them available as functions. Exports the following routines by default; each routine returns the value of the#definethat is the same as the routine name:FD_CLOEXECF_DUPFDF_GETFDF_GETFLF_GETLKF_RDLCKF_SETFDF_SETFLF_SETLKF_SETLKWF_UNLCKF_WRLCKO_APPENDO_CREATO_EXCLEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - fields
- InhaltsvorschauPragma that provides the ability to define class fields at compile time by updating the
%FIELDShash in the calling package. The%FIELDShash is set up at compile time as well; use thebasepragma to copy fields from base classes, and thenfieldsto add new fields. Lets you have objects with named fields that are as compact and fast as arrays to access. For more details, see the fields manpage and the pseudo-hash section of the perlref manpage.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Basename
- InhaltsvorschauParses a file's path, returning its three component pieces: the path to the file, the file's basename, and the file's extension. For example, for:
/usr/local/lib/perl5/SelectSaver.pm
the path is /usr/local/lib/perl5, the basename is SelectSaver, and the extension is .pm. File::Basename exports the following functions.basenamebasename (fullname[, suffixlist])Returns the first element of the list that would be produced if you calledfileparsewith the same arguments. Provides compatibility with the Unix basename command. Takes the following arguments:- fullname
- Input file specification
- suffixlist
- Optional list containing patterns to be matched against the end of fullname to find the suffix
dirnamedirname (fullname)Returns the directory portion of the input file specification. fullname is the input file specification.fileparsefileparse (fullname[, suffixlist])Divides a file specification into its three parts, returning them in this order: filename, path, suffix.($name, $path, $suffix) = fileparse($fullname, @suffixlist)
The arguments are the same as forbasename.fileparse_set_fstypefileparse_set_fstype (os-string)Called before the other routines to select the appropriate file specification syntax for your operating system, to be used in future File::Basename calls. Currently valid values for os-string (the operating system) areVMS,MSWin32,MSDOS,AmigaOS,os2,RISCOS, andMacOS. Uses Unix syntax by default.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::CheckTree
- InhaltsvorschauRuns file tests on a set of files. Exports one function,
validate, which takes a single multiline string as input. Each line of the string contains a filename plus a test to run on the file. The test can be followed with|| dieto make it a fatal error if it fails. The default is|| warn. Prepending!to the test reverses the sense of the test. You can group tests (e.g.,-rwx); only the first failed test of the group produces a warning. For example:use File::CheckTree; $warnings += validate( q{ /vmunix -e || die /bin cd csh !-ug sh -ex /usr -d || warn "What happened to $file?\n" });Available tests include all the standard Perl file-test operators except -t, -M, -A, and -C. Unless it dies,validatereturns the number of warnings issued.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Compare
- InhaltsvorschauCompares the contents of two sources, each of which can be a file or a filehandle. Returns
0if the sources are equal,1if they are unequal, and-1on error. File::Compare provides two functions.cmpcmp (file1, file2[, buffsize])cmpis a synonym forcompare. Exported on request.comparecompare (file1, file2[, buffsize])Compares file1 to file2. Exported by default. If present, buffsize specifies the size of the buffer to use for the comparison.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Copy
- InhaltsvorschauCopies or moves files or filehandles from one location to another. Returns
1on success,0on failure, or sets$!on error.copycopy (source, dest[, buffsize])Copies source to dest. Takes the following arguments:- source
- The source string, FileHandle reference, or FileHandle glob. If source is a filehandle, it is read from; if it's a filename, the filehandle is opened for reading.
- dest
- The destination string, FileHandle reference, or FileHandle glob. dest is created if necessary and written to.
- buffsize
- Specifies the size of the buffer to be used for copying. Optional.
cpcp (source, dest[, buffsize])Likecopy, but exported only on request:use File::Copy "cp"
movemove (source, dest)Moves source to dest. If the destination exists and is a directory, and the source is not a directory, then the source file is renamed into the directory specified by dest. Return values are the same as forcopy.mvmv (source, dest)Likemove, but exported only on request:use File::Copy "mv"
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::DosGlob
- InhaltsvorschauProvides a portable enhanced DOS-like globbing for the standard Perl distribution. DosGlob lets you use wildcards in directory paths, is case-insensitive, and accepts both backslashes and forward slashes (although you may have to double the backslashes). Can be run three ways:
- From a Perl script:
require 5.004 use File::DosGlob 'glob'; @perlfiles = glob "..\pe?l/*.p?"; print <..\pe?l/*.p?>;
- With the perl command, on the command line:
# From the command line (overrides only in main::) % perl -MFile::DosGlob=glob -e "print <../pe*/*p?>"
- With the perlglob.bat program on the DOS command line:
% perlglob ../pe*/*p?
When invoked as a program from the command line, File::DosGlob prints null-separated filenames to STDOUT.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Find
- InhaltsvorschauLooks for files that match a particular expression. Exports two functions.findfind (\&wanted, dir1[, dir2 ...])Works like the Unix find command; traverses the specified directories, looking for files that match the expressions or actions you specify in a subroutine called
wanted, which you must define. For example, to print out the names of all executable files, you could definewantedthis way:sub wanted { print "$File::Find::name\n" if -x; }Provides the following variables:-
$File::Find::dir - Current directory name (
$_has the current filename in that directory). -
$File::Find::name - Contains
$File::Find::dir/$_. You are chdired to$File::Find::dirwhenfindis called. -
$File::Find::prune - If true,
finddoes not descend into any directories. -
$File::Find::dont_use_nlink - Set this variable if you're using the Andrew File System (AFS).
finddepthfinddepth (\wanted, dir1[, dir2...])Likefind, but does a depth-first search.The standard Perl distribution comes with a Perl script, find2perl, which takes a Unix find command and turns it into awantedsubroutine.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- File::Path
- InhaltsvorschauCreates and deletes multiple directories with specified permissions. Exports two methods.mkpathmkpath (path, bool, perm)Creates a directory path and returns a list of all directories created. Takes the following arguments:
- path
- Name of the path or reference to a list of paths to create.
- bool
- Boolean. If true,
mkpathprints the name of each directory as it is created. Default is false. - perm
- Numeric mode indicating the permissions to use when creating the directories. Default is
0777.
rmtreermtree (root, prt, skip)Deletes subtrees from the directory structure, returning the number of files successfully deleted. Symbolic links are treated as ordinary files. Takes the following arguments:- root
- Root of the subtree to delete or reference to a list of roots. The roots, and all files and directories below each root, are deleted.
- prt
- Boolean. If true,
rmtreeprints a message for each file, with the name of the file and whether it's usingrmdirorunlinkto remove it (or if it's skipping the file). Default is false. - skip
- Boolean. If true,
rmtreeskips any files to which you do not have delete access (under VMS) or write access (under other operating systems). Default is false.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Spec
- InhaltsvorschauPerforms common operations on file specifications in a portable way. To do this, it automatically loads the appropriate operating system-specific module, which is one of File::Spec::Mac, File::Spec::OS2, File::Spec::Unix, File::Spec::VMS, or File::Spec::Win32. The complete reference of available functions is given in File::Spec::Unix; the functions are inherited by the other modules and overridden as necessary. Subroutines should be called as class methods, rather than directly.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- File::Spec::Cygwin
- InhaltsvorschauImplements methods for Cygwin file specs. You do not need to call this module. It is called internally by File::Spec.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- File::Spec::Mac
- InhaltsvorschauFile::Spec for MacOS.canonpathFile::Spec->canonpathNothing to do; returns what it's given.catdirFile::Spec->catdir(dir[, dir...])Concatenates two or more directory names to form a complete path. Ends with a directory name and appends a trailing : if there isn't one. You can get a relative path by either beginning the first argument with : or putting "" as the first argument.catfileFile::Spec->catfile(dir[, dir...], file)Concatenates one or more directory names and a filename to form a complete path that ends with a filename. Uses
catdir.curdirFile::Spec->curdirReturns string representing the current directory.file_name_is_absoluteFile::Spec->file_name_is_absolute(path)Takes a path as argument and returns true if it is an absolute path.pathFile::Spec->pathReturns null list for MacPerl applications, or$ENV{Commands}, suitably split, for the MacPerl tool under MPW.rootdirFile::Spec->rootdirReturns string representing the root directory. Under MacPerl, returns the name of the startup volume.updirFile::Spec->updirReturns string representing the parent directory.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Spec::OS2
- InhaltsvorschauFile::Spec for OS/2. Overrides the implementation of the File::Spec::Unix methods, but not the interface.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- File::Spec::Unix
- InhaltsvorschauFile::Spec for Unix. Provides methods for File::Spec to use in manipulating file specifications.canonpathFile::Spec->canonpathDoes logical cleanup of path.catdirFile::Spec->catdir(dir[, dir...])Concatenates two or more directory names to form a complete path. Ends with a directory name.catfileFile::Spec->catfile(dir[, dir...], file)Concatenates one or more directory names and a filename to form a complete path that ends with a filename.curdirFile::Spec->curdirReturns
., representing the current directory.file_name_is_absoluteFile::Spec->file_name_is_absolute(path)Takes a path as argument and returns true if it is an absolute path.joinFile::Spec->join(dir[, dir...], file)Same ascatfile.no_upwardsFile::Spec->no_upwards(files)Strips names of files referring to a parent directory from a list of filenames. Doesn't strip symbolic links.pathFile::Spec->pathReturns the PATH environment variable as an array.rootdirFile::Spec->rootdirReturns/, representing the root directory.updirFile::Spec->updirReturns.., representing the parent directory.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Spec::VMS
- InhaltsvorschauFile::Spec for VMS. Overrides the implementation of the File::Spec::Unix methods, but not the interface.catdirFile::Spec->catdir(dirspecs)Concatenates a list of directories and returns the result as a VMS-syntax directory specification.catfileFile::Spec->catfile(filespecs)Concatenates a list of file specifications and returns the result as a path.curdirFile::Spec->curdirReturns string representing the current directory.file_name_is_absoluteFile::Spec->file_name_is_absolute(path)Takes a path as argument and returns true if it is an absolute path. Checks for VMS directory specification as well as Unix separators.pathFile::Spec->pathTranslates the logical name
DCL$PATHas a searchlist.rootdirFile::Spec->rootdirReturns string representing the root directory.updirFile::Spec->updirReturns string representing the parent directory.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Spec::Win32
- InhaltsvorschauFile::Spec for Win32. Overrides the implementation of the File::Spec::Unix methods, but not the interface.canonpathFile::Spec->canonpathPerforms logical cleanup of a path; doesn't physically check the filesystem.catfileFile::Spec->catfile(dir[, dir...], file)Concatenates one or more directory names and a filename to form a complete path that ends with a filename.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- File::stat
- InhaltsvorschauProvides the same file status information as the Perl functions
statandlstat. Exports two functions that return File::stat objects. The objects have methods that return the equivalent fields from the Unix stat(2) call:FieldMeaningdevDevice number of filesysteminoInode numbermodeFile modenlinkNumber of links to the fileuidNumeric user ID of ownergidNumeric group ID of ownerrdevDevice identifiersizeSize of file, in bytesatimeLast access timeEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - File::Temp
- InhaltsvorschauFile::Temp can be used to create and open temporary files safely. The
tempfile( )function returns the name and the open filehandle of a temporary file. Thetempdir( )function creates a temporary directory. File::Temp guarantees that race conditions cannot occur since it returns both a filehandle and filename. In addition, File::Temp checks for safe file and directory permissions, so the sticky bits are checked for group-writable directories. To write a temp file into /tmp (default), you would do something like the following:#!/usr/local/bin/perl -w use File::Temp qw(tempfile); my($fh, $filename) = tempfile( ); print "opening $filename for writing...\n"; print $fh "some data ...\n";
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - FileCache
- InhaltsvorschauCloses and reopens files as necessary so you can always write to a file even if you already have the maximum number of files open. Exports one function.cacheoutcacheout (path)Makes sure the file at path is created and accessible through the filehandle also named path. You don't need to invoke
cacheoutbetween successive accesses to the same file.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - FileHandle
- InhaltsvorschauProvides object methods for working with filehandles. Provides the following methods.new$fh = new FileHandle [filename[, mode]]Constructor. Creates a FileHandle, which is a reference to a newly created symbol. The optional parameters, filename and mode, are passed to
open. The FileHandle object is returned if the open succeeds; otherwise, it is destroyed.new_from_fd$fh = new_from_fd FileHandle fd, modeConstructor. Creates a FileHandle, but it takes the file descriptor, fd, instead of filename as a parameter, along with mode; the parameters are required.fdopen$fh->fdopen fdname [openmode]Likeopen, except that its first parameter is not a filename but a filehandle name, a FileHandle object, or a file descriptor number.getpos$pos = $fh->getposIf the C functionsfgetpos(3)andfsetpos(3)are available,getposreturns the current position,$pos, of the FileHandle.open$fh->open filename [openmode]Takes filename and, optionally, the open mode, and opens a file. If the mode is present, it can be in Perl form (e.g.,>,+<) or in POSIX form (e.g.,w,r+).setpos$fh->setpos posUses the value (pos) returned bygetposto restore a previous position of the FileHandle.setvbuf$fh->setvbuf(params)Takes the same parameters as the C functionsetvbuf(3)and uses the C function to set the buffering policy for the FileHandle.The following additional FileHandle methods act as front-ends for the corresponding built-in Perl functions (see the O'Reilly book Programming Perl or the perlfunc manpage for more details):clearerrgetccloseEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Filter::Simple
- InhaltsvorschauSource filtering is a nice feature of newer versions of Perl (5.6 and later) because it allows the programmer to write extensions to the Perl language without tampering with the Perl source code itself. That is, you can create a macro language out of Perl.Filter::Simple is based on Filter:Util::Call, but simplifies the means by which you can begin doing your own source filtering with Perl. Filter::Simple ships with the Perl 5.8 source kit.Using Filter::Simple is, well, easy. Basically, Filter::Simple implements
FILTER { ... }, which you can use to handle many of your simple source-filtering needs. Let's say that you want a good glass of ale, and you decide that you don't want Perl toprint, butpintinstead. You can implement something like the following with Filter::Simple. First, create a module called Print_to_Pint:package Print_to_Pint; use Filter::Simple; FILTER { s/pint/print/g; } # true 1;Now, use Print_to_Pint to do something withpint:#!/usr/local/bin/perl -w use Print_to_Pint; my $bottles = 99; my $last = 1; foreach my $bottle (reverse($last .. $bottles)) { pint "$bottle -> burp\n"; }By default, Filter::Simple ignoresnobehavior, i.e., it stops filtering after ano Moduleis encountered. You can alter this behavior by passing another argument touse Filter::Simpleor toFILTER { ... }. For example:package Print_to_Pint; use Filter::Simple; FILTER { s/pint/print/g; } "";Filter::Simple also supportsFILTER_ONLY, which allows you to support multiple filters to handle different parts of your source code.FILTER_ONLYtakes several subroutines as options:code,executable,string,regex,quotelike, andall.codeorexecutablefilters all Perl code, except Pod or_ _DATA_ _types.quotelikefilters other Perl quotelike stuff, including here documents.stringfilters all string-related parts.regexfilters all pattern-literal parts ofquotelike.For example, the following module will skip all incidences of Pod in the PodSucks module:package PodSucks; use Filter::Simple; FILTER_ONLY executable => sub { s/x/X/g }, executable => sub { print } # True. True. 1;Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Filter::Util::Call
- InhaltsvorschauProvides a framework for implementing source filters in Perl code. While you may use Filter::Util::Call directly, we suggest you use Filter::Simple instead.For example:
package Milter; # Could just as well be called 'OldJoke' use Filter::Util::Call ; sub import { my($type) = @_ ; filter_add(bless []) ; } sub filter { my($self) = @_; my($status); s/Shut-Up/Trouble/g if ($status = filter_read()) > 0; $status ; } 1;You'd use the above in your code like so:#!/usr/local/bin/perl -w use Milter; print "Are you looking for Shut-Up?\n" ;
This prints:Are you looking for Trouble?
Filter::Util::Call implements the following methods.filterfilter()Performs the main processing for the filter. Used with closure filters; that is, a closure filter handles the lexical variables that are maintained by the closure. The finished source, as processed byfilter, will be returned in$_.filterreturns a status, as follows:-
< 0 - An error has been encountered.
-
EOF - End-of-file has been reached unexpectedly.
-
> 0 - Everything is OK.
filter_addfilter_add(ref)Installs the filter.filter_addtakes one parameter, a reference, and depending on the kind of reference used, dictates which of the two filter types is used. CODE references result in a closure filter; otherwise, method filters are assumed.filter_delfilter_del()Disables the current filter. It doesn't destroy any filters, just tells Perl to stop using them.filter_readfilter_read(n)Obtains a line or block from the next filter in the chain. If there are no other filters, then the actual source file is obtained. For example:$status = filter_read(); # Requests a line $status = filter_read($size); # Requests a block of $size
filter_read_exactfilter_read_exact()Obtains a line or block from the next filter in the chain. If there are no other filters, then the actual source file is obtained.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- FindBin
- InhaltsvorschauFinds the full path to a script's bin directory, letting you use relative paths to that directory without needing to know the actual location:
use FindBin; use lib "$FindBin::Bin/../lib";
or:use FindBin qw($Bin); use lib "$Bin/../lib";
FindBin exports the following variables:-
$Bin - Path to bin directory from which script was invoked
-
$Script - Basename of script from which Perl was invoked
-
$RealBin $Binwith all links resolved-
$RealScript $Scriptwith all links resolved
If you invoke Perl with the -e option or read the Perl script from STDIN, then FindBin sets both$Binand$RealBinto the current directory.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- GDBM_File
- InhaltsvorschauAllows Perl programs to make use of the facilities provided by the GNU
gdbmlibrary. Most of the libgdbm.a functions are available as methods of the GDBM_File interface. (See the gdbm(3) manpage and the description of DB_File in this chapter.) The following is an example of the use of GDBM_File:use GDBM_File; tie %hash, "GDBM_File", $filename, &GDBM_WRCREAT, 0644); # Read/writes of %hash are now read/writes of $filename untie %hash;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Getopt::Long
- InhaltsvorschauLets your program accept command-line options with long names, introduced by
--. Standard single-character options are also accepted. Options that start with--may have an argument appended, following a space or an equals sign (=):--foo=bar --foo bar
Provides two functions:GetOptionsandconfig.configGetopt::Long::config(optionlist)Sets the variables in optionlist to change the default behavior ofGetOptions. The following options are available:-
$Getopt::Long::autoabbrev - If true, option names can be invoked with unique abbreviations. Default is
1(true) unless the environment variablePOSIXLY_CORRECThas been set. -
$Getopt::Long::getopt_compat - If true, options can start with
+. Default is1unless the environment variablePOSIXLY_CORRECThas been set. -
$Getopt::Long::order - Value indicates whether options and non-options may be mixed on the command line:
-
$PERMUTE - Non-options may be mixed with options. The default if
POSIXLY_CORRECTis not set. -
$REQUIRE_ORDER - Mixing is not allowed. The default if
POSIXLY_CORRECTis set.
-
-
$Getopt::Long::ignorecase - If true, ignore case when matching options. Default is
1. -
$Getopt::Long::VERSION - The version number of this Getopt::Long implementation in the format major.minor.
-
$Getopt::Long::error - Internal error flag. May be incremented from a callback routine to cause options-parsing to fail.
-
$Getopt::Long::debug - If true, enables debugging output. Default is
0(false).
GetOptions$result = GetOptions(option-descriptions)Uses descriptions from option-descriptionsto retrieve and process the command-line options with which your Perl program was invoked. The options are taken fromEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Getopt::Std
- InhaltsvorschauProcesses single-character, command-line options with option clustering. Exports two functions, which analyze
@ARGV, extract information about the options, and return this information to your program in a set of variables. Processing of@ARGVstops when an argument without a leading-is encountered, if that argument is not associated with a preceding option. Otherwise,@ARGVis processed to the end and left empty.getoptgetopt ('switches'[, \%opts])switches is a string of the command-line options that take arguments. For each option,getoptsets$opt_x (in which x is the switch) to the value entered as an argument. If\%optsis specified, it is a reference to a hash in whichgetoptsets the key to the name of the switch and the value to the argument (and the$opt_variables are not set).getoptsgetopts ('switches'[, \%opts])Likegetopt, except that all valid options are included in switches, and options that take an argument are followed by a colon (:). For example:getopt('oDI') # -o, -D, & -I take arguments; there may # be other options getopts('o:DI') # -o, -D, and -I are the only valid # options; only -o takes an argument\%opts means the same as withgetopt.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Hash::Util
- InhaltsvorschauOffers a selection of general-utility hash subroutines. Starting with Perl 5.8, hashes allow you to restrict access to the data that's stored in the hash. Individual keys can be locked so they cannot be deleted, nor can their values be changed. Hash::Util is largely intended to replace the deprecated pseudo-hashes.For example:
#!/usr/local/bin/perl -w %hash = (foo => 42, bar => 23); lock_keys(%hash); # Now, try to set %hash{'something'} while(my($key, $value) = each %hash) { print "$key -> $value\n"; } unlock_keys(%hash);You can lock specific values as follows:#!/usr/local/bin/perl -w %hash = (foo => 42, bar => 23); lock_key(%hash, 'foo'); # Now, try to set 'foo' and see what happens unlock_keys(%hash, 'foo');
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - I18N::Collate
- InhaltsvorschauThe use of I18N::Collate is now deprecated, although it is still provided for compatibility with older programs. Don't use it in new programs, because its functionality was integrated into the core Perl in Perl 5.004. See the
localepragma.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - I18N::Langinfo
- InhaltsvorschauProvides locale-specific information for constants supported in langinfo.h. I18N::Langinfo implements just one function,
langinfo.langinfolanginfo(constant)Returns the locale-specific data associated with the specified constant. For example, the following prints the date and time in the format for the current locale:print langinfo(D_T_FMT);
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - I18N::LangTags
- InhaltsvorschauImplements language tags per RFC 3066. Language tags let you specify a certain language that you'll use in a segment of text or code. I18N::LangTags lets you perform a number of common tasks with language tasks that you might come across when dealing with different protocols and applications.I18N::LangTags is shipped with the Perl 5.8 source kit. It implements the following methods.alternate_language_tagsalternate_language_tags(language)Returns all language tags that are alternate forms of language:
alternate_language_tags('en'); # Returns () alternate_language_tags('he'); # Returns ('iw') alternate_language_tags('iw'); # Returns ('he')encode_language_tagencode_language_tag(language)Returns the encoding of a language tag. Returnsundefif language is invalid.extract_language_tagsextract_language_tags(source)Returns a list of what is perceived as valid language tags from source. For example:my $chewbacca_dialect = 'growl, growl, fr, growl, growl!'; extract_language_tags($chewbacca_dialect); # Returns 'fr' Chewbacca is French?! Say it isn't so!
is_dialect_ofis_dialect_of(lang1, lang2)Returns true if lang1 represents a form of lang2. It doesn't go both ways, so make sure that lang1 comes first.is_dialect_of('en-US', 'en'); # true is_dialect_of('en', 'en-US'); # falseis_language_tagis_language_tag(language)Returns true if language is a valid language tag. For example:my $gutteral = 'Chewbacca'; is_language_tag($gutteral); # false my $pourquois = 'fr'; is_language_tag($pourquois); # true
locale2language_taglocale2language_tag(locale)Takes a locale name and maps it to a language tag. Certain tags aren't mappable, such asCorPOSIX, in which caselocal2language_tagwill return an empty list.locale2language_tag('en'); # Returns 'en' locale2language_tag('POSIX'); # Returns undef or ()same_language_tagsame_language_tag(lang1, lang2)Returns true if lang1 and lang2 both represent the same language form. For example:same_language_tag('en', 'en-US'); # Returns false en != en-USsimilarity_language_tagEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - I18N::LangTags::List
- InhaltsvorschauProvides a lengthy and nearly comprehensive list of any language tags that you might need, from
abtozn. You should refer to the I18N::LangTags::List documentation for the list of these tags and what they represent.I18N::LangTags::List implements thename()function that takes a language tag and returns its best attempt at an English name for it. Ifname()doesn't understand the language tag, it returnsundef.For example:#!/usr/local/bin/perl -w use I18N::LangTags::List; my $tag = 'en-CA'; print "What is this tag aboot? ", I18N::LangTags::List::name($tag), "\n";
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - if
- InhaltsvorschauThe
ifpragma "uses" a Perl module if a condition exists. For example:use if CONDITION, MODULE => ARGUMENTS;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - integer
- InhaltsvorschauPragma that tells the compiler to use integer operations from here to the end of the enclosing block. Improves processing time on systems without floating-point hardware support.
use integer; $x = 10/3; # $x is now 3, not 3.33333333333333333
Use thenointegerdirective to turn offintegerinside an inner block.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IO
- InhaltsvorschauLoads all of the following IO modules with a single
usestatement: IO::Handle, IO::Seekable, IO::File, IO::Pipe, and IO::Socket.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IO::File
- InhaltsvorschauInherits from IO::Handle and IO::Seekable, extending them with methods specific to filehandles. Provides three such methods.new$fh = new ([params])Constructor. Creates an IO::File object, passing any parameters to the method
open. If the open fails, the object is destroyed. Otherwise, it is returned to the caller.new_tmpfile$fh = new_tmpfileConstructor. Creates an IO::File object opened for read/write on a newly created temporary file. If the system permits, the temporary file is anonymous; if the temporary file cannot be created or opened, the object is destroyed. Otherwise, it is returned to the caller.open$fh->open(filename[, mode[, perms]])Opens the newly created filehandle. Accepts one, two, or three parameters. With one parameter, it acts as a frontend for Perl's built-inopenfunction. With two parameters, the first parameter is a filename, and the second is the open mode, optionally followed by a third parameter, the file permission value.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IO::Handle
- InhaltsvorschauThe base class for all other IO handle classes. Its main purpose is for the other IO classes to inherit from it; programs should not create IO::Handle objects directly. Provides the following methods.newnewConstructor. Creates a new IO::Handle object.new_from_fdnew_from_fd (fd, mode)Constructor. Like
new, creates an IO::Handle object. It requires two parameters, which are passed to the methodfdopen; iffdopenfails, the object is destroyed. Otherwise, it is returned to the caller.clearerr$fh->clearerrClears the given handle's error indicator.error$fh->errorReturns true if the given handle has experienced any errors since it was opened or since the last call toclearerr.fdopen$fh->fdopen (fd, mode)Like an ordinaryopenexcept that the first parameter is a filehandle name, an IO::Handle object, or a file descriptor number.flush$fh->flushFlushes the given handle's buffer.getline$fh->getlineWorks like<$fh>, described in the section on "I/O Operators" in the perlop manpage, but is more readable and can be safely called in an array context, while still returning one line.getlines$fh->getlinesWorks like<$fh>when called in an array context to read all the remaining lines in a file, but is more readable.croaks if called in scalar context.opened$fh->openedReturns true if the object is currently a valid file descriptor.ungetc$fh->ungetc (ord)Pushes a character with the ordinal value ord back onto the given handle's input stream.untaint$fh->untaintSpecial method for working under -T and setuid/gid scripts. Marks the object as taint-clean, and as such, data read from it is also considered taint-clean.write$fh->write (buf, len[, offset])Likewritefound in C; that is, the opposite ofread. The wrapper for the Perlwritefunction isformat_write.IO::Handle also provides the following methods, which are not described in detail here because they are simply frontends for the corresponding built-in functions. See Chapter 5 for more information.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IO::Pipe
- InhaltsvorschauProvides an interface for creating pipes between processes.new$pipe = new IO::Pipe([readfh, writefh])Constructor. Creates an IO::Pipe object, which is a reference to a newly created symbol. The two optional arguments should be objects blessed into IO::Handle or one of its subclasses. These objects are used for the system call to
pipe. With no arguments, the methodhandlesis called on the new IO::Pipe object.handles$pipe->handles( )Called during construction byIO::Pipe::newon the newly created IO::Pipe object. Returns an array of two objects blessed into IO::Pipe::End, or a subclass.reader$pipe->reader([args])Object is reblessed into a subclass of IO::Handle and becomes a handle at the reading end of the pipe. If there are any args, thenforkis called, and the arguments are passed toexec.writer$pipe->writer([args])The object is reblessed into a subclass of IO::Handle and becomes a handle at the writing end of the pipe. If there are any args, thenforkis called, and the arguments are passed toexec.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IO::Seekable
- InhaltsvorschauIntended to be inherited by other IO::Handle-based objects to provide methods that allow you to seek the file descriptors. Has no constructor.
use IO::Seekable; package IO::XXX; @ISA = qw(IO::Seekable);Provides two methods.seek$fh->seek(offset, whence)Frontend for the corresponding built-inseekfunction, which sets a filehandle's position in the file. Takes the following arguments:- offset
- The offset where you want to set the position.
- whence
- The position in the file that the offset is relative to. Possible values are:
0for the beginning of the file,1for the current position, or2for end of file. May also be expressed as the following constants, which are exported:-
SEEK_SET - Beginning of file
-
SEEK_CUR - Current position
-
SEEK_END - End of file
-
tell$fh->tell( )Frontend for the corresponding built-intellfunction, which returns the current file position in bytes (starting from 0).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IO::Select
- InhaltsvorschauImplements an object-oriented approach to the system
selectfunction call. Allows the user to see which I/O handles are ready for reading, writing, or have an error condition pending.newnew $s = IO::Select->new([handles])Constructor. Creates a new object and optionally initializes it with a set of handles.add$s->add(handles)Adds list of handles to the IO::Select object, to be returned when an event occurs. IO::Select keeps the list of handles in a cache, which is indexed by the handle's file number. Each handle can be an IO::Handle object, an integer, or a reference to an array, in which the first element is an IO::Handle object or an integer.bits$s->bits( )Returns the bit string that is suitable for use as an argument to the coreselectcall.can_read$s->can_read([timeout])Returns array of handles that are ready for reading. timeout is the maximum amount of time to wait before returning an empty list. If timeout is not given, and any handles are registered, then the call blocks.can_write$s->can_write([timeout])Same ascan_read, but checks for handles that can be written to.count$s->count( )Returns the number of handles that the object checks for when one of thecan_methods is called or the object is passed to theselectstatic method.exists$s->exists(handle)Returns the handle if it is present; otherwise, returnsundef.handles$s->handlesReturns an array of all registered handles.has_error$s->has_error([timeout])Same ascan_read, but checks for handles that have an error condition.remove$s->remove(handles)Removes all the given handles from the object, locating them by file number.select$s->select(read, write, error[, timeout])Static method. Call it with the package name as withnew.read,write, anderrorare eitherundefor IO::Select objects. The optional argument timeout has the same effect as for the coreselectcall.Returns an array of three elements, each a reference to an array or an empty array on error. The arrays hold the handles that are ready for reading, ready for writing, and have error conditions, respectively.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IO::Socket
- InhaltsvorschauProvides an object interface to creating and using sockets. It is built on the IO::Handle interface and inherits all the methods defined by IO::Handle.IO::Socket defines methods for only those operations that are common to all types of socket. IO::Socket exports all functions (and constants) defined by Socket. See Chapter 13 for detailed information.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- IPC::Msg
- InhaltsvorschauSystem V Msg IPC object class. Uses constants defined in IPC::SysV.new$msg = new IPC::Msg(key, flags)Creates a new message queue associated with key and uses flags to set the permissions. Creates the new message queue if the following are true:
- key is equal to IPC_PRIVATE.
- key doesn't already have an associated message queue, and
FLAGS & IPC_CREATis true.
id$msg->idReturns the system identifier for the message queue.rcv$msg->rcv(buf, len[, type[, flags]])Reads a message from the queue, returning the type of the message.remove$msg->removeRemoves and destroys the message queue.set$msg->set(stat) $msg->set(name=>value[,name=>value...])Accepts either a stat object as returned by thestatmethod or a list of name/value pairs and sets the following values of the stat structure associated with the message queue:uid gid mode (the permission bits) qbytes
snd$msg->snd(type, msg[, flags])Puts a message of type type on the queue with the data from msg. See themsgsndfunction.stat$ds = $msg->statReturns an object of type IPC::Msg::stat (which is a subclass of Class::Struct) that provides the following fields:uid gid cuid cgid mode qnum qbytes lspid lrpid stime rtime ctime
See thestatfunction and your system documentation for more information.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IPC::Open2
- InhaltsvorschauOpens a child process that allows two-way communication between your program and the child. Returns the process ID of the child process or reports a fatal error on failure. Exports one function.open2open2 (\*rdr, \*wtr, cmd_with_args)Forks a child process to execute the specified command. Takes the following arguments:
-
\*rdr - Represents a read filehandle that your program can use to read from the command $cmd's standard output. Can be a filehandle object or a reference to a typeglob.
-
\*wtr - Represents a write filehandle that your program can use to write to the command $cmd's standard input. Can be a filehandle object or a reference to a typeglob.
- cmd_with_args
- The command to be executed by the child process and its arguments. Can be specified two ways:
$cmd_with_args $cmd, "arg1", "arg2", ...
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- IPC::Open3
- InhaltsvorschauIPC::Open3 works like IPC::Open2.
use IPC::Open3; $pid = open3($wtr, $rdr, $err, $cmd_with_args); $pid = open3($wtr, $rdr, $err, $cmd, "arg1", "arg2", ...);
The following differences apply:- The first two arguments (
$wtr and$rdr) are passed in the opposite order. - A third filehandle can be passed, for standard error. If this argument is given as "", then STDERR and STDOUT for
$cmdare on the same filehandle. - If
$wtrbegins with<, then the leading<is stripped from the name, and the remainder is assumed to be a regular filehandle for an open file, rather than a reference to a typeglob.open3opens this file as STDIN for$cmdand closes it in the parent. Likewise, if$rdror$errbegins with>, then$cmddirects STDOUT or STDERR directly to that file rather than to the parent.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IPC::Semaphore
- InhaltsvorschauSystem V Semaphore IPC object class. Uses constants defined in IPC::SysV.new$sem = new IPC::Semaphore(key, nsems, flags)Creates a new semaphore set associated with key and containing nsems semaphores. Uses flags to set the permissions. Creates the new set if the following are true:
- key is equal to IPC_PRIVATE.
- key doesn't already have an associated semaphore identifier, and
FLAGS & IPC_CREATis true.
getall$sem->getallReturns the values of the semaphore set as an array.getncnt$sem->getncnt(sem)Returns the number of processes waiting for the semaphore sem to become greater than its current value.getpid$sem->getpid(sem)Returns the process ID of the last process that operated on semaphore sem.getval$sem->getval(sem)Returns the current value of semaphore sem.getzcnt$sem->getzcnt(sem)Returns the number of processes waiting for the semaphore sem to become0.id$sem->idReturns the system identifier for the semaphore set.op$sem->op(oplist)Passes a list of operations to thesemopfunction. oplist is the list of operations, consisting of a concatenation of smaller lists. Each of the smaller lists has three values: the semaphore number, the operation, and a flag. See thesemopfunction in Chapter 5 for more information.remove$sem->removeRemoves and destroys the semaphore set.set$sem->set(stat $sem->set(name=>value[, name=>value...])Accepts either a stat object as returned by thestatmethod or a list of name/value pairs and sets the following values of the stat structure associated with the semaphore set:uid gid mode (the permission bits)
setall$sem->setall(values)Sets the values of all the semaphores in the set to those given by the values list. The number of values on the list must match the number of semaphores in the set.setval$sem->setval(n, value)Sets the nth value in the semaphore set to value.stat$ds = $sem->statReturns an object of typeIPC::Semaphore::stat(which is a subclass of Class::Struct) that provides the following fields:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - IPC::SysV
- InhaltsvorschauDefines and conditionally exports all the constants defined in your system include files that are needed by the System V IPC calls.ftokftok (path, id)Returns a key based on path and id for use by
msgget,semget, andshmget.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - less
- InhaltsvorschauPragma, currently unimplemented, that may someday be a compiler directive to make certain trade-offs, such as:
use less 'memory';
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - lib
- InhaltsvorschauPermits adding additional directories to Perl's default search path at compile time. The directories are added at the front of the search path.
use lib list;adds the directories specified in list to@INC.For each directory $dir in list,liblooks for an architecture-specific subdirectory that has an auto subdirectory under it—that is, it looks for $dir/$archname/auto. If it finds that directory, then $dir/$archname is also added to the front of@INC, preceding $dir.Normally, you should only add directories to@INC. However, you can also delete directories. The statement:no lib listdeletes the first instance of each named directory from@INC. To delete all instances of all the specified names from@INC, specify:ALLas the first parameter of list.As with adding directories,libchecks for a directory called $dir/$archname/auto and deletes the $dir/$archname directory from@INC. You can restore@INCto its original value with:@INC = @lib::ORIG_INC;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - List::Util
- InhaltsvorschauA collection of list-related subroutines. As of Perl 5.8, List::Util is included with the Perl source kit.You can get the first item of a list (that matches the condition in BLOCK) like so:
#!/usr/local/bin/perl -w use List::Util qw(first); my @ll = qw(one two three); my $fir = first { defined($_) } @ll; print "$fir\n"; # Prints 'one'List::Util implements (but does not export) the following methods.firstfirst { BLOCK } @listEvaluates a block of Perl code and sets$_to each element of the list in turn. If BLOCK is true,firstreturns the first element. If BLOCK never returns true, or@list has no items, thenfirstreturnsundef. Note thatfirstdoesn't necessarily return the first item in a list. Consider the following:my @ll = qw(1 2 3); my $fir = first { $_ > 1 } @ll; print "$fir\n"; # Prints '2', since as 2 is the first item # in BLOCK that's > 1maxmax @listReturns the entry in the list with the highest numerical value. If the list is empty,maxreturnsundef:my @ll = qw(100 294 2 4 95 73); my $max_num = max @ll; print "$max_num\n"; # Prints '294'
maxstrmaxstr @listSimilar tomax, except thatmaxstrtreats all list items as strings.maxstrwill return the "highest string" as determined by thegtoperator. As always, if list is empty,maxstrreturnsundef.my @ll = qw(1 3 5 nate Person pizza man carl_everett dinosaur); my $max_s = maxstr(@ll); print "$max_s\n"; # Prints 'pizza'
minmin @listReturns the lowest numerical value. If the list is empty,minreturnsundef.minstrminstr @listTreats all list items as strings, but returns the "lowest string" as determined by theltoperator. If the list is empty,minstrreturnsundef.reducereduce { BLOCK } @listLiterally "reduces"@list by calling BLOCK until there are no more items to operate on in@list.reducesets$aand$bfor each operation in BLOCK and returns the reduced list as a scalar. IfEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - locale
- InhaltsvorschauPragma that tells the compiler to disable (or enable) the use of POSIX locales for built-in operations (LC_CTYPE for regular expressions and LC_COLLATE for string comparison). Each
no localeoruse localeaffects statements to the end of the enclosing block.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Math::BigFloat
- InhaltsvorschauProvides methods that permit use of floating-point numbers of arbitrary length. The following apply to all methods, except as noted:
- The object
$f remains unchanged. - All methods except
fcmpreturn a number string (nstr) of the form/[+-]\d+E[+-]\d+/, with embedded whitespace ignored. - A return value of
NaNindicates that either an input parameter was "Not a Number" or that an illegal operation was attempted. - A similar default scale value is computed for square roots.
new$f = Math::BigFloat->new(string)Creates a new object,$f.fabs$f->fabs( )Returns absolute value of$f.fadd$f->fadd(nstr)Returns sum of nstr and$f.fcmp$f->fcmp(nstr)Compares$f to nstr. Returns-1,0, or1depending on whether$f is less than, equal to, or greater than nstr, orundefif nstr is not a number.fdiv$f->fdiv(nstr[,n])Returns$f divided by nstr to nplaces. If scale (the number of digits) is unspecified, division is computed to the number of digits given by:max($div_scale, length(dividend)+length(divisor))
ffround$f->ffround(n)Returns$f rounded at nth place.fmul$f ->fmul(nstr)Returns$f multiplied by nstr.fneg$f->fneg( )Returns negative of$f.fnorm$f->fnorm( )Returns normalization of$f.fround$f->fround(n)Returns value of$frounded to n digits.fsqrt$f->fsqrt([n])Returns square root of$f to n places.fsub$f->fsub(nstr)Returns$f minus nstr.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Math::BigInt
- InhaltsvorschauAllows use of arbitrary length integers, in which the following apply to all methods, except as noted:
- The object
$i remains unchanged. - Big integer strings (bints) have the form
/^\s*[+-]?[\d\s]+$/. - All methods except
bcmpreturn a big integer string or strings. - Embedded whitespace is ignored.
- Output values are always in the canonical form:
/^[+-]\d+$/. - The return value
NaNresults when an input argument is not a number, or when a divide by zero is attempted.
new$i = Math::BigInt->new(string)Creates a new object,$i.babs$i->babsReturns absolute value of$i.badd$i->badd(bint)Returns sum of bint and$i.bcmp$i->bcmp(bint )Compares$i to bint. Thebcmpmethod returns-1,0, or1depending on whether$f is less than, equal to, or greater than the number string given as an argument. If the number string is undefined or null,undefis returned.bdiv$i->bdiv(bint)Returns$i divided by bint. In list context, returns a two-element array containing the quotient of the division and the remainder; in scalar context, returns only the quotient.bgcd$i->bgcd(bint)Returns greatest common divisor of$i and bint.bmod$i->bmod(bint)Returns$i modulus bint.bmul$i->bmul(bint)Returns$i multiplied by bint.bneg$i->bnegReturns negative of$i.bnorm$i->bnormReturns normalization of$i.bsub$i->bsub(bint)Returns$i minus bint.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Math::BigInt::Calc
- InhaltsvorschauSupports big integer calculations. Math::BigInt::Calc allows you to use library modules for core math routines. This module is shipped with the Perl 5.8 source kit.If you've written a module that uses the same API as Math::BigInt, you can use Math::BigInt::Calc as follows:
use Math::BigInt lib => 'yourlibname'; use Math::BigInt lib => 'Math::BigInt::yourlibname';
Math::BigInt exports the following functions, which must be defined in your module so Math::BigInt can support it:-
_new(string) - Returns a reference to new object from reference to decimal string.
-
_zero() - Returns a new object with value
0. -
_one() - Returns a new object with value
1. -
_str(obj) - Returns a reference to a string representing the object.
-
_num(obj) - Returns a Perl integer or floating-point number. This may not necessarily be accurate, depending on machine-dependent, floating-point size limitations.
-
_add(obj,obj) - Allows simple addition of two objects.
-
_mul(obj,obj) - Allows multiplication of two objects.
-
_div(obj,obj) - Implements division of the first object by the second. In a list context,
div()returns result, remainder. -
_sub(obj,obj) - Implements simple subtraction of one object from another. A third, optional parameter indicates that the parameters are swapped.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Math::BigRat
- InhaltsvorschauAllows you to use arbitrarily big rationals. Math::BigRat is shipped with the Perl 5.8 source kit.For example:
#!/usr/local/bin/perl -w use Math::BigRat; my $rat = Math::BigRat->new('2/7'); print $rat->bstr(), "\n";Math::BigRat implements the following methods.newnew(value)Creates a new Math::BigRat object. You can use all types of input fornew():'3/5','2/33','6/9', etc.denominatordenominator()Returns a copy of the denominator as a positive BigInt:my $rat = Math::BigRat->new('2/7') print $rat->denominator(), "\n"; # Prints 7numeratornumerator()Returns a copy of the numerator as a signed BigInt:my $rat = Math::BigRat->new('2/7'); print $rat->numerator(), "\n"; # Prints 2partsparts()Returns a list consisting of a signed numerator and unsigned denominator. Both are BigInts.my($n, $d) = $rat->parts(); ### Ewwww, rat parts! print "numerator: $n\n"; print "denominator: $d\n";
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Math::Complex
- InhaltsvorschauProvides support for complex numbers, including a full set of mathematical functions; permits creation and manipulation of complex numbers. Numerous overload and other operations are provided for working with complex numbers. See the documentation for the module for the complete list and also for a discussion of complex numbers. The following methods are provided.emake$z = Math::Complex->emake(args) cplxe $z = cplxe(args)Creates a complex number using the polar form.display_formatdisplay_format ([format])When called as a method, sets display format for current object. If format is not specified, returns the current setting. Possible settings are:
-
c - Cartesian format
-
p - Polar format
When called as a function, overrides the default display format, which is Cartesian.make$z = Math::Complex->make(args) cplx $z = cplx(args)Creates a complex number using the Cartesian form.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Math::Trig
- InhaltsvorschauDefines many trigonometric functions not defined by the core Perl, plus the constant
piand some additional functions for converting angles. For example:use Math::Trig; $x = tan(0.9); $halfpi = pi/2;The following functions are defined. A slash (/) between two functions means the values are aliases.-
acsc/acosec,asec,acot/acotan - Arcus cofunctions of sine, cosine, and tangent
-
acsch/acosech,asech,acoth/acotanh - Arcus cofunctions of hyperbolic sine, cosine, and tangent
-
asin,acos,atan - Arcus (inverse) functions of sine, cosine, and tangent
-
asinh,acosh,atanh - Arcus functions of hyperbolic sine, cosine, and tangent
-
atan2(y,x) - Principal value of arc tangent of y/x
-
csc/cosec,sec,cot/cotan - Cofunctions of sine, cosine, and tangent
-
csch/cosech,sech,coth/cotanh - Cofunctions of hyperbolic sine, cosine, and tangent
-
deg2rad - Degrees to radians
-
deg2grad - Degrees to gradians
-
grad2deg - Gradians to degrees
-
grad2rad - Gradians to radians
-
pi - The trigonometric constant π
-
rad2deg - Radians to degrees
-
rad2grad - Radians to gradians
-
sinh,cosh,tanh - Hyperbolic sine, cosine, and tangent
-
tan - Tangent
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- MIME::Base64
- InhaltsvorschauProvides functions to encode and decode strings into the Base64 encoding scheme as specified in RFC 2045 (dealing with MIME, or Multipurpose Internet Mail Extensions). Base64 encoding was designed to represent data in octets in an encoded form; all data is encoded using a 65-character subset, which is comprised of
A-Z,a-z,0-9+,/, and=. MIME::Base64 ships with the Perl source kit as of 5.8.For example:#!/usr/local/bin/perl -w use MIME::Base64; my $stone = 'purplebarneystone'; my $b64 = encode_base64($stone); print "$b64\n";
MIME::Base64 implements the following functions, both of which are exported.decode_base64decode_base64(string)Unpacks the base64-encoded string and returns the decoded data. In addition,decode_base64ignores any character that's not part of the recognized 65-character base64 subset.encode_base64encode_base64(string, [end_of_line])Base64-encodes string with the optional end_of_line argument. To base64-encode a JPEG image that lives in a file, you should specify end_of_line, sinceencode_base64returns base64-encoded content that's broken down into 76 characters per line. If you do not want the 76-character breaks to be imposed on you, set end_of_line to an empty string ("").Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - MIME::QuotedPrint
- InhaltsvorschauProvides functions to encode and decode strings into the quoted-printable encoding as specified in RFC 2045 (MIME). Quoted-printable encoding is used to represent data that's comprised of data that corresponds to ASCII characters. Nonprintable characters are represented by a triplet consisting of the
=character followed by two hexadecimal digits. MIME::QuotedPrint ships with the Perl source kit as of 5.8.MIME::QuotedPrint implements and exports the following functions.decode_qpdecode_qp(string)Returns the plain-text version of string, which is quoted-printable-encoded.encode_qpencode_qp(string)Returns a quoted-printable-encoded version of string. The returned version of string will not be CRLF-terminated.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - NDBM_File
- InhaltsvorschauProvides Perl programs with tied access to NDBM database files. See Perl's built-in
tiefunction and the DB_File module.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::Cmd
- InhaltsvorschauThe network command class, which is required by all of the modules under the libnet umbrella: Net::FTP, Net::SMTP, Net::POP3, etc. In addition, Net::Cmd can be inherited by a subclass of IO::Handle. Unless you are writing a new module that will become a part of libnet, Net::Cmd probably doesn't have any servicable parts that you'd be interested in, since these parts are already implemented in the underlying modules. This module is part of the core Perl distribution starting with Perl 5.8.Net::Cmd implements the following methods, which provide an interface to the Net::Cmd object.codecode()Returns the three-digit code from the last command. If the last command is still pending,
codereturns0.dataenddataend()Stops sending data to the remote server and ensures that a final CRLF has been sent.datasenddatasend(data)Sends data to the remote server, converting LF to CRLF. data can be an array or reference to an array.debugdebug(level)Sets the debug level for the object. If you do not specify a value, then no debugging information will be provided. If you specifyundefas the value, then the debug level will be determined by the debug level of the class.messagemessage()Returns a text message from the last command.okok()Returns nonzero if the last code value was greater than 0 and less than 400.statusstatus()Returns the current status code and, if pending, returnsCMD_PENDING.Net::Cmd implements the following class methods, which you should probably never touch at a user level.commandcommand(command, [, args, ...])Sends a command to the remote server. Returnsundefon failure.debug_printdebug_print(dir, text)Outputs debugging information. dirrepresents data sent to the server, and text is the text that is sent.debug_textdebug_text(text)Prints debugging information.getlinegetline()Retrieves one line, delimited by CRLF, from the remote server. Returnsundefon failure.parse_responseparse_response(text)Returns an array of two values: the three-digit status code and a flag that is true when this is part of a multiline response. Called byEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::Config
- InhaltsvorschauHolds configuration data for the modules in the libnet distribution. Net::Config builds this configuration interactively at install time of libnet, and the Net::Config file is further queried when you use modules such as Net::FTP. This module is part of the core Perl distribution starting with Perl 5.8.Net::Config stores the following values (which can be
undef):nntp_hosts,snpp_hosts,pop3_hosts,smtp_hosts,ph_hosts,daytime_hosts, andtime_hosts. Each is a reference to an array of hostnames (in order of preference), which should be used for the given protocol. You can override any of the Net::Config values when you use any of the modules that live under the libnet umbrella. In addition, you can maintain your own .libnetrc to hold your custom values all the time. A sample .libnetrc follows:$ cat .libnetrc # .libnetrc { nntp_hosts => [ "news.my.host", "news.their.host" ] } _ _END_ _In addition to the options listed previously, the following options can be specified:-
inet_domain - Your Internet domain name.
-
ftp_firewall - If you have an FTP proxy firewall (not an HTTP or SOCKS firewall), then this value should be set to the firewall hostname. If your firewall does not listen on port 21, then this value should be set to
hostname:port(e.g.,hostname:99). -
ftp_firewall_type - An integer from 1 to 7 signifying the sequence of commands that Net::FTP will use to traverse a firewall, as follows:
-
* - There is no firewall (default).
-
1 USER user@remote.host PASS password
-
2 USER firewall_username PASS firewall_password USER user@remote.host PASS pass
-
3 USER firewall_username PASS firewall_password SITE remote.site USER user PASS pass
-
4 USER firewall_username PASS firewall_password OPEN remote.site USER user PASS pass
-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Net::Domain
- InhaltsvorschauAttempts to evaluate the current host's Internet name and domain using several methods. This module is part of the core Perl distribution starting with Perl 5.8.For example, each of the following Net::Domain functions will return
undefif the FQDN cannot be determined.hostdomainhostdomain()Returns the remainder of the FQDN after the hostname has been removed.hostfqdnhostfqdn()Identifies and returns the FQDN of the current host.hostnamehostname()Returns the smallest part of the FQDN that can be used to identify the host.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::FTP
- InhaltsvorschauImplements a simple FTP client in Perl (see Chapter 16). This module is part of the core Perl distribution starting with Perl 5.8.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Net::hostent
- InhaltsvorschauOverrides the core
gethostbynameandgethostbyaddrfunctions with object-oriented versions that return Net::hostent objects. The objects have methods that return the fields of the same name from the hostent structure in netdb.h:FieldDescriptionaddrAddress of host, for backward compatibilityaddr_listList of addresses returned from name serveraddrtypeHost address typealiasesList of aliaseslengthLength of addressnameName of hostYou can access the structure fields with the methods or by importing the fields into your namespace with the :FIELDS import tag and accessing them by prependingh_to the field name:$host_obj->name( ) $h_name
Net::hostent exports the following.gethostgethost (host)Frontend forgethostbyaddrandgethostbyname. If hostis numeric, callsgethostbyaddr; otherwise, callsgethostbyname.gethostbyaddrgethostbyaddr (addr, addrtype)Returns information about the host with address addr of type addrtype.gethostbynamegethostbyname (hostnameEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::netent
- InhaltsvorschauReturns information for a network. Overrides the core
getnetbynameandgetnetbyaddrfunctions with object-oriented versions that return Net::netent objects. The objects have methods that return the fields of the same name from the netent structure in netdb.h:FieldDescriptionaddrtypeNet address typealiasesArray of aliasesnameName of netnetNetwork numberYou can access the structure fields with the methods or by importing the fields into your namespace with the :FIELDS import tag and accessing them by prependingn_to the field name:$net_obj->name( ) $n_name
Net::netent exports the following.getnetgetnet (net)Frontend forgetnetbyaddrandgetnetbyname. If net is numeric, callsgetnetbyaddr; otherwise, callsgetnetbyname.getnetbyaddrgetnetbyaddr (addr, addrtype)Returns information about the net with address addr of type addrtype.getnetbynamegetnetbyname (netname)Returns information about the net with name netname.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::Netrc
- InhaltsvorschauImplements a simple interface to .netrc in Perl (see Chapter 16). This module is part of the core Perl distribution starting with Perl 5.8.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Net::NNTP
- InhaltsvorschauImplements a simple NNTP client in Perl (see Chapter 17). This module is part of the core Perl distribution starting with Perl 5.8.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Net::Ping
- InhaltsvorschauProvides methods to create ping objects and test the reachability of remote hosts on the network. After the object has been created, a variable number of hosts can be pinged multiple times before closing the connection. The methods are the following.new$p = Net::Ping->new([proto[, def_timeout[, bytes]]])Creates a new ping object. All arguments are optional. Takes the following arguments:
- proto
- The protocol to use when doing a ping. Default is
udp. The possible protocols are:-
icmp - Sends an
icmpechomessage to the remote host. If the echoed message is received back correctly from the remote host, that host is considered reachable. Requires the program to be run as root or setuid to root. -
tcp - Attempts to establish connection to remote host's
echoport. If successful, remote host is considered reachable. No data is actually echoed. No special privileges are required, but overhead is higher than for the others. -
udp - Sends a udp packet to remote host's
echoport. If the echoed packet is received back from the remote host and contains the same data that was sent, the remote host is considered reachable. Requires no special privileges.
-
- def_timeout
- Default timeout in seconds to be used if timeout not passed to the
pingmethod. Must be greater than zero; defaults to five seconds. - bytes
- Number of bytes included in the ping packet sent to the remote host. Ignored if protocol is tcp. Default is
1if protocol is udp, otherwise0. These are also the minimum number of bytes; the maximum is 1,024.
close$p->close( )Closes network connection for this ping object. The connection can also be closed byundef $pand is automatically closed if the ping object goes out of scope.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::POP3
- InhaltsvorschauImplements a simple POP3 client in Perl (see Chapter 17). This module is part of the core Perl distribution starting with Perl 5.8.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Net::protoent
- InhaltsvorschauReturns information for an Internet protocol. Overrides the core
getprotoent,getprotobyname, andgetprotobynumberfunctions with object-oriented versions that return Net::protoent objects. The functions take a default second argument oftcp. The objects have methods that return the fields of the same name from the protoent structure in netdb.h:FieldDescriptionaliasesList of aliasesnameName of hostprotoProtocolYou can access the structure fields with the methods or by importing the fields into your namespace with the :FIELDS import tag and accessing them by prependingp_to the field name:$proto_obj->name( ) $p_name
getprotogetproto (protocol)Frontend forgetprotobynumberandgetprotobyname. If protocol is numeric, callsgetprotobynumber; otherwise, callsgetprotobyname.getprotobynamegetprotobyname (addr, addrtype)Returns information about the host with address addr of type addrtype.getprotobynumbergetprotobynumber (hostname)Returns information about the host with name hostname.getprotoentgetprotoent (protocol)Frontend forgetprotobynumberandgetprotobyname. If protocol is numeric, callsgetprotobynumber; otherwise, callsgetprotobyname.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::servent
- InhaltsvorschauReturns information for an Internet service. Overrides the core
getservent,getservbyname, andgetservbyportfunctions, replacing them with versions that return Net::servent objects. The functions take a default second argument oftcp. The objects have methods that return the fields of the same name from the servent structure in netdb.h:FieldDescriptionaliasesList of aliasesnameName of serviceportPortprotoProtocol to useYou can access the structure fields with the methods or by importing the fields into your namespace with the :FIELDS import tag and accessing them by prependings_to the field name:$serv_obj->name( ) $s_name
getservgetserv(service)Frontend forgetservbyportandgetservbyname. If service is numeric, callsgetservbyport; otherwise, callsgetservbyname.getservbynamegetservbyname(name)Returns information for the Internet service with protocol name name.getservbyportgetservbyport(port)Returns information for the Internet service with port number port.getserventgetserventReturns entries from the database of Internet services.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::SMTP
- InhaltsvorschauImplements a simple SMTP client in Perl (see Chapter 16). This module is part of the core Perl distribution starting with Perl 5.8.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Net::Time
- InhaltsvorschauProvides subroutines that obtain the time on a remote machine. This module is part of the core Perl distribution starting with Perl 5.8.Net::Time implements the following functions.inet_daytimeinet_daytime( [host [, protocol [, timeout]]])Obtains the time on host , or a default host if host is not given.
inet_daytimeuses protocol, which can be eitherudportcp. Returns an ASCII string orundefon failure.inet_timeinet_time( [host [, protocol [, timeout]]])Obtains the time on host, or a default host if host is not given.inet_timeuses protocol, which can be eitherudportcp. Returns some units oftimeon success orundefon failure.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - O
- InhaltsvorschauGeneric interface to the Perl compiler backends. See also the B module.
perl -MO=backend[,options] perlscript
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ODBM_File
- InhaltsvorschauProvides Perl programs with tied access to ODBM database files. See Perl's built-in
tiefunction and the DB_File module.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Opcode
- InhaltsvorschauPermits defining an operator mask (opmask) so that any code containing a masked opcode will not compile or execute when Perl next compiles any code. Not usually used directly; for examples of Opcode's use, see the
opspragma and the Safe module.Valid opcodes are listed in the arrayop_namein the file opcode.h. Many Opcode functions and methods take lists of operators, which are composed of elements. Each element can be a:- name (opname) or negated name
- Name of operator, usually lowercase. Prefixing the name with an exclamation mark (
!) removes it from the accumulated set of operations. - set (opset)
- Operator set. Binary string holding a set of zero or more operators.
- tag name (optag) or negated tag
- Operator tag name; refers to groups (or sets) of operators. Begins with a colon (
:). Negated by prefixing with an exclamation mark (!). Several optags are predefined, including the following. See the Opcode module's manpage for the opcodes included in each tag.:base_core :base_io :base_loop :base_math :base_mem :base_orig :browse :dangerous :default :filesys_open :filesys_read :filesys_write :others :ownprocess :still_to_be_decided :subprocess :sys_db
All the following functions can be exported.define_optagdefine_optag (optag, opset)Defines optag as symbolic name for the set opset.empty_opsetempty_opsetReturns an empty opset.full_opsetfull_opsetReturns an opset that includes all operators.invert_opsetinvert_opset (opset)Returns an opset that is the inverse of opset.opcodesopcodesIn scalar context, returns the number of opcodes in this version of Perl.opdescopdesc (op, ...)Takes list of operator names and returns the corresponding list descriptions.opdumpopdump ([pat])Writes two-column list of operator names and descriptions to STDOUT. If pat is specified, only lines matching the (case-insensitive) pattern are output.opmaskopmaskReturns an opset corresponding to the current opmask.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - ops
- InhaltsvorschauPragma that disables unsafe opcodes during compilation. Can also be used to specify opcodes to be disabled. Generally used with the -M option on the command line:
perl -Mops=:default ... # Allow only reasonably safe operations perl -M-ops=system ... # Disable system opcode
See the Opcode module for more information.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - overload
- InhaltsvorschauLets you substitute class methods or your own subroutines for standard Perl operators. For example, the code:
package Number; use overload "+" => \add, "*=" => "muas";declares functionaddfor addition and methodmuasin the Number class (or one of its base classes) for the assignment form*=of multiplication.Arguments touse overloadare key/value pairs, in which the key is the operation being overloaded, and the value is the function or method that is to be substituted. Legal values are values permitted inside a&{ ... }call, so a subroutine name, a subroutine reference, or an anonymous subroutine are all legal. Legal keys (overloadable operations) are:TypeOperationsArithmetic+ - * / % ** << >> x.+= -= *= /= %= **= <<= >>= x= .=Comparison< <= > >= == != <=>lt le gt ge eq ne cmpBit and unary% ^ | neg ! ~Increment, decrement++ -Transcendentalatan2 cos sin exp abs log sqrtBoolean, string, numeric conversionbool""0+Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - PerlIO
- InhaltsvorschauAn on-demand loader for PerlIO layers and the root of the PerlIO namespace. PerlIO allows you to expand the functionality of
open(). For example:use PerlIO 'special';
The code in PerlIO.pm then attempts to find'special':require PerlIO::special;
PerlIO currently defines the following layers:-
unix - Low-level layer that calls
read,write,lseek, etc. -
stdio - Calls
fread,fwrite,fseek,ftell, etc.stdiowill use your operating system's I/O via the C library. That is, you cannot place any layers beneathstdio. -
perlio - A reimplementation of a
stdio-like buffering written as a PerlIO layer. As such, it will call whatever layer is below it for its operations. -
crlf - Does CRLF translation depending on distinguishing text, and binary files a la MS-DOS.
-
utf8 - Declares that the stream accepts Perl's internal encoding of characters (which is really
UTF-8on ASCII machines andUTF-EBCDICon EBCDIC machines). This allows any character Perl can represent to be read from or written to the stream. TheUTF-X encoding is chosen to render simple text parts (i.e., nonaccented letters, digits, and common punctuation) human-readable in the encoded file. -
raw - A pseudo-layer that performs two functions. It forces the filehandle to be considered binary at that point in the layer stack, and it prevents the I/O system from searching before it in the layer specification. For example:
open($fh,":raw:perlio",...);
rawforces the use of theperliolayer even if the platform default or theuse opendefault is something else (such as:encoding(iso-8859-7)).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- PerlIO::Scalar
- InhaltsvorschauSupports in-memory I/O. It exists so it can use XSLoader to load C code that supports treating a scalar as an "in-memory" file. PerlIO::Scalar allows all normal file operations to be performed on the handle. Returns
undef.For example:#!/usr/local/bin/perl -w use PerlIO::Scalar; open($fh, "<...", \$some_scalar);
This module is part of the core Perl distribution starting with Perl 5.8.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - PerlIO::Via
- InhaltsvorschauA helper class for PerlIO layers implemented in Perl. PerlIO::Via ships with the Perl 5.8 source kit.For example, you can use PerlIO::Via to call
MIME::Base64::encode_base64()viaopen():#!/usr/local/bin/perl -w; use MIME::Base64; open(my $fh, ">Via(MIME::Base64)", "encode_base64");
PerlIO::Via implements the following methods.CLOSECLOSE(fh)Returns0on success and-1on error.EOFEOF(fh)Returns end-of-file state. The default behavior is to return a value ofFILL()orREAD().ERRORERROR(fh)Returns error state.FILENOFILENO(fh)Returns a numeric value that represents the Unix-like file descriptor, or-1if no file descriptor exists.FILLFILL(fh)Returns a string that will be placed in the buffer.FLUSHFLUSH(fh)Flushes any buffered write data. Returns0on success and-1on error.POPPEDPOPPED([fh])Removes a layer from PerlIO::Via.PUSHED$class->PUSHED([mode [,fh]])Returns an object or the class, or-1on failure.PUSHEDtakes optional arguments for file open mode—r,w,w+, etc.—and takes a mandatory filehandle for the PerlIO layer itself.READREAD(buffer, len, fh)Returns the number of octets in buffer, which must be less than or equal to len.SEEKSEEK(posn, where, fh)Returns0on success and-1on error.TELLTELL(fh)Returns the file position, without an available default.UNREADUNREAD(buffer, fh)Returns the number of octets from bufferthat have been successfully saved.WRITEWRITE(buffer, fh)Returns the number of octets in buffer that have been written.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Pod::Functions
- InhaltsvorschauUsed internally by Pod::Html for converting from pod to HTML.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Pod::Html
- InhaltsvorschauConverts files from pod to HTML format. Not generally used directly, but via the pod2html script (see Chapter 4), which is included in the standard distribution.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Pod::ParseLink
- InhaltsvorschauParses an
L<>formatting code in POD text. It implements a single function,parselink(), which takes the text of anL<>formatting code and parses it.parselink()returns the anchor text for the link, the anchor text possibly inferred from the name and section, the name or URL, and the section and the type of link. The link type will beurl,pod, orman. For example:#!/usr/local/bin/perl -w use Pod::ParseLink; my $link = 'L<http://www.some-site.com/indexes/index.html>'; my ($text, $inferred, $name, $section, $type) = parselink ($link);
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Pod::Text
- InhaltsvorschauConverts files from pod format to formatted ASCII text. Not generally used directly, but via the pod2text script (see Chapter 4). Termcap is optionally supported for boldface and underlining and can be enabled with:
$Pod::Text::termcap=1
Otherwise, backspaces are used to simulate bold and underlined text. Exports one function.pod2textpod2text (filename[, filehandle])Converts from pod to text format. Takes the following arguments:- filename
- File to convert, or
<&STDINto read from STDIN. - filehandle
- Optional. Filehandle glob to which output should be sent (
*STDOUTto write to STDOUT).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - POSIX
- InhaltsvorschauProvides access to standard POSIX 1003.1 identifiers: functions, classes, and constants. Can be
used to import one or multiple symbols:use POSIX; # Import all symbols use POSIX qw(setsid); # Import one symbol use POSIX qw(:errno_h :fcntl_h); # Import sets of symbols
Functions listed as C-specific are not implemented.FunctionDescription_exitIdentical to C function_exit(2)abortIdentical to C functionabort(3)absIdentical to Perl'sabsfunctionaccessDetermines accessibility of a file; returnsundefon failureacosIdentical to C functionacos(3)alarmIdentical to Perl'salarmfunctionasctimeIdentical to C functionasctime(3)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - re
- InhaltsvorschauPragma that lets you alter the behavior of regular expressions. Permits the following alterations:
-
use re 'debug' - Causes Perl to produce debugging messages when compiling and at runtime when using regular expressions. See the re manpage and the section on "Debugging regular expressions" in the perldebug manpage for details.
-
use re 'eval' - Permits a regular expression to contain
(?{...})zero-width assertion even if the regular expression contains variable interpolation, which normally isn't permitted for security reasons. The pragma is ignored if the regular expression comes from tainted data. -
use re 'taint' - When a tainted string is the target of a regular expression, causes the regular expression memories (or the values returned by the
m//operator in list context) to be tainted.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Safe
- InhaltsvorschauCreates compartments for evaluating untrusted Perl code. Each compartment has an associated operator mask for excluding particular Perl operators from the compartment. (See the Opcode module for more information on operators and operator masks.) The default mask is applied during compilation to prevent all operations that give access to the system. Safe provides the following methods.new$cpt = new Safe [(namespace, mask)]Constructor. Creates a new compartment. Takes the following arguments:
- namespace
- Optional. Root namespace to use for the compartment. Default is
Safe::Root0, which autoincrements for each new compartment. - mask
- Optional. Operator mask to use; defaults to a restrictive set.
mask$cpt->mask ([mask])Sets operator mask for the compartment if mask is specified; otherwise, it gets the current mask.rdo$cpt->rdo (filename)Evaluates the contents of file filenameinside the compartment.reval$cpt->reval (string)Evaluates string as Perl code inside the compartment.root$cpt->root ([namespace])If namespace is specified, sets the root namespace for the compartment; otherwise, gets the current namespace.share$cpt->share (varname[, ...])Shares the variable(s) in the argument list with the compartment.trap$cpt->trap (op[, ...])For each operator specified in the argument list, sets the corresponding bit in the compartment's operator mask.untrap$cpt->untrap (op[, ...])For each operator specified in the argument list, resets the corresponding bit in the compartment's operator mask.varglob$cpt->varglob (varname)Returns a glob for the symbol table entry of varname in the compartment's package.The following subroutines are available for export by Safe. The operator names can be found in the arrayop_namein the file opcode.h in the Perl distribution.emptymaskemptymaskReturns a mask with all operators unmasked.fullmaskfullmaskReturns a mask with all operators masked.mask_to_opsmask_to_ops (Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Scalar::Util
- InhaltsvorschauImplements a few useful scalar-related subroutines. Like List::Util, Scalar::Util is something useful that doesn't necessarily fit well as a keyword in the Perl core. By default, Scalar::Util does not export any subroutines. As of Perl 5.8, Scalar::Util is shipped with the source kit.Scalar::Util implements the following methods.blessedblessed exprEvaluates whether expr is a blessed reference. If successful,
blessedreturns the name of the package. Otherwise,blessedreturnsundef.use Scalar::Util qw(blessed); use CGI; my $cgi = CGI->new(); my $not_cgi = "IamNotCGI"; my $is_blessed = blessed($cgi); if(defined($is_blessed) { print "$cgi\n;" } # Prints CGI my $is_blessed2 = blessed($not_cgi); if(defined($is_blessed2) { print "$not_cgi\n"; } # undefdualvardualvar number, stringReturns a string that has the value numberin a numeric context and a value string in a string context. For example:my $context = dualvar(10, "Nathan"); my $add_nums = $context + 1; # '11' my $str_add = $context . "Patwardhan"; # Nathan Patwardhan
isweakisweak exprReturns true if expr is a scalar, which is a weak reference:my $weak_ref = \$boo_hoo; my $i_am_weak = isweak($weak_ref); # false weaken($weak_ref); $i_am_weak = isweak($weak_ref); # true
openhandleopenhandle fhReturnsfhif fh is an open filehandle. fh may also be a tied filehandle. Returnsundefon failure.my $fh = openhandle(*STDIN); $fh = openhandle("sumfin"); # undef, since sumfin isn't # openreadonlyreadonly scalarReturns true if scalar is read-only.reftypereftype exprReturns the reference type of expr if expr is a reference. Otherwise, returnsundef.my $r_type = reftype "ORA"; # undef, not a reference my $r_type = reftype []; # ARRAY
taintedtainted exprReturns true if the result of expr is tainted:my $is_tainted = tainted($ENV{PATH}); # Returns true if -T is enabledweakenweaken refEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - SDBM_File
- InhaltsvorschauProvides Perl programs with tied access to SDBM database files. See Perl's built-in
tiefunction and the DB_File module.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Search::Dict
- InhaltsvorschauSearches for a key in an ordered text file and sets the file position. Exports one function.looklook *fh, key, dict, foldPerforms string search and sets the position in filehandle fh to the first line with a key equal to or greater than key. Returns the new file position, or
-1in case of error. Takes the following arguments:- fh
- Filehandle of the dictionary file
- key
- Key to search for
- dict
- If true, searches in dictionary order, considering only word characters and whitespace
- fold
- If true, ignores case
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - SelectSaver
- InhaltsvorschauProvides a way to save and restore filehandles so you can temporarily use a different filehandle.new$saver = new SelectSaver[(fh)]Constructor. Creates a new SelectSaver object,
$saver, which saves the current filehandle. The optional parameter fh is the filehandle that will temporarily replace the current filehandle. If fh is present, the current filehandle is saved in$saver, and the new one becomes the current filehandle. With no parameter, the current filehandle is saved in the object$saver, and it remains current.You can use the newly selected filehandle within the current block. When you exit the block, the previous filehandle is again made the current one, and the SelectSaver object in which it was stored is destroyed.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - SelfLoader
- InhaltsvorschauUsed when you want to include functions in your program but want to load them only if necessary. Functions that will be self-loaded are placed after the line:
_ _DATA_ _
in your program. When the code is compiled, compilation stops at the_ _DATA_ _token. The SelfLoader exports theAUTOLOADsubroutine to the package; this subroutine loads the subroutines after_ _DATA_ _when they arerequired.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Shell
- InhaltsvorschauAllows you to invoke Unix shell utilities as if they were Perl subroutines. Arguments (including switches) are passed to the utilities as strings:
use Shell qw(date cp ps); # List shell commands you want to use $date = date( ); # Put the output of the date(1) command into $date cp("-p" "/etc/passwd", "/tmp/passwd"); # Copy password file to a tmp file print ps("-ww"); # Print the results of a "ps -ww" commandEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - sigtrap
- InhaltsvorschauPragma to enable simple signal handling. Provides two signal handlers that can be installed, or you can install your own handler; also provides options to specify which signals to trap. Ignores requests to trap signals not used in your system's architecture.
use sigtrap; # Initialize default signal handlers use sigtrap qw(die normal-signals); use sigtrap 'handler' => \handlername, 'normal-signals'; use sigtrap qw(handler handlername normal-signals stack-trace error-signals);Used to specify which handler will be installed for signals installed after the handler:-
die - Installs handler that
dies with a message indicating the signal that was trapped. -
handlerhandlername - Installs your handler handlername.
-
stack-trace - Default signal handler. Outputs stack trace to STDERR and tries to dump core.
You can specify your own list of options:use sigtrap qw(BUS SEGV PIPE ABRT);
or use one of the following built-in option lists:-
error-signals - Signals that indicate a serious problem: ABRT, BUS, EMT, FPE, ILL, QUIT, SEGV, SYS, and TRAP.
-
normal-signals - Signals a program is most likely to encounter: HUP, INT, PIPE, and TERM.
-
old-interface-signals - Default. Signals trapped by default in older versions of
sigtrap: ABRT, BUS, EMT, FPE, ILL, PIPE, QUIT, SEGV, SYS, TERM, and TRAP.
-
any - Installs handlers only for subsequently listed signals that aren't already taken care of.
- number
- Requires that the version of
sigtrapbeing used must be at least number. -
signal - Installs a handler for any argument that looks like a signal name.
-
untrapped - Installs handlers only for subsequently listed signals not already trapped or ignored.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Socket
- InhaltsvorschauTranslation of the C socket.h file that uses h2xs and your C compiler. See Chapter 13 for details.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- sort
- InhaltsvorschauThe
sortpragma allows you to controlsort()behavior. In Perl 5.6 and earlier, the defaultsort()behavior was written withquicksort. Perl 5.8, with which sort.pm is shipped in the source kit, implementsmergesort.mergesortguarantees the worst-case behavior ofO(N log N), wherequicksortguaranteesO(N ** 2).Perl 5.8 and later shuffle large arrays before sorting. Note that sort.pm is global and not lexical in scope.For example:#!/usr/local/bin/perl -w use sort '_quicksort'; # Or _qsort, if you'd like sort(@something);
mergesortis better thanquicksortfor several reasons. First,mergesortis more stable and does fewer comparisons thanquicksort, so it's better for more complicated sorting routines. In addition,mergesorttakes preexisting order into account.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Storable
- InhaltsvorschauStorable.pm allows you to keep peristent state on your Perl data structures, which include objects of type
SCALAR,ARRAY,HASH, andREF. In other words, Storable lets you deal with any Perl types that can be conveniently stored on disk and retrieved at a later time. At the heart of Storable isstore, which takes a reference to the object that will be stored and the filename where the information should be written. And, while you're statefully keeping your Perl data on a filesystem,retrievewill open the file where the data is kept so you can work with it. As of Perl 5.8, Storable is shipped with the source kit.For the cost of a slight header overhead, you can store to an already opened file descriptor using thestore_fdroutine and retrieve from a file viafd_retrieve. These names aren't imported by default, so you will have to do this explicitly if you need these routines. The file descriptor you supply must be opened for read if you're going to retrieve and for write if you wish to store. For example:#!/usr/local/bin/perl -w use Storable; my $state_file = '/tmp/emp.cache'; my %empdata = (EmployeeNumber => 1, Person => 'Nathan Patwardhan'); store(\%empdata, $state_file); my $h_ref = retrieve($state_file);
Storable implements the following methods.lock_retrievelock_retrieve()Gets an exclusive lock at the file before writing.lock_storelock_store()Same asstore, except that it gets an exclusive lock at the file before writing.nlock_storenlock_store()Same asnstore(), except that it gets an exclusive lock at the file before writing.nstore_fdnstore_fd()Allows you to store data in network order so it can be shared across platforms. It also stores stringified double values to ensure portability.nstore_fdworks the same asstore_fdand behaves the same if errors are encountered.retrieveretrieve(file)Takes file as an option and recreates the objects in memory for you; a reference to the object is returned.retrievereturnsundefif an I/O error is encountered.storestore(type, file)Takes type (Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - strict
- InhaltsvorschauPragma for doing strict error checking within the current block. Can be turned off by prefixing with
no:use strict 'vars'; ... no strict 'vars';
Provides three kinds of restriction:-
strict 'refs' - Generates runtime error if you use any symbolic references.
-
strict 'subs' - Generates compile-time error if you use a bareword identifier that's not a predeclared subroutine.
-
strict 'vars' - Generates compile-time error if you access a variable that wasn't declared via
my, isn't fully qualified, or wasn't imported.
use strictby itself (with no import list) is the most restrictive, causing all possible restrictions to be imposed.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- subs
- InhaltsvorschauPragma that predeclares subroutines whose names are given in a list:
use subs qw(sub[, ...]); sub $arg[, ...];
This lets you use the subroutines without parentheses even before they're defined and lets you override built-in functions.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Switch
- InhaltsvorschauSwitch.pm implements a
switchstatement for Perl, which works something like the switch statement you'd find in C and other languages. Switch.pm is intended to supplement the standard Perl syntax with two control statements:switchandcase.switchtakes a single scalar argument of any type, specified in parentheses, that is then stored in a localized control variable. It is followed by any number of Perl statements (in a block) that are checked to meet various conditions, or cases, of the switch.casetakes a single scalar argument, variable, or regular expression as an argument. Ifcasefinds a match, it will take the action that's specified between the braces on the right. Switch.pm is shipped with the Perl 5.8 source kit.For example:#!/usr/local/bin/perl -w use Switch; switch($some_value) { case 1 { print "number 1" } case "a" { print "string a" } case [1..10,42] { print "number in list" } case (@array) { print "number in list" } case /\w+/ { print "pattern" } case qr/\w+/ { print "pattern" } case (%hash) { print "entry in hash" } case (\%hash) { print "entry in hash" } case (\&sub) { print "arg to subroutine" } else { print "Get off my case." } }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Symbol
- InhaltsvorschauProvides functions for creating anonymous globs and qualifying variable names. Exports the following.gensymgensymCreates an anonymous glob and returns a reference to it that can be used as a filehandle or directory handle.qualifyqualify (symname[, pkg])Turns unqualified symbol names into qualified variable names (e.g., turns
myvarintoMyPackage::myvar).qualify_to_refqualify_to_ref (symname[, pkg])Likequalify, but returns a glob reference that can be used even ifuse strict 'refs'is in effect.ungensymungensymFor backward compatibility only; does nothing.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Sys::Hostname
- InhaltsvorschauProvides one function,
hostname, which attempts to get the system hostname by doing checks appropriate to the operating system. Removes nulls, returns, and newlines from the result, which it then caches.croaks on failure.use Sys::Hostname; $host = hostname( );
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Sys::Syslog
- InhaltsvorschauInterfaces to Unix
syslog(3)program. Requires the file syslog.ph, which must be created with h2ph by your system administrator. Provides the following four functions.closelogcloselogCloses the log file.openlogopenlog ident, logopt, facilityOpens the log file. Takes the following arguments:- ident
- Prepended to every message
- logopt
- Logging options, containing one or more of:
-
cons - Writes messages to system console if they can't be sent to syslogd
-
ndelay - Opens the connection immediately
-
nowait - Doesn't wait for child processes before logging messages to the console
-
pid - Logs process ID
-
- facility
- Specifies the part of the system making the log entry
setlogmasksetlogmask mask_prioritySets log mask to mask_priority and returns the old mask.syslogsyslog priority, mask, format, argsIf priority and mask permit, logs message formed as if bysprintf(format, args), with the addition that%mis replaced with the current error message from$!.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Term::Cap
- InhaltsvorschauProvides low-level functions to extract and use capabilities from a terminal capability (termcap) database. For general information about the use of this database, see the termcap(5) manpage. Provides the following functions.Tgetent$terminal = Tgetent Term::Cap { TERM => termtype, OSPEED=>ospeed }Acts as the constructor for Term::Cap. Extracts the termcap entry for terminal type termtype and returns a reference to a terminal object. The termcap entry itself is
$terminal->{TERMCAP}. CallsCarp::croakon failure. Takes the following arguments:-
TERM =>termtype - Terminal type. Defaults to the value of the environment variable TERM if termtype is false or undefined.
-
OSPEED =>ospeed - The terminal output bit rate, specified as either a POSIX termios/SYSV termio speed or an old BSD-style speed. You can use the POSIX module to get your terminal's output speed (in ospeed here).
Tgoto$terminal->Tgoto('cm', col, row[, fh])Produces control string to move the cursor relative to the screen. Doesn't cache output strings, but does%expansion as needed on control string. Takes the following arguments:-
'cm' - Required first argument ("cursor move")
- col, row
- Column and row to move cursor to
- fh
- Filehandle that will receive the control string
Tpad$terminal->Tpad(string, count, fh)Specifies padding required to create delay needed by terminal. Takes the following arguments:- string
- The string to pad with
- count
- The number of pad characters
- fh
- The filehandle to pad
Tputs$terminal->Tputs('cap', count[, fh])Produces control string for capabilities other than cursor movement. Does not do%expansion, but does cache output strings ifEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Term::Complete
- InhaltsvorschauProvides word completion on list of words in a specified array. Exports one function.CompleteComplete ('prompt_string', array)Sends string to the currently selected filehandle, reads the user's response, and returns the response. Takes the following arguments:
- prompt_string
- The prompt for user input
- array
- The array of words against which the user's input is matched
If any of the following characters are included in the user's response to prompt_string, they are treated as special characters:- Tab
- Does word completion, matching what the user has typed so far against the list of strings in completion_list. On a unique match, outputs the rest of the matched string and waits for the user to press Return. Otherwise, leaves partial input unchanged and sounds the bell.
- Ctrl-D
- Prints all possible completions of the user's partial input, or the entire completion list if the partial input string is null, and reissues the prompt string and the partial input. Redefine by setting the variable
$Term::Complete::complete. - Ctrl-U
- Erases any partial input. Redefine by setting the variable
$Term::Complete::kill. - Del, BS
- Delete and backspace characters; both erase one character from the partial input string. Redefine by setting the variables
$Term::Complete::erase1and$Term::Complete::erase2.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Term::ReadLine
- InhaltsvorschauFrontend to other ReadLine packages. Currently interfaces to Term-ReadLine, which is available on CPAN. Defines the variables
$INand$OUT, which return the filehandles for input and output, respectively, orundefif Readline input and output cannot be used for Perl. Provides the following methods.new$term = new Term::ReadLine 'name'Constructor. Returns the handle for subsequent calls to other ReadLine methods. Argument name is the name of the application. Optionally can be followed by two arguments that are globs specifying input and output filehandles.addhistory$term->addhistory(line)Adds line to the input history.Features$term->FeaturesReturns a reference to a hash whose keys are features present in the current implementation and whose values are assigned to each feature. Several optional features are used in the minimal interface:- appname
- Should be present if the first argument to
newis recognized - minline
- Should be present if
MinLinemethod is not a dummy - autohistory
- Should be present if lines are put into history automatically (maybe subject to MinLine)
- addhistory
- Should be present if the
addhistorymethod is not a dummy
findConsole$term->findConsoleReturns array of two strings containing the most appropriate names for input and output files, using the conventions<$inand>$out.MinLine$term->MinLine([size])With size argument, serves as a recommendation on minimal size of line to be added to history. Without an argument, does not add anything to the history. Returns the old value.ReadLine$term->ReadLineReturns the actual package that executes the commands. Some possible values areTerm::ReadLine::Gnu,Term::ReadLine::Perl, orTerm::ReadLine::Stub.readline$term->readline(prompt)Prompts for input line and gets the result. Removes trailing newline and returnsundefat end-of-file.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Test
- InhaltsvorschauProvides a framework for writing test scripts so you don't need to know the particular output that Test::Harness expects to see. Useful if you are writing modules and writing tests for those modules. Provides the following test types:
- Normal
- Tests that are expected to succeed.
- Skip
- Tests that need a platform-specific feature. They work like normal tests except that the first argument should evaluate to true if the required feature is not present.
- Todo
- Tests designed for maintaining an executable todo list; the tests aren't expected to succeed.
Test also provides an onfail hook that can trigger additional diagnostics for failures at the end of the test run. To use onfail, pass it an array reference of hash references in which each hash contains at least the package, repetition, and result fields, as well as any expected value or diagnostic string.See the Test manpage for details and examples.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Test::Builder
- InhaltsvorschauA backend for building test libraries under Perl. Note that Test::Builder is in the early stages of development and that things may become more (or less) stable, or may change completely. Test::Builder is more flexible than other testing modules such as Test::Simple and Test::More.Test::Builder implements the following methods.newnew()Returns a Test::Builder object representing the current state of the test. There's no need to create more than one Test::Builder object, since you run only one test per program.BAILOUTBAILOUT(reason)Terminates all tests and exits immediately.expected_testsexpected_tests()Gets and sets the tests that will run and prints out the correct headers.exported_toexported_to(package)Specifies the package you exported your functions to.is_eqis_eq(got_from_test, expected_from_test, name_of_test)Checks if got_from_test
eqexpected_from_test.isnt_eqisnt_eq(got_from_test, did_not_expect, name_of_test)Checks if got_from_testnedid_not_expect.isnt_numisnt_num(got_from_test, did_not_expect, name_of_test)Checks if got_from_test!=did_not_expect.is_numis_num(got_from_test, expected_from_test, name_of_test)Checks if got_from_test==expected_from_test.likelike(string,'/regex/', name_of_test)Checks if string matches the specified regular expression.no_planno_plan()Declares that there may be an infinite number of tests.okok(test, name)Reports if test by name is true.planplan()Sets up the tests for you, prints appropriate headers, and takes appropriate actions.plancan be used in lieu of any of the subsequent methods.skipskip([reason])Skips the current test, citing reason.skip_allskip_all(reason)Shamelessly skips all the tests, citing the given reason . Exits with0.my $reason = "I didn't feel like it today."; $Test->skip_all($reason);
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Test::Harness
- InhaltsvorschauUsed by MakeMaker; runs Perl test scripts and prints some statistics. You can use the Test module to write test scripts without knowing the exact output Test::Harness expects. Exports one function.runtestsruntests (tests)Runs all test scripts named in tests and checks standard output for the expected
okn strings. Prints performance statistics after all tests have been run.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Test::More
- InhaltsvorschauYet another framework for writing test scripts. Its more flexible successor is Test::Builder.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Test::Simple
- InhaltsvorschauProvides basic utilities for writing tests. It is shipped with the Perl source kit as of 5.8. For example:
my $name = 'Inigo Montoya'; my $quote = 'Prepare to die'; ok($name eq $quote, 'name is quote');
Theokfunction is given an expression to evaluate.ok()prints out'ok'or'not ok'along with the number of the test.Here's another example that tests if you can use CGI.pm:#!/usr/local/bin/perl -w use Test::Simple tests => 2; use CGI; # Test this my $cgi = CGI->new(); # Test #1—this will be ok ok(defined($cgi) and ref $cgi eq 'CGI', 'I have your CGI right here!'); my $header = $cgi->header(-type => `text/plain'); # Test #2—this will not be ok ok($header eq "Content-Type: text/mex");
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text::Abbrev
- InhaltsvorschauGiven a list of strings, creates a hash of unambiguous abbreviations. Exports one function.abbrevabbrev (\%hashref, list)Takes each string in list and constructs the hash referenced by
\%hashref. Each key is an unambiguous truncation of one of the strings, and the value is the full string (in which unambiguous means that there is only one possible expansion that matches one of the strings in the list). For example, if list contains "file" and "find", then the key/value pairs created include:fil => file file => file fin => find find => find
Both "f" and "fi" are ambiguous, since they start both words, and therefore, they don't appear as keys.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text::Balanced
- InhaltsvorschauExtracts delimited text sequences from strings. It implements various
extract_-named subroutines to capture the delimited string.In a list context, all Text::Balanced methods return a list that contains the extracted string with delimiters, the remainder of the string, and the parts of the string that were skipped. Text::Balanced is shipped with the Perl source kit as of 5.8.Text::Balanced implements the following methods.extract_bracketedextract_bracketed(text, delimiter)Extracts the initial substring of textthat is bracketed with delimiters specified by delimiter. Note that delimiter should contain one of(),{},[], or<>.extract_codeblockextract_codeblock(text, delimiter)Extracts the initial substring of textthat represents a block of Perl code. This code is specified by delimiter, which contains one of(),{},[], or<>.extract_delimitedextract_delimited(text, delimiter)Extracts the initial substring of textthat is delimited by two instances of delimiter.extract_multipleextract_multple(text ...)Extracts the initial substrings of textthat would be extracted by one or more sequential applications of the specified functions.extract_quotelikeextract_quotelike(text)Extracts the quoted portion of text.extract_taggedextract_tagged(text,"TAG1","TAG2",undef, nesting_allowed)Extracts the initial substring of textthat is bounded by an HTML or XML tag:# Extract HTML tags but don't allow <HTML> to be embedded ($extracted, $left) = extract_tagged($text,"<HTML>","</HTML>", undef,{bad=>["<HTML>"]}); extract_multiple($text, ...)gen_delimited_patgen_delimited_pat(q{pattern})Creates a string that represents the optimized pattern that matches a substring delimited byq{pattern}.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text::ParseWords
- InhaltsvorschauParses lines of text and returns an array of words. Provides three functions.old_shellwordsold_shellwords (lines)Splits an array of lines into words. Exported on request. Same as the pre-Perl 5 program shellwords.pl.quotewordsquotewords (delim, keep, lines)Accepts delimiter and list of lines and breaks the lines into a list of words at occurrences of the delimiter. Exported by default. Takes the following arguments:
- delim
- Delimiter, which can be a regular expression. Occurrences inside quotes are ignored.
- keep
- Boolean. If false, quotes and single backslashes are removed from the list of words returned, and a double backslash is returned as a single backslash. If true, quotes and backslashes are retained.
- lines
- The list of lines to be parsed.
shellwordsshellwords (lines)Works likeold_shellwords, but does not default to using$_if there is no argument. Exported by default.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text::Soundex
- InhaltsvorschauImplements the soundex algorithm, which hashes a word (in particular, a surname) into a compressed form that approximates the sound of the word when spoken by an English speaker:
use Text::Soundex; $code = soundex $string; # Get soundex code for a string @codes = soundex @list; # Get list of codes for list of strings
Returns the value of the variable$soundex_nocodeif there is no soundex code representation for a string.$soundex_nocodeis initially set toundef, but can be reset to another value. For example:$soundex_nocode = 'Z000';
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text::Tabs
- InhaltsvorschauProvides subroutines that expand tabs into spaces and compress ("unexpand") spaces into tabs. The appearance of the text is unchanged. Defines the
tabstopvariable, which defines the number of spaces equivalent to a tab. Default is8. Exports the following functions.expandexpand (text)Given an array of strings (text) containing tabs, replaces each tab character with the equivalent number of spaces.unexpandunexpand (text)Given an array of strings (text) that may or may not contain tabs, replaces each$tabstopconsecutive spaces with a tab character.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Text::Wrap
- InhaltsvorschauWraps text into a paragraph. Defines the
$columnsvariable, which specifies the output line length. Default is76. Exported on request. Provides the following function.wrapwrap (init_str, other_str, text)Breaks lines of array text at the word boundary closest to the size of a line. Prepends init_str to the first output line and other_str to subsequent lines, for indentation. Exported by default.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Thread
- InhaltsvorschauProvides Perl multithreading support. Distributed as a beta feature with Perl 5.005 and runs only on versions of Perl that were built with thread support. Has the following functions and methods.new$t = new Thread \&sub[, params]Constructor. Starts a new thread in the referenced subroutine, \sub, returning a thread object that represents the new thread. The optional parameter list is passed to the subroutine. Execution continues in both the new thread and the code.async$t = async {block};Creates a new thread to execute the block that follows it. The block is treated as an anonymous subroutine (and therefore has a semicolon after the closing bracket). Returns a thread object.
asyncisn't exported by default, so you can specifyuseThread qw(async);or fully qualify the name (Thread::async).cond_broadcastcond_broadcast varLikecond_wait, but unblocks all threads blocked in acond_waiton the locked variable, not just one thread.cond_signalcond_signal varTakes the locked variable var and unblocks one thread that'scond_waiting on that variable. If multiple threads are so blocked, the one that will be unblocked can't be determined.cond_waitcond_wait varTakes the locked variable var, unlocks it, and blocks until another thread does acond_signalorcond_broadcastfor that variable. The variable is relocked after thecond_waithas been satisfied. If multiple threads arecond_waiting, all but one will reblock waiting to reacquire the lock.evaleval {$t->join}Wraps anevalaround ajoin. Waits for a thread to exit and passes any return values from the thread, putting errors into$@.join$t->joinWaits for a thread to end. When it does, returns any exit values from the thread. Blocks until the thread has ended, unless the thread has already terminated.listThread->listReturns list of thread objects for all running and finished, but notjoined, threads.locklock var lock subLocks a variable or a subroutine. A lock on a variable is maintained until the lock goes out of scope. If the variable is already locked by another thread, theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Thread::Queue
- InhaltsvorschauProvides a thread-safe queue. Any number of threads can add elements to the end of the queue or remove elements from the head.new$q = new Thread::QueueCreates a new empty queue. Returns an object representing the queue.dequeue$q->dequeueRemoves and returns a scalar from the head of the queue. If the queue is empty,
dequeueblocks the thread until another threadenqueues a scalar on the queue.dequeue_nb$q->dequeue_nbLikedequeue, but returnsundefif the queue is empty instead of blocking.enqueue$q->enqueue listAdds the list of scalars, list, to the end of the queue.pending$q->pendingReturns the number of items remaining in the queue.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Thread::Semaphore
- InhaltsvorschauProvides a mechanism to regulate access to resources. Semaphores are more general than locks because they aren't tied to a particular scalar. They can have values other than
0or1and can be incremented or decremented by a specified number.new$sem = new Thread::Semaphore([val])Constructor. Creates a new semaphore object, with an optional initial count of val, or1if val isn't specified.downdown [number]Decrements the semaphore's count by the specified number, which defaults to1. If the resulting count would be negative, blocks until the semaphore's count has been increased to be equal to or larger than the amount you want to decrease it.upup [number]Increments the semaphore's count by the specified number, which defaults to1. If a thread is blocked waiting to decrement the count, and the increment brings the count high enough, the blocked thread is unblocked.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Thread::Signal
- InhaltsvorschauStarts a special signal handler thread to reliably run signal handlers. All signals are handed to this thread, which runs the associated
$SIG{signal}handlers for them.use Thread::Signal; $SIG{HUP} = handler;Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Thread::Specific
- InhaltsvorschauProvides thread-specific keys.key_create$k = key_create Thread::SpecificConstructor. Creates a Thread::Specific key object.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Tie::Array, Tie::StdArray
- InhaltsvorschauProvides methods for array-tying classes. (See the perltie manpage for the functions needed for tying an array to a package.) The basic Tie::Array package provides stub DELETE and EXTEND methods and implements PUSH, POP, SHIFT, UNSHIFT, SPLICE, and CLEAR in terms of basic FETCH, STORE, FETCHSIZE, and STORESIZE.Tie::StdArray inherits from Tie::Array and provides the methods needed for tied arrays implemented as blessed references to an "inner" Perl array. It causes tied arrays to behave like standard arrays, allowing for selective method overloading.See the perltie manpage for more detailed information and for examples. To write your own tied arrays, use the following required methods.TIEARRAYTIEARRAY classname, listConstructor. This method is invoked by the command
tie@array , classname. Associates an array instance with the specified class. list represents additional arguments needed to complete the association. Should return an object of a class that provides the remaining methods.CLEARCLEAR thisClears all values from the tied array associated with object this.DESTROYDESTROY thisNormal object destructor.EXTENDEXTEND this, countDoesn't need to do anything. Provides information that the array will likely grow to have count entries.FETCHFETCH this, indexRetrieves the data item in index for the tied array associated with object this.FETCHSIZEFETCHSIZE thisReturns the number of items in the tied array associated with object this.POPPOP thisRemoves the last element from the array and returns it.PUSHPUSH this, listAppends elements of list to the array.SHIFTSHIFT thisRemoves and returns the first element of the array, shifting the remaining elements down.SPLICESPLICE this, offset, length, listPerforms the equivalent of a splice on the array. Returns a list of the originalEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Tie::File
- InhaltsvorschauRepresents a regular text file as a Perl array, such that each element in the array corresponds to a record in the file. The first line of the file is element
0of the array, the second line is element1, and so on. When you add a new item to the array, this change will be noted in the file immediately. Note that the file isn't loaded into memory, so the files can be very large if needed. Tie::File is shipped with the Perl 5.8 source kit.Let's say that we have a file that contains:One Two Three Four Five Six
You can use Tie::File to report about the contents of the file as follows:#!/usr/local/bin/perl -w use Tile::File; my $infile = 'mynotes.db.txt'; my @lines; tie(@lines, 'Tie::File', $infile) die("can't open $infile: $!"); my $n_recs = @lines; print "$infile has [$n_recs]\n";Now, set the second line of the file to3:$lines[2] = 3;
and lowercase everything that's in the file:foreach my $line (@lines) { lc($line); }Add one line to the file:push(@lines, "Here's one more for you");
Now we're done:untie @lines;
Tie::File supports the following options:-
recsep - Changes
$/to what you'll use to separate the records (or lines) in your file.recsepmay not be undefined.my $file = 'datafile'; my $recsep = "\cA"; # Break records on ^A tie @lines, 'Tie::File', $file, recsep => $recsep;
Given the line:this^Athat^Athe^Aother^Athing\n
Tie::File would see the records like so:0: this 1: that 2: the 3: other 4: thing
If you do not specify arecsep, Tie::File will default to\n. Thus, the following are equivalent:$lines[5] = "Sixty6"; $lines[5] = "Sixty6\n";
-
autochomp - If specified, and if
\nis your defaultrecsep,\nwill be removed as the record separator. Default is0. -
mode - Sets if the file will be set for read, write, or read/write access. Options include
O_RDWRandO_CREAT:use Fcntl 'O_RDWR', 'O_CREAT'; # Open file RDWR, or CREAT if $file doesn't exist tie @lines, 'Tie::File', $file, mode => O_RDWR | O_CREAT;
-
memory
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Tie::Handle
- InhaltsvorschauProvides skeletal methods for handle-tying classes. Tie::Handle provides a
newmethod as backup in case a class has noTIEHANDLEmethod. (See the perltie manpage for more detailed information and for examples.) To write your own tied-handle classes, use the following methods.TIEHANDLETIEHANDLE classname, listConstructor. This method is invoked by the commandtie* glob, classname. Associates new glob instance with class classname. list represents any additional arguments needed to complete the association.DESTROYDESTROY thisFrees storage associated with the tied handle this. Permits class to take some action when an instance is destroyed. Rarely needed.GETCGETC thisGets one character from tied handle this.PRINTPRINT this, listPrints the values in list.PRINTFPRINTF this, format, listPrints the values in list using format.READREAD this, scalar, length, offsetReads length bytes from scalar starting at offset.READLINEREADLINE thisReads one line from this.WRITEWRITE this, scalar, length, offsetWrites length bytes of data from scalar starting at offset.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Tie::Hash
- InhaltsvorschauProvides skeletal methods for hash-tying classes. Tie::Hash provides a
newmethod, as well as the methodsTIEHASH,EXISTS, andCLEAR. Thenewmethod is provided as backup in case a class has noTIEHASHmethod.To write your own tied hashes, the methods listed here are required. See the perltie manpage for more detailed information and for examples.TIEHASHTIEHASH ClassName, listConstructor. Associates a new hash instance with class ClassName. listis a list of additional arguments needed to complete the association.tie %hash, ClassName, list
CLEARCLEAR thisClears all values from tied hash this.DELETEDELETE this, keyDeletes key from tied hash this.EXISTSEXISTS this, keyVerifies that key exists for tied hash this.FETCHFETCH this, keyRetrieves value associated with key for tied hash this.FIRSTKEYFIRSTKEY thisReturns key/value pair for the first key in tied hash this.NEXTKEYNEXTKEY this, lastkeyReturns next key/value pair after lastkeyfor tied hash this.STORESTORE this, key, valueStores value into tied hash this with key key.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Tie::Memoize
- InhaltsvorschauAdds data to the hash when needed. That is, Tie::Memoize allows a tied hash to autoload all its values on first access and to use the cached value on subsequent accesses. Read accesses will result in one of the Tie::Memoize functions being called. Write accesses will act as if you're operating on a normal hash. For example:
#!/usr/local/bin/perl -w require Tie::Memoize; tie %hash, 'Tie::Memoize', \&fetch, $DATA, \&exists, {%ini_value}, {%ini_existence}; sub fetch { ... } sub exists { ... }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Tie::RefHash
- InhaltsvorschauProvides the ability to use references as hash keys after you've tied a hash variable to the module:
use Tie::RefHash; tie hashvariable, 'Tie::RefHash', list; untie hashvariable;
Uses the TIEHASH interface and provides the same methods.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Tie::Scalar
- InhaltsvorschauThe basic Tie::Scalar package provides a
newmethod, as well as methodsTIESCALAR,FETCH, andSTORE. Thenewmethod is provided as backup in case a class has noTIESCALARmethod.To write your own tied hashes, the methods listed here are required. See the perltie manpage for more detailed information and for examples.TIESCALARTIESCALAR classname, listConstructor. Associates new scalar instance with class classname. listrepresents any additional arguments needed to complete the association.tie $scalar, classname, list
DESTROYDESTROY thisFrees storage associated with the tied scalar referenced by this. Permits a class to perform specific actions when an instance is destroyed. Rarely needed.FETCHFETCH thisRetrieves value of the tied scalar referenced by this.STORESTORE this, valueStores value in the tied scalar referenced by this.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Tie::SubstrHash
- InhaltsvorschauProvides a hash table-like interface to a fixed-sized array that has a constant key size and record size:
require Tie::SubstrHash; tie %myhash, "Tie::SubstrHash", key_len, value_len, table_size;
To tie a new hash to this package, specify the following:- key_len
- Length of each key
- value_len
- Length of each value
- table_size
- Size of the table given as the number of key/value pairs
An attempt to store a key/value pair in which either the key or the value is the wrong length, or in which the resulting table would be greater than table_size, results in a fatal error.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Time::gmtime
- InhaltsvorschauReplaces Perl's core
gmtimefunction with a version that returns Time::tm objects. Exports two functions.gmctime$gmc = gmctime( )Overrides the coregmtimefunction in scalar context; returns a string with the date and time:use Time::gmtime; $gmc = gmctime( ); print $gmc;
Then the output of theprintcommand looks like:Thu Apr 9 18:15:06 1998
gmtime$gm = gmtime( )Overrides the coregmtimefunction. The Time::tm object returned has methods with the same names as the structure fields they return. That is, to return the fieldmon, use themonmethod:use Time::gmtime; $gm = gmtime( ); print $gm->mon;
The field names (and therefore the method names) are the same as the names of the fields in the tm structure in the C file time.h:sec,min,hour,mday,mon,year,wday,yday, andisdst. You can access the fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and prependingtm_to the method name (for example,$tm_mon).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Time::HiRes
- InhaltsvorschauProvides "high-resolution" functionality for
alarm,sleep,gettimeofday, andintervaltimers. Ordinarily, Perl deals in seconds when you use something likesleep()oralarm(), with which only positive integers are allowed. Time::HiRes allows you to use more granular times for functions such assleep()andalarm(). For example:#!/usr/local/bin/perl -w use Time::HiRes qw(usleep); my $ms = 349_000; # That's 349,000 microseconds usleep($ms); print "I'm awake now.\n";
Time::HiRes implements a Perl interface tousleep(),ualarm(),gettimeofday(),setitimer(), andgetitimer().Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Time::Local
- InhaltsvorschauProvides routines that take the time and return the number of seconds elapsed between January 1, 1970 and the specified time. The arguments are defined like the corresponding arguments returned by Perl's
gmtimeandlocaltimefunctions and the results agree with the results of those functions. Exports two functions; both return-1if the integer limit is hit. On most machines, this applies to dates after January 1, 2038.timegm$time = timegm(sec, min, hours, mday, mon, year)Converts from Greenwich time.timelocal$time = timelocal(sec, min, hours, mday, mon, year)Converts from local time.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Time::localtime
- InhaltsvorschauReplaces Perl's core
localtimefunction with a version that returns Time::tm objects. Exports two functions.ctime$ct = ctime( )Overrides the corelocaltimefunction in scalar context; returns a string with the date and time:use Time::gmtime; $ct = ctime( ); print $ct
Then the output of theprintcommand looks like:Thu Apr 9 16:50:10 1998
localtime$lt = localtime( )Overrides the corelocaltimefunction. The Time::tm object returned has methods with the same names as the structure fields they return. That is, to return the field mon, use themonmethod:use Time::localtime; $lt = localtime( ); print $lt->mon;
The field names (and therefore the method names) are the same as the names of the fields in the tm structure in the C file time.h:sec,min,hour,mday,mon,year,wday,yday, andisdst. You can access the fields with the methods or by importing the fields into your namespace with the :FIELDS import tag and prependingtm_to the method name (for example,$tm_mon).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Time::tm
- InhaltsvorschauUsed internally by Time::localtime and Time::gmtime. Don't use it directly. Creates addressable Time::tm struct object.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- UNIVERSAL
- InhaltsvorschauBase class; all blessed references inherit from it:
$sub = $obj->can('print'); $yes = UNIVERSAL::isa($ref, "HASH");Provides the following methods.can$sub = $obj->can(method)Checks if object$objhas a method method. If so, returns a reference to the subroutine; otherwise, returnsundef. Can be called as a static or object method call, or as a subroutine:$ref = UNIVERSAL::can(val, method)
Returns a reference to the subroutine if val is a blessed reference with a method method, andundefif val is not blessed or does not have method.isa$io = $fd->isa(type)Returns true if the reference is blessed into package type or inherits from that package. Can be called as a static or object method call, or as a subroutine:UNIVERSAL::isa(val, type)
Returns true if the first argument is a reference and either of the following is true:- val is a blessed reference and is blessed into package type or inherits from package type.
- val is a reference to a type of Perl variable (e.g.,
'HASH').
VERSIONVERSION([require])Returns the value of the variable$VERSIONin the package the object is blessed into. With require specified,VERSIONdies if the version of the package is not equal to or greater than the version specified in require. Can be called as either a static or object method call.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - User::grent
- InhaltsvorschauOverrides core
getgrent,getgruid, andgetgrnamfunctions with versions that return User::grent objects. The object returned has methods with the same names as the structure fields they return. That is, to return the field name, use thenamemethod:use User::grent; $gr = getgrgid(0) or die "No group zero"; if ( $gr->name eq 'wheel' && @{$gr->members} > 1 ) { print "gid zero name wheel, with other members"; }The field names (and therefore the method names) are the same as the names of the fields in the group structure from the C file grp.h: name, passwd, gid, and members (not mem). The first three return scalars, the last an array reference. You can access the fields with the methods or by importing the fields into your namespace with the :FIELDS import tag and prependinggr_to the method name (for example,gr_name). Exports four functions.getgr$gr->getgr(arg)Frontend that forwards a numeric arg togetgridand other args togetgrname.getgrent$gr = getgrent( )Successive calls togetgrentreturn objects representing successive entries from the group file.getgrgid$gr = getgrgid(gid)Accesses the group file by group ID gid.getgrnam$gr = getgrnam(gname)Accesses the group file by group name gname.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - User::pwent
- InhaltsvorschauOverrides core
getpwent,getpwuid, andgetpwnamfunctions with versions that return User::pwent objects. The object returned has methods with the same names as the structure fields they return. That is, to return the field name, use thenamemethod:use User::pwent; $pw = getpwnam('daemon') or die "No daemon user"; if ( $pw->uid == 1 && $pw->dir =~ m#^/(bin|tmp)?$# ) { print "gid 1 on root dir"; }The field names (and therefore the method names) are the same as the names of the fields in the passwd structure from the C file pwd.h: name, passwd, uid, gid, quota, comment, gecos, dir, and shell. You can access the fields with the methods or by importing the fields into your namespace with the :FIELDS import tag and prependingpw_to the method name (for example,pw_name). Exports four functions.getpw$pw->getpw(arg)Frontend that forwards a numeric arg togetpwuidand other args togetpwnam.getpwent$pw->getpwent( )Successive calls togetpwentreturn objects representing successive entries from the password table.getpwnam$pw->getpwnam(name)Accesses the password table by user's name.getpwuid$pw->getpwuid(uid)Accesses the password table by user's ID number, uid.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - utf8
- InhaltsvorschauWhile Perl's implementation of Unicode support is incomplete, the
use utf8pragma tells the Perl parser to allow UTF-8 in the program text in its current lexical scope.no utf8tells Perl to switch back to treating text as literal bytes in the current lexical scope. You'll probably useuse utf8only for compatibility, since future versions of Perl will standardize on the UTF-8 encoding for source text.use utf8has the following effects: bytes with their high-bit set (identifiers, string constants, constant regular expressions, package names) will be treated as literal UTF-8 characters and regular expressions within the scope of theutf8pragma and will default to using character semantics instead of byte semantics. For example:@bytes_or_chars = split //, $data; # May split to bytes if data # $data isn't UTF-8 { use utf8; # Forces char semantics @chars = split //, $data; # Splits characters }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - vars
- InhaltsvorschauPragma that, given a list of variable names, predeclares all variables in the list, making sure they are available to routines with delayed loading (e.g., routines loaded by the AutoLoader or SelfLoader). This allows you to use the variables under
use strict. Thevarspragma also disables warnings about typographical errors.use vars qw($var1 @var2 %var3);
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - vmsish
- InhaltsvorschauControls VMS-specific language features. Currently, there are four VMS-specific features available:
status ($?),exit,time, andhushed. If you're not using VMS, then this module won't have any affect.vmsish is shipped with the Perl 5.8 source kit.For example, without vmsish, you can't execute ahushedversion of exit:$ perl -e"exit 44;" Non-hushed error exit %SYSTEM-F-ABORT, abort DCL message $ show sym $STATUS $STATUS == "%X0000002C"
When you use vmsish, you get . . . nothing!$ perl -e"use vmsish qw(hushed); exit 44;"
vmsish implements the following options.-
status - Causes
$?andsystemto return the native VMS exit status instead of emulating the POSIX exit status. -
exit - Causes
exit 1to produce a successful exit (with statusSS$_NORMAL) instead of emulating Unixexit(), which considersexit 1as an indication of an error. As with the CRTL'sexit()function,exit 0is also mapped to an exit status ofSS$_NORMAL, and any other argument toexit()is used directly as Perl's exit status. -
time - Makes all times relative to the local time zone instead of the default Universal Time (a.k.a. Greenwich Mean Time, or GMT).
-
hushed - Suppresses printing of VMS status messages to
SYS$OUTPUTandSYS$ERRORif Perl terminates with an error status and allows programs that are expecting Unix-style Perl to avoid parsing VMS error messages. It does not supress any messages from Perl itself, just the messages generated by DCL after Perl exits. The DCL symbol$STATUSwill still have the termination status, but with a high-order bit set.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- XS::Typemap
- InhaltsvorschauTests XS typemaps distributed with Perl. XS::Typemap implements a function that's available for each and every typemap that's in Perl. Generally, you should never use XS::Typemap directly. This module ships with the Perl 5.8 source kit.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 9: CGI Overview
- InhaltsvorschauPerl is the most commonly used language for CGI programming on the World Wide Web .The Common Gateway Interface (CGI) is an essential tool for creating and managing comprehensive web sites. With CGI, you can write scripts that create interactive, user-driven applications.CGI allows the web server to communicate with other programs that are running on the same machine. For example, with CGI, the web server can invoke an external program, while passing user-specific data to the program (such as what host the user is connecting from, or input the user has supplied through an HTML form). The program then processes that data, and the server passes the program's response back to the web browser.Rather than limiting the Web to documents written ahead of time, CGI enables web pages to be created on the fly, based upon the input of users. You can use CGI scripts to create a wide range of applications, from surveys to search tools, from Internet service gateways to quizzes and games. You can increment the number of users who access a document or let them sign an electronic guestbook. You can provide users with all types of information, collect their comments, and respond to them.For Perl programmers, there are two approaches you can take to CGI. They are:
- Programs that handle all CGI interaction directly, without the use of a module such as CGI.pm. While often frowned upon by Perl programmers because it's more likely to introduce bugs, bypassing the modules has the advantage of avoiding the overhead of CGI.pm for quick, dirty tasks. This chapter explains the concepts of CGI necessary if you intend to write CGI programs from scratch.
- CGI.pm is a Perl module designed to facilitate CGI programming. For non-trivial CGI programs, especially ones that need to maintain state over multiple transactions, CGI.pm is indispensable, and is included in the standard Perl distribution as of Perl 5.004. Rather than discuss it in Chapter 8, with the rest of the standard libraries, however, its complexity and importance made it a candidate for its own chapter, Chapter 10.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - A Typical CGI Interaction
- InhaltsvorschauFor an example of a CGI application, suppose you create a guestbook for your website. The guestbook page asks users to submit their first name and last name using a fill-in form composed of two input text fields. Figure 9-1 shows the form you might see in your browser window.
Figure 9-1: HTML formThe HTML that produces this form might read as follows:<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD> <BODY> <H1>Fill in my guestbook!</H1> <FORM METHOD="GET" ACTION="/cgi-bin/guestbook.pl"> <PRE> First Name: <INPUT TYPE="TEXT" NAME="firstname"> Last Name: <INPUT TYPE="TEXT" NAME="lastname"> <INPUT TYPE="SUBMIT"> <INPUT TYPE="RESET"> </FORM>
The form is written using special "form" tags, as follows:- The
<form>tag defines the method used for the form (either GET or POST) and the action to take when the form is submitted—that is, the URL of the CGI program to pass the parameters to. - The
<input>tag can be used in many different ways. In its first two invocations, it creates a text input field and defines the variable name to associate with the field's contents when the form is submitted. The first field is given the variable namefirstnameand the second field is given the namelastname. - In its last two invocations, the
<input>tag creates a "submit" button and a "reset" button. - The
</form>tag indicates the end of the form.
When the user presses the "submit" button, data entered into the<input>text fields is passed to the CGI program specified by theactionattribute of the<form>tag (in this case, the /cgi-bin/guestbook.pl program).Parameters to a CGI program are transferred either in the URL or in the body text of the request. The method used to pass parameters is determined by themethodattribute to the<form>tag. The GET method says to transfer the data within the URL itself; for example, under the GET method, the browser might initiate the HTTP transaction as follows:GET /cgi-bin/guestbook.pl?firstname=Joe&lastname=Schmoe HTTP/1.0
The POST method says to use the body portion of the HTTP request to pass parameters. The same transaction with the POST method would read as follows:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - URL Encoding
- InhaltsvorschauBefore data supplied on a form can be sent to a CGI program, each form element's name (specified by the
nameattribute) is equated with the value entered by the user to create a key/value pair. For example, if the user entered "30" when asked for his or her age, the key/value pair would be "age=30". In the transferred data, key/value pairs are separated by the ampersand (&) character .Since under the GET method the form information is sent as part of the URL, form information can't include any spaces or other special characters that are not allowed in URLs, and also can't include characters that have other meanings in URLs, like slashes (/). (For the sake of consistency, this constraint also exists when the POST method is being used.) Therefore, the web browser performs some special encoding on user-supplied information.Encoding involves replacing spaces and other special characters in the query strings with their hexadecimal equivalents. (Thus, URL encoding is also sometimes called hexadecimal encoding.) Suppose a user fills out and submits a form containing his or her birthday in the syntax mm/dd/yy (e.g., 11/05/73). The forward slashes in the birthday are among the special characters that can't appear in the client's request for the CGI program. Thus, when the browser issues the request, it encodes the data. The following sample request shows the resulting encoding:POST /cgi-bin/birthday.pl HTTP/1.0 Content-length: 21 birthday=11%2F05%2F73
The sequence%2Fis actually the hexadecimal equivalent of the slash character.CGI scripts have to provide some way to "decode" the form data that the client has encoded. The best way to do this is to use CGI.pm (covered in Chapter 10) and let someone else do the work for you.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Extra Path Information
- InhaltsvorschauIn addition to passing query strings, you can pass additional data, known as extra path information, as part of the URL. The server gauges where the CGI program name ends; anything following is deemed "extra" and is stored in the environment variable PATH_INFO. The following line calls a script with extra path information:
http://some.machine/cgi-bin/display.pl/cgi/cgi_doc.txt
In this example, we use a script with a .pl suffix to make it clear where the CGI program's path ends and the extra path information begins. Everything after display.pl is the extra pathand is placed in the PATH_INFO environment variable. The PATH_TRANSLATED variable is also set, mapping the PATH_INFO to the DOCUMENT_ROOT directory (e.g., /usr/local/etc/httpd/public/cgi/cgi_doc.txt).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CGI Environment Variables
- InhaltsvorschauMost of the information needed by CGI programs is made available via Unix environment variables. Programs can access this information as they would any environment variable (via the
%ENVhash in Perl). The table below lists environment variables commonly available through CGI. However, since servers occasionally vary on the names of environment variables they assign, check with your own server documentation for more information.Environment variableContent returnedAUTH_TYPEThe authentication method used to validate a user. See REMOTE_IDENT and REMOTE_USER.CONTENT_LENGTHThe length of the query data (in bytes or the number of characters)passed to the CGI program through standard input.CONTENT_TYPEThe media type of the query data, such astext/html.DOCUMENT_ROOTThe directory from which web documents are served.GATEWAY_INTERFACEThe revision of the Common Gateway Interface that the server uses.HTTP_ACCEPTA list of the media types that the client can accept.HTTP_COOKIEA list of cookies defined for that URL.HTTP_FROMThe email address of the user making the query (many browsers do not support this variable).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 10: The CGI.pm Module
- InhaltsvorschauCGI.pm is a Perl module for creating and parsing CGI forms. It has been distributed with the Perl source kit since 5.004, but you can upgrade your existing CGI.pm installation from CPAN. As of the writing of this edition, the current version of CGI.pm is 2.81.CGI is an object-oriented module. Don't let the object-oriented nature scare you off, though; CGI.pm is very easy to use, as evidenced by its overwhelming popularity among all levels of Perl programmers. To give you an idea of how easy it is to use CGI.pm, let's take a scenario in which a user fills out and submits a form containing her birthday. Without CGI.pm, the script would have to translate the URL-encoded input by hand (probably using a series of regular expressions) and assign it to a variable. For example, you might try an antiquated parsing method like this:
#!/usr/local/bin/perl # CGI script without CGI.pm $size_of_form_info = $ENV{'CONTENT_LENGTH'}; read ($STDIN, $form_info, $size_of_form_info); # Split up each pair of key/value pairs foreach $pair (split (/&/, $form_info)) { # For each pair, split into $key and $value variables ($key, $value) = split (/=/, $pair); # Get rid of the pesky %xx encodings $key =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg; $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg; # Use $key as index for $parameters hash, $value as value $parameters{$key} = $value; } # Print out the obligatory content type line print "Content-type: text/plain\n\n"; # Tell the user what they said print "Your birthday is on " . $parameters{birthday} . ".\n";Regardless of whether this code actually works, you must admit it's ugly, and completely ignores important details such as dealing with tainted input. With CGI.pm, the script could be written as:#!/usr/local/bin/perl -w # CGI script with CGI.pm use CGI; my $query = CGI->new( ); my $bday = $query->param("birthday"); print $query->header(-type => 'text/plain'); print $query->p("Your birthday is $bday.");Even for this tiny program, you can see that CGI.pm can alleviate many of the headaches associated with CGI programming.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - HTML Tag Generation
- InhaltsvorschauIn addition to the form-generation methods, CGI.pm includes a group of methods for creating HTML tags. The names of the HTML tag methods generally follow the HTML tag name (e.g.,
pfor<P>) and take named parameters that are assumed to be valid attributes for the tag (e.g.,img(src=>'camel.gif')becomes<IMG SRC="camel.gif">). We do not list all tags in this book; see the CGI.pm manpage for more information, or the book Official Guide to Programming with CGI.pm by Lincoln Stein (John Wiley & Sons, 1998).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Importing Method Groups
- InhaltsvorschauThe syntax for calling CGI methods can be unwieldy. However, if you choose not to use the object form of CGI.pm, you can import individual methods instead. The "birthday" example shown earlier could be written even more simply as:
#!/usr/local/bin/perl -w use CGI qw(param header p); my $bday = param("birthday"); print header('text/plain'); print "Your birthday is $bday.";By importing theparam,header, andpmethods into your namespace, you no longer have to use thenewconstructor (since it is called automatically now), and you don't need to specify a CGI object with every method call.CGI.pm also lets you import groups of methods, which can make your programs much simpler and more elegant. For example, to import all form-creation methods and all CGI-handling methods:use CGI qw/:form :cgi/;
The method groups supported by CGI.pm are:-
:cgi - All CGI-handling methods
-
:cgi-lib - All methods supplied for backward compatibility with cgi-lib
-
:form - All form-generation methods
-
:html - All HTML methods
-
:html2 - All HTML 2.0 methods
-
:html3 - All HTML 3.0 methods
-
:netscape - All methods generating Netscape extensions
-
:ssl - All SSL methods
-
:standard - All HTML 2.0, form-generation, and CGI methods
-
:all - All available methodsYou can also define new methods for HTML tag generation by simply listing them on the import line and letting CGI.pm make some educated guesses. For example:
use CGI shortcuts,smell; print smell {type=>'garlic', intensity=>'strong'}, "Scratch here!";This will cause the following tag to be generated:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Maintaining State
- InhaltsvorschauOne of the first complications for any nontrivial CGI script is how to "maintain state." Since HTTP is a stateless protocol, there's no built-in mechanism for keeping track of requests from the server end. A CGI transaction involving multiple forms, therefore, needs to find a way to remember information supplied on previous forms. One way to deal with this issue is to use cookies, which allow the CGI program to save information on the browser's end; but not all browsers support cookies, and some users are uncomfortable with the perceived privacy infringement associated with cookies.CGI.pm simplifies maintaining state without cookies. When a CGI.pm script is called multiple times, the input fields are given default values from the previous invocation.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Named Parameters
- InhaltsvorschauFor most CGI.pm methods, there are two syntax styles. In the "standard" style, the position of the parameters determines how they will be interpreted—for example, parameter 1 is the name that the script should assign, parameter 2 is the initial value, etc. For example:
print $query=textfield('username', 'anonymous');In the "named parameters" style, the parameters can be assigned like a hash, and the order doesn't matter. For example:print $query->textfield(-name=>'name', -default=>'value');
If you want to use named parameters, just call theuse_named_parametersmethod early in the script.Which syntax style should you use? It depends on how lazy you are and how much control you need. Generally, standard syntax is faster to type. However, it is also harder to read, and there are many features that are simply not available using standard syntax (such as JavaScript support). In general, we recommend using the named parameters syntax for all but the most trivial scripts.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Using JavaScript Features
- InhaltsvorschauCGI.pm supports JavaScript scripting by allowing you to embed a JavaScript script into the HTML form within
<SCRIPT>tags and then calling the script using the-scriptparameter to thestart_htmlmethod. You can then call the appropriate JavaScript functions to the form elements.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Debugging
- InhaltsvorschauA complication of writing CGI scripts is that when debugging the script, you have to wrestle with the web server environment. CGI.pm provides support for debugging the script on the command line.If you run the script on the command line without arguments, you will be placed into an "offline" mode, in which name/value pairs can be entered one-by-one. When you press Ctrl-D, the script runs. For example:
% birthday (offline mode: enter name=value pairs on standard input) birthday=6/4/65 ^D Content-type: text/html <P>Your birthday is 6/4/65.</P>
You can also supply the name/value parameters directly on the command line. For example:% test birthday=6/4/65 Content-type: text/html <P>Your birthday is 6/4/65.</P>
Multiple values can be separated by spaces (as separate arguments on the command line) or by ampersands (as in URL-encoded syntax). In fact, you can use URL-encoded syntax on the command line. This makes it easy to supply raw CGI input to the script for testing purposes. Just remember to protect the ampersand from the shell.% test 'birthday=6%2f4%2f65&name=Fred%20Flintstone' Content-type: text/html <P>Fred Flintstone, your birthday is 6/4/65.</P>
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - CGI.pm Reference
- InhaltsvorschauThe following methods are supported by CGI.pm.accept$query->accept(['content_type'])Returns a list of media types that the browser accepts.
- content_type
- If specified, returns instead the browser's preference for the specified content type, between 0.0 and 1.0
append$query->append(-name=>'name',-values=>'value')Appends a value or list of values to the named parameter.-
-name=>'name' - The parameter to append.
-
-values=>'value' - The value to append. Multiple values can be specified as a reference to an anonymous array.
auth_typeauth_type( )Returns the authorization method.autoEscape$query->autoEscape(undef)Turns off autoescaping of form elements.buttonprint$query->button('name','function')Generates a JavaScript button.- name
- The name of the button.
- function
- The function to execute when the button is clicked. Using named parameters, the syntax is:
print $query->button(-name=>'name', -value=>'label', -onClick=>"function");
-
-value=>'label' - The label to display for the button
-
checkboxprint$query->checkbox('name' [,'checked','value','label'])Generates a single checkbox.- name
- The name to assign the input to (required).
- checked
- Checkbox should be checked initially.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 11: Web Server Programming with mod_perl
- InhaltsvorschauA common criticism of CGI is that it requires forking extra processes each time a script is executed. If you have only a few hits an hour, or even a few hits a minute, this isn't a big deal. But for a high-traffic site, lots of repeatedly spawning CGI scripts can have an unfortunate effect on the machine running the web server. The CGI scripts will be slow, the web server will be slow, and other processes on the machine will slow to a crawl.The solution to this problem is mod_perl. mod_perl, written by Doug MacEachern and distributed under CPAN, embeds the Perl interpreter directly into the web server. The effect is that your CGI scripts are precompiled by the server and executed without forking, thus running much more quickly and efficiently. Furthermore, CGI efficiency is only one facet of mod_perl. Since mod_perl is a complete Apache/Perl hybrid, other benefits to mod_perl include:
- Writing server-side includes in Perl
- Embedding Perl code into the Apache configuration files
- Writing complete Apache modules in Perl
mod_perl is a Perl runtime library linked into the Apache server. With mod_perl, the Perl programmer has access to Apache's C language API through an object-oriented Perl interface. This means that you can write Apache modules and extensions entirely in Perl and embed Perl code and custom directives in your Apache configuration files. Furthermore, the embedded Perl interpreter removes the overhead that you'd experience if you'd merely written a Perl CGI program and put it in Apache's cgi-bin.Aside from the framework mentioned above, another major benefit of mod_perl is the Apache::Registry module. Apache::Registry implements the CGI environment under the mod_perl framework, which means that you can reuse most of your existing Perl CGI programs to realize the benefits of mod_perl. Apache::Registry caches compiled scripts on the first execution of a script and updates scripts that have changed on disk.Finally, mod_perl gives the Perl programmer the ability to interact with all stages of an HTTP request, many of which aren't available through CGI. These include the Apache handler phase, the HTTP header parser, URI translation, authentication, authorization, access (permissions), type checking, fixup, and logger stages.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Design of mod_perl
- Inhaltsvorschaumod_perl is a Perl runtime library linked into the Apache server. With mod_perl, the Perl programmer has access to Apache's C language API through an object-oriented Perl interface. This means that you can write Apache modules and extensions entirely in Perl and embed Perl code and custom directives in your Apache configuration files. Furthermore, the embedded Perl interpreter removes the overhead that you'd experience if you'd merely written a Perl CGI program and put it in Apache's cgi-bin.Aside from the framework mentioned above, another major benefit of mod_perl is the Apache::Registry module. Apache::Registry implements the CGI environment under the mod_perl framework, which means that you can reuse most of your existing Perl CGI programs to realize the benefits of mod_perl. Apache::Registry caches compiled scripts on the first execution of a script and updates scripts that have changed on disk.Finally, mod_perl gives the Perl programmer the ability to interact with all stages of an HTTP request, many of which aren't available through CGI. These include the Apache handler phase, the HTTP header parser, URI translation, authentication, authorization, access (permissions), type checking, fixup, and logger stages.Now that you've been subjected to two rather optimistic paragraphs, we'll take a few moments to appease the cynics. It might occur to you that sticking a large program into another large program makes a very, very large program. mod_perl certainly makes httpd significantly bigger. If you have limited memory capacity, mod_perl may not be for you. There are several ways to minimize the size of Apache with mod_perl (which you can find in the mod_perl manpage or the FAQs), ranging from fiddling with Apache configuration directives to building Perl with reduced memory consumption.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Installing mod_perl
- InhaltsvorschauIf you already have Apache installed on your machine, you will have to rebuild it with mod_perl. If you prefer, you can install the mod_perl-enabled Apache installation somewhere else, which we'll also detail in this section. You can get the source for both Apache and mod_perl from
http://www.apache.org/dist/httpd/. You can get mod_perl alone from CPAN or fromhttp://perl.apache.org/dist/. The mod_perl build process is quite configurable, and after you've met some Perl module dependencies, you should be well on your way to building and getting your mod_perl-enabled Apache installation online.First, you should take a look at your existing Apache installation (or installations) and make sure that you don't unintentionally interfere with a working Apache installation. If you're running Apache-1.3.X, it's likely that your Apache installation lives under /usr/local/apache, or C:\apache if you're on a Win32 platform. Second, make sure that you're running a current version of Perl and that you've installed the LWP Bundle of modules. If you haven't installed the LWP modules bundle, mod_perl might not build correctly and will not run its tests correctly.Once you've met the requirements listed above, you should unpack the Apache and mod_perl distributions and run:% perl Makefile.PL EVERYTHING=1 APACHE_PREFIX=[target directory]Next, run make, make test, and assuming all goes well, make install to install the mod_perl-enabled Apache:% make % make test % make install
TheEVERYTHING=1option says to build mod_perl with all of the supported features. If this isn't what you were looking for or if you'd like to learn more about making a custom Apache build with mod_perl, you should read the INSTALL file that ships with mod_perl.At the time of this writing, both Apache and mod_perl have been ported to Win32. However, you might have the best results with mod_perl under Win32 if you run ActiveState's Perl distribution and its precompiled version of mod_perl. For further information about building mod_perl under Win32, see INSTALL.win32.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - mod_perl Handlers
- InhaltsvorschauTo understand mod_perl, you should understand how the Apache server works. When Apache receives a request, it processes it in several stages. First, it translates the URL to the associated resource (i.e., filename, CGI script, etc.) on the server machine. Then it checks to see if the user is authorized to access that resource, perhaps by requesting and checking an ID and password or hostname and IP address. Once the user has passed inspection, the server figures out the kind of data it's sending back (e.g., it decides a file ending in .html is probably a
text/htmlfile), creates some headers, and sends those headers back to the client with the resource itself. When all is said and done, the server makes a log entry.At each stage of this process, Apache looks for routines to "handle" the request. That is, if Apache doesn't find handlers you've told it to use, it knows to use its own. For example, if you've enabled CGI programs in httpd.conf, Apache knows to execute programs that live in cgi-bin if it encounters thecgi-scriptdirective:<Location /cgi-bin> ... SetHandler cgi-script ... </Location>
mod_perl allows you to write your own handlers in Perl by embedding the Perl runtime library directly into the Apache httpd server executable. To use mod_perl for CGI (which is all that most people want to do with it), assign theSetHandlerdirective toperl-script, and the mod_perl-specificPerlHandlerdirective to a special Perl module called Apache::Registry:SetHandler perl-script PerlHandler Apache::Registry
PerlHandleris the mod_perl handler for the content retrieval stage of the transaction.To use other handlers, you don't need to reassignSetHandler. For example, to identify a handler for the logging stage of the request:<Location /snoop/> PerlLogHandler Apache::DumpHeaders </Location>
For this to work, mod_perl must have been built with the logging hooks enabled (as described in the previous section), and the Apache::DumpHeaders module must have been installed. mod_perl looks in Apache::DumpHeaders for a routine calledEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Running CGI Scripts with mod_perl
- InhaltsvorschauWhat most people want to do with mod_perl is improve CGI performance. The mod_perl installation assumes this request by enabling the
PerlHandlercallback hook by default and by installing the Apache::Registry module.PerlHandleris the handler used for the content retrieval stage of the server transaction. Apache::Registry is the Perl module that emulates the CGI environment so you can use "standard" Perl CGI scripts with mod_perl without having to rewrite them (much). This is by far the cheapest way to get improved CGI performance.With Apache::Registry, each individual CGI program is compiled and cached the first time it is called (or whenever it is changed) and remains available for all subsequent instances of that CGI script. This process avoids the costs of startup time.Whereas most CGI scripts are kept in cgi-bin, scripts that use Apache::Registry are placed in a separate directory, e.g., perl-bin. The access.conf Apache configuration file needs to point to this directory by setting an alias and defining a handler for this new location:Alias /perl-bin/ /usr/local/apache/perl-bin/ <Location /perl-bin> SetHandler perl-script PerlHandler Apache::Registry PerlSendHeader On Options ExecCGI </Location>
Instead of using thecgi-scripthandler, we use theperl-scripthandler to give control to mod_perl. Next, thePerlHandlerdirective tells mod_perl that the Apache::Registry module should be used for serving all files in that directory.PerlSendHeaderis another mod_perl-specific directive; in this case, it tells mod_perl to send response lines and common headers—by default, none are sent. (For NPH scripts, you'll want to turn this feature off again.)Options ExecCGIis a standard Apache header that is needed to tell Apache to treat the script as a CGI script.If you want to load Perl modules in addition to Apache::Registry, you can use the PerlModule directive:PerlModule CGI
If you include this line, you shouldn't need to explicitlyuse CGIin each Perl CGI script anymore, since CGI.pm will be loaded directly from the Apache server. Up to ten modules can be listed with theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Server-Side Includes with mod_perl
- InhaltsvorschauServer-side includes (SSIs) are tags embedded directly into an HTML file that perform special functions. They are most commonly used for running CGI scripts and displaying the result; most web page counters are performed using SSIs.If you use mod_perl with mod_include (another Apache server module), you can embed Perl subroutines into SSI directives. For example:
<!--#perl sub="sub {print ++Count}" -->The Apache::Include module lets you include entire Apache::Registry scripts:<!--#perl sub="Apache::Include" arg="/perl-bin/counter.pl"-->
You could have used standard SSIs to include a CGI script for the same purpose, but this way is faster. To use mod_include with mod_perl, you need to configure mod_perl to do so at compile time.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - <Perl> Sections
- InhaltsvorschauWith mod_perl, you can use Perl in Apache configuration files. What this means is that you can make your Apache configuration much more flexible by using conditionals.Any Perl code in Apache configuration files should be placed between
<Perl>and</Perl>directives. This code can define variables and lists used by mod_perl to assign the associated Apache configuration directives; for example, assigning the$ServerAdminvariable will redefine theServerAdminApache configuration directive.Suppose you share the same Apache configuration files across multiple servers, and you want to allow personal directories on only one of them. You can use Perl directives like this:<Perl> if ('hostname' =~ /public/) { $UserDir = "public.html"; } else { $UserDir = "DISABLED"; } 1; </Perl>Directive blocks (such as<Location>...</Location>) can be represented as a hash. For example:<Perl> $Location{"/design_dept/"} = { DefaultType => 'image/gif', FancyIndexing => 'On' } </Perl>Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Apache:: Modules
- InhaltsvorschauApache::Registry is the most commonly used mod_perl module. But there are many more, all available on CPAN. The following table lists the Apache::* modules and the handler they're designed to be used with, but you should also check the apache-modlist.html file on CPAN for the latest listing.ModuleDescriptionPerlHandlerApache::CallHandlerMaps filenames to subroutine callsApache::DirControls directory indexingApache::EmbperlEmbeds Perl code in HTML filesApache::ePerlEmbedded Perl (ePerl) emulationApache::FTPEmulates an FTP proxyApache::GzipChainCompresses output from another handlerApache::JavaScriptGenerates JavaScript codeApache::OutputChainChains multiple handlers via "filter" modulesApache::PassFileSends files via OutputChainApache::RegistryRuns unaltered CGI scriptsEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Chapter 12: Databases and Perl
- InhaltsvorschauSince one of Perl's greatest strengths is working with text, a genuine concern is how to store data. Flat files are one possibility, but they don't scale very well for large amounts of data. When working with lots of data, you'll likely need database software to satisfy your capacity and performance requirements.There are two general solutions to using databases with Perl. For simple database purposes, Database Management (DBM) will serve your needs. DBM is a library supported by many (if not all) Unix systems and many non-Unix systems as well. DBM is more efficient than flat text files because of how it packs records into the database files and the (large) size of data it can store and retrieve efficiently. Perl's interface to your system's DBM is based on a hash, so you can add, store, and delete data by key.When you need to store a larger variety of data and need other goodies such as searchability on multiple records, you'll probably need to use a database that supports SQL. To this end, you can buy a prepackaged database product such as Oracle or Sybase, or a shareware equivalent such as MySQL or PostgreSQL. For these larger database projects, you should use DBI and DBD. DBI is a module that provides a consistent interface for database solutions. DBD is a database-specific driver that translates DBI calls as needed for that database.In this chapter, we'll cover DBM and talk at length about DBI/DBD.DBM is a simple database management facility for Unix systems. It allows programs to store a collection of key/value pairs in binary form, thus providing rudimentary database support for Perl. Practically all Unix systems ship with built-in DBM support, some with a separate libdb and others with DBM calls built into libc. In the absence of DBM support on your system, you can use gdbm from GNU, which is an extension to vanilla DBM or BerkeleyDB-3.x from
http://www.sleepycat.com/.To use DBM databases in Perl, you can associate a hash with a DBM database through the AnyDBM module that usestie( ). This hash (called a DBM array) is then used to access and modify the DBM database. Previously, you could useEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - DBM Databases and DBM Hashes
- InhaltsvorschauDBM is a simple database management facility for Unix systems. It allows programs to store a collection of key/value pairs in binary form, thus providing rudimentary database support for Perl. Practically all Unix systems ship with built-in DBM support, some with a separate libdb and others with DBM calls built into libc. In the absence of DBM support on your system, you can use gdbm from GNU, which is an extension to vanilla DBM or BerkeleyDB-3.x from
http://www.sleepycat.com/.To use DBM databases in Perl, you can associate a hash with a DBM database through the AnyDBM module that usestie( ). This hash (called a DBM array) is then used to access and modify the DBM database. Previously, you could usedbmopen( )to open, read, write, and delete a database, but whiledbmopen( )remains available, you should use the AnyDBM module that's always suited to your underlying DBM implementation.For example, with AnyDBM:#!/usr/local/bin/perl -w use AnyDBM_File; use Fcntl; # needed for O_ thingies my %h; my $db_name = 'perl_in_a_nutshell2.dbmx'; # tie %h. will fail if $db_name can't be created and $db_name can't be # written tie(%h, 'AnyDBM_File', $db_name, O_RDWR|O_CREAT, 0640) or die("can't create \%h: $!"); # Populate %h foreach my $letter ('a' .. 'z') { $h{$letter} = uc($letter); } while(my($key, $value) = each(%h)) { print "$key -> $value\n"; } untie(%h);The%ARRAYNAMEparameter is a Perl hash. (If it already has values, the values are discarded under DBM_File modules, although you can have multiple keys under BerkeleyDB-2.x and newer.)%ARRAYNAMEis tied to a DBM database called$db_name. This database may be stored on disk as a single file, or as two files called $db_name.dir and $db_name.pag, depending on the DBM implementation.The$modeparameter is a number that controls the permissions of the pair of files if the files need to be created. The number is in octal, so make sure that you use permissions such as0640instead of640, which are different numbers in octal. If the files already exist,Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Design of DBI
- InhaltsvorschauIf DBM is too primitive for your database requirements, you'll have to use a more sophisticated database package. Options include the commercial products Oracle, Sybase, and Informix, and the freely available MySQL and Postgres.Prior to Perl Version 5 and DBI, the problem was that with all the database packages to choose from, there was no way to universalize database support for Perl. You'd have to rebuild the Perl executable itself against libraries that included subroutines for direct access to the database package. For example, sybperl and oraperl are both packages for building Perl Version 4 with Sybase and Oracle calls embedded, respectively. An application written for sybperl would not be portable to Oracle, or vice versa. However, since current versions of Perl support binary extension loading at runtime, database support can now be added at runtime, which simplifies adding database interfaces to Perl programs while keeping the size of the Perl binary to a minimum.Support for binary extensions doesn't mean that database access has been standardized. There are still many database extensions to Perl, each with a different API. However, their underlying support for SQL (or ability to be manipulated into a form that mimics the behavior of SQL through a DBD) has made it possible to develop a standard set of methods to work with any database. DBI defines a set of functions, variables, and conventions that provide a consistent database programming interface for Perl.The success of DBI is that it is only half of the story. The other half is a DBD, or a database driver. DBI provides the interface and framework for the drivers, but it's the database drivers that do the real work. Drivers implement the DBI methods for the private interface functions of the corresponding database engine.Unless you're developing a sophisticated database application, you probably don't care about the drivers except that you want to install the correct one. Table 12-1 lists database servers, where you can find them, and the DBD driver designed for it. (The freeware or shareware database servers are available for download, and some of the commercial servers offer evaluation copies for download.)Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- DBI Methods
- InhaltsvorschauThe following methods are available under DBI.available_drivers@drivers = DBI->available_drivers([nowarn])Returns a list of available drivers by searching
@INCfor the presence of DBD::* modules.- nowarn
- A Boolean value specifying whether to suppress warnings if some drivers are hidden by others of the same name in earlier directories. Default is false (don't suppress).
bind_col$result = $st_handle->bind_col(col, \variable [, \%attr ])Binds a field of a select statement to a variable, to be updated whenever the row is fetched.- col
- The column number to bind
- \variable
- A reference to the variable to bind
-
\%attr - Attributes to set for the statement handle
bind_columns$result = $st_handle->bind_columns(\%attr,@reflist )Runsbind_colon each column of the statement.-
\%attr - Attributes to set for the statement handle
-
@reflist - A list of references to the variables to bind
bind_param$result = $st_handle->bind_param(n, value [, type ])Binds a value with a placeholder in a prepared statement.- n
- The parameter number to bind.
- value
- The value to associate with parameter n.
- type
- The data type for the placeholder. The type can also be specified as an anonymous list (
{TYPE =>type}).
commit$result = $db_handle->commitCommits the most recent changes. See also the AutoCommit attribute.connect$db_handle = DBI->connect(Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - DBI Environment Variables
- InhaltsvorschauThe following environment variables are defined for use with DBI:
- DBI_DSN
- The data source value to use if none is specified with the
connectmethod. - DBI_DRIVER
- The driver to use if none is specified with the
connectmethod. - DBI_USER
- The username to use if none is specified with the
connectmethod. - DBI_PASS
- The password to use if none is specified with the
connectmethod. (For security purposes, this environment variable should not be set except for testing.) - DBI_TRACE
- Enables tracing behavior as with the
tracemethod. DBI_TRACE can be set to any of the following values:-
0 - Disables the trace
-
1 - Traces the execution of the DBI
-
2 - Outputs detailed call trace information including parameters and return values
-
- filename
- Appends trace information to the specified file; the trace level is set to
2.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 13: XML and Perl
- InhaltsvorschauThe Extensible Markup Language (XML) is a metalanguage for providing complete, configurable information for documents and other types of data. XML is based loosely on SGML, but has divorced itself of much of the complexity that made SGML unsuitable for everyday use. Without opening a can of worms about the differences between SGML and XML, suffice it to say that SGML is the predecessor to XML, and XML is a subset of SGML, with extensions.With XML, you aren't bound by a fixed format, but can mark up a document to make it easily adaptable to whatever final format you later decide to apply it to. In fact, this book is written in XML, to be produced later not only in a print format but in an online format as well.XML is often associated with web content, but it is much more flexible than that. Lately, XML's application to web services such as SOAP and XML-RPC has given it a chance to flex its muscles and show what it's capable of. XML gives you the structure to hold any content you'd like, whether it be the pages of this book in their rawest form, a list of your favorite recipes, or the ledger from your checkbook. XML is structured so that you can represent any kind of data in XML. XML's openness means that you can implement an XML-based application on any platform.This chapter is focused on parsing, checking and delivering XML content. Chapter 14 covers SOAP programming in XML.The two most common tasks that you'll perform on your XML content are likely to be parsing and validating. If you've ever combed around on CPAN for XML-related modules, you probably already know that there's no shortage of resources when it comes to Perl and XML. On the contrary, the sheer volume of modules available for Perl and XML is rather daunting, so you might be looking for a place to start.This chapter covers two Perl/XML modules in particular: XML::Simple and XML::Parser. These modules were selected because they allow you to parse and manipulate most XML. While these modules themselves don't validate XML, we'll resort to a little bit of trickery to show you how you can do exactly that.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- XML Parsing and Validation
- InhaltsvorschauThe two most common tasks that you'll perform on your XML content are likely to be parsing and validating. If you've ever combed around on CPAN for XML-related modules, you probably already know that there's no shortage of resources when it comes to Perl and XML. On the contrary, the sheer volume of modules available for Perl and XML is rather daunting, so you might be looking for a place to start.This chapter covers two Perl/XML modules in particular: XML::Simple and XML::Parser. These modules were selected because they allow you to parse and manipulate most XML. While these modules themselves don't validate XML, we'll resort to a little bit of trickery to show you how you can do exactly that.XML::Simple provides an easy API that allows you to read and write XML. It is built on top of XML::Parser, which will be covered shortly. As its name suggests, XML::Simple implements only two methods:
XMLin( )andXMLout( ). But don't let its apparent lack of methods fool you; XML::Simple lets you do great things simply, such as parsing XML-written configuration files.Let's say that your company keeps a log of its Sun Microsystems servers and their respective operation-system versions, IP addresses, and current patch levels. While you could keep this information in your home directory as a delimited file (which you can parse and analyze when you need to, or import into a database, such as PostGresSQL or MySQL), why not just write it in XML? You'll find that by writing this information in an XML document, you'll be able to operate on this information just as flexibly as you can with one of the aforementioned strategies. In addition, your information would reside in a structure in which the relationships between items and their meanings are clear.Let's say that your flat text log file looks like this:# sunhosts - patches and levels atlas|solaris|2.8|192.168.0.2|Generic_108528-10|5.6.1 carrie|solaris|2.8|192.168.1.10|Generic_108527-12|5.6.0 not4sun|solaris|2.8|192.168.0.25|Generic_108482-06|5.005_03
While you could parse this configuration file easily, and generate some kind of report from it, your configuration file doesn't really tell you anything about the data that it represents. You can represent the same data in XML like so:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - XML::Parser Methods
- InhaltsvorschauThe following methods are defined by XML::Parser.newnew(%option)Constructor. Options are passed as keyword/value pairs. Recognized options are:
-
Style - Sets the type of parser. The built-in styles are
Debug,Subs,Tree,Objects, andStream. Custom styles can be provided by giving a fully qualified package name containing at least one "::". This package must have subroutines defined for each parser type. -
Handlers - An anonymous hash containing the handler types as the keys with their associated values, which are references to subroutines for handling that type of event.
-
Pkg - Some styles will refer to subroutines defined in the specified package.
-
ErrorContext - The number of lines to show surrounding the line in which an error occurred.
-
ProtocolEncoding - Sets the protocol-encoding name (default is none). The built-in encodings are
UTF-8,ISO-8859-1,UTF-16, andUS-ASCII. You may introduce additional encodings by adding directories to@Encoding_Path. -
Namespaces - If true, then namespace processing is done during the parse.
-
NoExpand - Normally, the parser will try to expand references to entities defined internally. If this option is true and a default handler is also set, then the default handler will be called when an entity reference is encountered.
-
Stream_Delimiter - A string for XML::Parser to interpret as end-of-file if found alone on a line. Useful when working with MIME multipart documents. The string should not contain a trailing newline.
-
ParseParamEnt - Unless standalone is set to
yesin the XML declaration, setting this to true allows the external DTD to be read, and parameter entities to be parsed and expanded.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Expat Handlers
- InhaltsvorschauExpat is an event-based parser that recognizes parts of the document (such as the start or end tag for an XML element) and calls any handlers registered for that type of an event. All handlers receive an instance of XML::Parser::Expat as their first argument.
- Init (Expat)
- Called before parsing starts.
- Final (Expat)
- Called after parsing has finished, but only if no errors occurred.
- Start (Expat, Element [, Attr, Val [,...]])
- Generated when an XML start tag is encountered. Element is the name of the XML element type. Attr and Val pairs are generated for each attribute in the start tag of the element.
- End (Expat, Element)
- Generated when an XML end tag or empty tag (
<foo/>) is encountered. - Char (Expat, String)
- Generated when non-markup is recognized, with the non-markup sequence of characters in String given to the handler in
UTF-8. - Proc (Expat, Target, Data)
- Generated when a processing instruction is recognized.
- Comment (Expat, Data)
- Generated when a comment is recognized.
- CdataStart (Expat)
- Called at the start of a CDATA section.
- CdataEnd (Expat)
- Called at the end of a CDATA section.
- Default (Expat, String)
- Called for any characters that aren't tied to a registered handler, including markup declarations. Whatever the encoding in the original document, the string is returned to the handler in
UTF-8. - Unparsed (Expat, Entity, Base, Sysid, Pubid, Notation)
- Called for a declaration of an unparsed entity. Entity is the name of the entity. Base is the base to be used for resolving a relative URI. Sysid is the system ID. Pubid is the public ID. Notation is the notation name. Base and Pubidcan be undefined.
- Notation (Expat, Notation, Base, Sysid, Pubid)
- Called for a declaration of notation. Notation is the notation name. Base is the base to be used for resolving a relative URI. Sysid is the system ID.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - XML::Parser Styles
- Inhaltsvorschau
- Debug
- Prints out the document in outline form.
- Subs
- Allows you to define a subroutine so that when an element is encountered, the subroutine by that name is called, using the same parameters that the Start handler is called with. When an element ends, a subroutine with that name appended with an underscore ("_") is called with the same parameters that the End handler is called with.
- Tree
- Returns a parse tree for the document. Each node in the tree takes the form of a tag/content pair. Text nodes use a pseudo-tag of ``0'' and the string that is their content. Elements represent their content in an array reference, in which the first item in the array is a hash reference containing attributes (if any). The remainder of the array is a sequence of tag/content pairs representing the content of the element.
- Objects
- Similar to Tree, except that a hash object is created for each element.
- Stream
- Prints a copy of the document without comments or declarations if none of the following routines are found:
-
StartDocument - Called at the start of the parse.
-
StartTag - Called for every start tag with a second parameter of the element type. The
$_variable contains a copy of the tag, and the%_variable contains attribute values supplied for that element. -
EndTag - Called for every end tag with a second parameter of the element type. The
$_variable will contain a copy of the end tag. -
Text - Called just before start or end tags with accumulated non-markup text in the
$_variable. -
PI - Called for processing instructions. The
$_variable will contain a copy of the PI, and the target and data are sent as second and third parameters, respectively. -
EndDocument
-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Expat Encodings
- InhaltsvorschauXML documents may be encoded in character sets other than Unicode as long as they can be mapped into the Unicode character set. Expat has further restrictions on encodings. Read the xmlparse.h header file in the expat distribution to see details on these restrictions.Expat has built-in encodings for:
UTF-8,ISO-8859-1,UTF-16, andUS-ASCII. Encodings are set through either the XML declaration encoding attribute or theProtocolEncodingoption to XML::Parser or XML::Parser::Expat.For encodings other than the built-ins, Expat calls the functionload_encodingin the Expat package with the encoding name. This function looks for a file in the path list@XML::Parser::Expat::Encoding_Paththat matches the lowercased name with a .enc extension. The first one it finds, it loads.If you wish to build your own encoding maps, check out the XML::Encoding module from CPAN.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - XML::Parser::ContentModel Methods
- InhaltsvorschauThe element declaration handlers are passed objects of this class as the content model of the element declaration. They also represent content particles, which are components of a content model.When referred to as a string, these objects are automatically converted to a string representation of the model (or content particle):
-
isempty - Returns true if the object is
EMPTY, false otherwise. -
isany - Returns true if the object is
ANY, false otherwise. -
ismixed - Returns true if the object is
(#PCDATA)or(#PCDATA|...)*, false otherwise. -
isname - Returns true if the object is an element name.
-
ischoice - Returns true if the object is a choice of content particles.
-
isseq - Returns true if the object is a sequence of content particles.
-
quant - Returns
undefor a string representing the quantifier (?, *, +) associated with the model or particle. -
children - Returns
undefor (for mixed, choice, and sequence types) an array of component content particles. There will always be at least one component for choices and sequences, but for a mixed content model of purePCDATA,(#PCDATA), thenundefis returned.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Chapter 14: SOAP
- InhaltsvorschauXML's openness allows it to be implemented on any platform. Between the clear nature of XML and the ease at which you can deliver content over the Web, you can easily use XML to distribute content to a wide audience.Imagine an order-entry system for a company with a heterogenous computing environment in locations all over the world. While you could write client software for every platform that you support, a preferable solution might be to deliver XML content over the Web and have an order-entry client that parses the XML, displays the results, and posts any changes back to the server via XML.If you think that such an idea might be a workable one, but fear writing such a thing for yourself from scratch, you might consider trying SOAP or Frontier (XML-RPC2).SOAP (Simple Object Access Protocol) is a protocol that allows you to invoke methods on remote objects. SOAP was originally drafted in 1998 by Dave Winer, Microsoft, and DevelopMentor.SOAP is not tied to any specific programming language. You can find similar SOAP implementations under Perl, Python, C, and Java. It is merely a protocol, one that is simple enough to function under HTTP.SOAP implements its own XML vocabulary that represents methods, return values, and exceptions. By implementing its own set of HTTP headers, SOAP also allows you to handle SOAP packets at your firewall/proxy server.There are two components to SOAP: RPC and EDI. RPC, or remote procedure call, is what you'd use to get a data response (in pairs) from another host, such as a set of items and prices from an order-entry system. EDI is the interface component of SOAP, returning content such as an order entry form, but leaving the actual data processing to RPC.You can try an implementation of SOAP with Perl called SOAP::Lite, written by Paul Kulchenko. SOAP::Lite is a collection of Perl modules that provide a simple and lightweight interface for both the client and server side. This version of SOAP::Lite supports the SOAP 1.1 specification (
http://www.w3.org/TR/SOAP) and works with many SOAP implementions, including Apache SOAP, Frontier, Microsoft SOAP, Microsoft .NET, DevelopMentor, XMethods, 4s4c, Phalanx, Kafka, SQLData, Lucin (in Java), Perl, C++, Python, VB, COM, and XSLT.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - What Is SOAP?
- InhaltsvorschauSOAP (Simple Object Access Protocol) is a protocol that allows you to invoke methods on remote objects. SOAP was originally drafted in 1998 by Dave Winer, Microsoft, and DevelopMentor.SOAP is not tied to any specific programming language. You can find similar SOAP implementations under Perl, Python, C, and Java. It is merely a protocol, one that is simple enough to function under HTTP.SOAP implements its own XML vocabulary that represents methods, return values, and exceptions. By implementing its own set of HTTP headers, SOAP also allows you to handle SOAP packets at your firewall/proxy server.There are two components to SOAP: RPC and EDI. RPC, or remote procedure call, is what you'd use to get a data response (in pairs) from another host, such as a set of items and prices from an order-entry system. EDI is the interface component of SOAP, returning content such as an order entry form, but leaving the actual data processing to RPC.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- SOAP::Lite
- InhaltsvorschauYou can try an implementation of SOAP with Perl called SOAP::Lite, written by Paul Kulchenko. SOAP::Lite is a collection of Perl modules that provide a simple and lightweight interface for both the client and server side. This version of SOAP::Lite supports the SOAP 1.1 specification (
http://www.w3.org/TR/SOAP) and works with many SOAP implementions, including Apache SOAP, Frontier, Microsoft SOAP, Microsoft .NET, DevelopMentor, XMethods, 4s4c, Phalanx, Kafka, SQLData, Lucin (in Java), Perl, C++, Python, VB, COM, and XSLT.Here's an example that uses SOAP::Lite. The following code creates a SOAP::Lite object and uses it, but what's special about the SOAP::Lite object is that it's based on code that lives onwww.soaplite.com. In other words, the code that lives on the remote end of the connection might not be Perl at all—but by using SOAP::Lite, you can execute thef2c( )function as if you were callingf2c( )from your own Perl program.Also note the uri and proxy options. The uri option is the URI for SOAP methods. Basically, uri tells SOAP::Lite where SOAP-related content lives. In Perl terms, uri can represent the class in which you'll find the function to execute. For example, let's say you have the following SOAP server that uses HTTP as its transport mechanism:#!/usr/local/bin/perl -w use SOAP::Transport::HTTP; SOAP::Transport::HTTP::CGI -> dispatch_to('Hello::(?:hello)') -> handle ;This example has two key parts: it will look for a module named "Hello" and will executeHello::hello( )when called. Note that you don't have to explicitly "require" Hello.pm; SOAP::Lite does this for you. Now, let's look at the client:#!/usr/local/bin/perl -w use SOAP::Lite; # If you want to see why something isn't working, enable +trace after # use SOAP::Lite, as shown below #use SOAP::Lite +trace; my $proxy = 'http://www.some.server/cgi-bin/hello'; print SOAP::Lite -> uri('urn:Hello') -> proxy($proxy) -> hello() -> result . "\n\n" ;It's essential that uri, as used above, matches the module in which theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - SOAP::Data
- InhaltsvorschauThe SOAP::Data class allows you specify a value, name, type, URI, or other attributes for SOAP elements. For example, you can serialize the name/value pair of "Nate/31" with the following code:
SOAP::Data->name('Nate')->value(31);This becomes<Nate>31</Nate>.You can also import SOAP::Data methods withimport( ). To import'name':SOAP::Data->import('name');Once imported,'name'can be used as follows:name(Nate => 31);
SOAP::Data also provides an interface to get or set specific attributes, includingactor( ),mustUnderstand( ),encodingStyle( ), androot( ). For example:SOAP::Data ->name(Nate => 31) ->encodingStyle('http://www.some.site/soap/showmetheliteral');This is serialized as follows:<Nate SOAP-ENV:encodingStyle="http://www.some.site/soap/showmetheliteral" xsi:type="xsd:int">31</Nate>
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - SOAP::Serializer
- InhaltsvorschauSOAP::Serializer does not need to be used directly except when autotyping is enabled. It allows you to specify types for your data.You can specify a type with SOAP::Data, with code similar to the following:
SOAP::Data->type(something => [ ... ])
When serialization is reached, SOAP::Lite will attempt to serialize your data with theas_somethingmethod, if such a method exists. If you don't create anas_somethingmethod, no serialization will occur. You can createas_somethingwith the following:sub SOAP::Serializer::as_something { my $self = shift; my($key, $val) = @_; ... return [$key, {'xsi:type' => 'xsd:something', %attr}, $val]; }Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - SOAP::Fault
- InhaltsvorschauThis class gives you access to a fault generated on the server side. To create a fault message, you can simply die on the server side, and the SOAP processor will wrap your message as a
faultstringelement and transfer the fault on the client side. But in some cases, you need to have more control over this process, and the SOAP::Fault class gives it to you. To use it, simply die with the SOAP::Fault object as a parameter:die SOAP::Fault->faultcode('Server.Custom') # Will be qualified ->faultstring('Died in server method') ->faultdetail(bless {code => 1} => 'BadError') ->faultactor('http://www.soaplite.com/custom');Thefaultdetail( )andfaultactor( )methods are optional, and sincefaultcodeandfaultstringare required to represent a fault message, SOAP::Lite will use default values ("Server" and "Application error") if not specified.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 15: Sockets
- InhaltsvorschauWhy build networking functionality into your Perl scripts? You might want to access your email remotely, or write a simple script that updates files on an FTP site . You might want to check up on your employees with a program that searches for Usenet postings that came from your site. You might want to check a web site for any recent changes, or even write your own home-grown web server. The network is the computer these days, and Perl makes network applications easy.Perl programmers have their choice of modules for doing common tasks with network protocols; Chapter 14 through Chapter 17 cover the modules for writing email, news, FTP, and web applications in Perl. If you can do what you want with the available modules, you're encouraged to jump to those chapters and skip this one. However, there will be times when you'll have to wrestle with sockets directly, and that's when this chapter comes in.Sockets are the underlying mechanism for networking on the Internet. With sockets, one application (a server) sits on a port waiting for connections. Another application (the client) connects to that port and says hello; then the client and server have a chat. Their actual conversation is done with whatever protocol they choose—for example, a web client and server would use HTTP, an email server would use POP3 and SMTP, etc. But at the most basic level, you might say that all network programming comes down to opening a socket, reading and writing data, and closing the socket.You can work with sockets in Perl at various levels. At the lowest level, Perl's built-in functions include socket routines similar to the system calls in C of the same name. To make these routines easier to use, the Socket module in the standard library imports common definitions and constants specific to your system's networking capabilities. Finally, the IO::Socket module provides an object interface to the socket functions through a standard set of methods and options for constructing both client and server communications programs.Sockets provide a connection between systems or applications. They can be set up to handle streaming data or discrete data packets. Streaming data continually comes and goes over a connection. A transport protocol such as TCP (Transmission Control Protocol) is used to process streaming data so that all of the data is properly received and ordered . Packet-oriented communication sends data across the network in discrete chunks. The message-oriented protocol UDP (User Datagram Protocol) works on this type of connection. Although streaming sockets using TCP are widely used for applications, UDP sockets also have their uses.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Built-in Socket Functions
- InhaltsvorschauPerl provides built-in support for sockets. The following functions are defined specifically for socket programming. For full descriptions and syntax, see Chapter 5.
-
socket - Initializes a socket and assigns a filehandle to it.
-
bind - For servers, associates a socket with a port and address. For clients, associates a socket with a specific source address.
-
listen - (Server only.) Waits for incoming connection with a client.
-
accept - (Server only.) Accepts incoming connection with a client.
-
connect - (Client only.) Establishes a network connection on a socket.
-
recv - Reads data from a socket filehandle.
-
send - Writes data to a filehandle.
-
shutdown(orclose) - Terminates a network connection.
Regular functions that read and write filehandles can also be used for sockets, e.g.,write,print,printf, and the diamond input operator,<>.The socket functions tend to use hardcoded values for some parameters, which severely hurts portability. Perl solves this problem with a module called Socket, included in the standard library. Use this module for any socket applications that you build with the built-in functions (e.g.,use Socket). The module loads the socket.h header file, which enables the built-in functions to use the constants and names specific to your system's network programming, as well as additional functions for dealing with address and protocol names.The next few sections describe Perl socket programming using a combination of the built-in functions together with the Socket module. After that, we describe the use of the IO::Socket module.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The IO::Socket Module
- InhaltsvorschauThe IO::Socket module included in the core Perl distribution provides an object-oriented approach to socket programming. This module provides a convenient way to handle the large number of options you have to deal with, and it handles the laborious task of forming addresses. IO::Socket is built upon the Socket module provided in the standard library. It inherits from IO::Handle, which supports a class of filehandle objects for much of the IO library. The following IO::Socket functions are simply frontends for the corresponding built-in functions and use the same syntax:
socket socketpair bind listen send recv peername (same as getpeername) sockname (same as getsockname)
Theacceptfunction in IO::Socket is slightly different from the equivalent function, however, and is described later in the chapter.IO:Socket contains two subclasses: INET and UNIX. The INET subclass is used to create and manipulate Internet-domain sockets, such as those used in the examples. The UNIX subclass creates Unix domain sockets.IO::Socket greatly simplifies the implementation of a socket for client communications. The following example creates an Internet-domain socket (using the INET subclass) and attempts to connect to the specified server:use IO::Socket; $sock = new IO::Socket::INET (PeerAddr => 'www.ora.com', PeerPort => 80, Proto => 'tcp'); die "$!" unless $sock;IO::Socket::INET::newcreates an object containing a socket filehandle and connects it to the host and port specified inPeerAddrandPeerPort. The object$sockcan then be written to and read from like other socket filehandles.On the server side, IO::Socket provides a nice wrapper for creating server sockets. The wrapper encompasses thesocket,bind, andlistenprocedures, while creating a new IO::Socket object. For example, we can create an Internet-domain socket withIO::Socket::INET:use IO::Socket; $sock = new IO::Socket::INET (LocalAddr => 'maude.ora.com', LocalPort => 8888, Proto => 'tcp', Listen => 5); die "$!" unless $sock;Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 16: Email Connectivity
- InhaltsvorschauElectronic mail is arguably the most essential Internet application. In fact, for many people, it's their introduction to the Internet. Thus, the Perl modules that deal with email are among the most useful modules. There are two major groups of modules that provide email capabilities. The first group is Graham Barr's libnet collection, which contains packages for developing client-side applications over the Internet in Perl. Table 16-1 lists some of the protocols implemented by the libnet modules.
Table 16-1: Protocols implemented by the libnet modules ProtocolModuleDescriptionPOP3Net::POP3Post Office Protocol, for reading emailSMTPNet::SMTPSimple Mail Transfer Protocol, for sending emailFTPNet::FTPFile Transfer Protocol, for transferring files between hostsNNTPNet::NNTPNetwork News Transfer Protocol, for reading Usenet newsIn this chapter, we discuss Net::SMTP and Net::POP3. Chapter 17 talks about Net::NNTP, Chapter 18 discusses Net::FTP, and Chapter 19 covers Net::LDAP. Other libnet modules, such as Net::SNPP and Net::Time, are not described in this book, but you can get information about them from CPAN or with the perldoc command if libnet is installed on your system.The second group of mail-related modules are the Mail modules, which can be found on CPAN as the MailTools collection. Other interesting mail-related modules include Mail::Folder and its subclasses, Mail::RBL, Mail::Audit, and Unix::AliasFile. This chapter describes the following subset of the Mail modules:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The Net Modules
- InhaltsvorschauNet::SMTP and Net::POP3 are the modules for sending and receiving email via the SMTP and POP3 protocols. When you use these modules, you are working at the socket level; they directly implement the Internet protocols for sending and receiving mail as defined in the relevant RFCs: RFC 821 for SMTP and RFC 1081 for POP3.The Simple Mail Transfer Protocol, or SMTP, is responsible for clients negotiating RCPT ("to") and FROM ("from") requests with an SMTP server, sending data to the SMTP server, and then sending an end-of-data indicator. Net::SMTP is a subclass of Net::Cmd and IO::Socket::INET that implements an interface to the SMTP and ESMTP protocols. These protocols send mail by talking to an SMTP server through a socket, as described in RFC 821.When would you want to use Net::SMTP instead of sending mail with an external program? Since socket communications don't involve spawning an external program, your programs won't suffer from the overhead associated with running an extra process. Talking to SMTP is convenient for sending a volume of mail messages. Naturally, your server must have an SMTP server running, or a remote mailhost must allow you to talk to it; otherwise, you won't be able to use this module. That's when you can turn to Mail::Mailer or Mail::Send and let them provide an interface to an external mail program for you. This is the case, for example, with home computers, which don't generally run their own SMTP server.The SMTP protocol defines the set of commands a client sends to an SMTP server, which is generally bound to port 25 of a mailhost. Requests and responses are negotiated between client and server.When a client negotiates an SMTP session with a server, the server tells the client that it's listening. Once you're connected, you introduce yourself to the server by issuing a HELO command. The HELO command accepts one parameter—your hostname—and defaults to your remote hostname if you don't specify one. If the command is successful, the server sends a 250 response, as follows:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- The Mail Modules
- InhaltsvorschauThe Mail modules operate at a higher level than the Net modules, interacting with external mail packages such as mail, mailx, sendmail, or a POP3 server in the case of Net::POP3. This section describes some of the MailTools modules, Mail::Folder, and the other mail-related modules that were mentioned at the beginning of this chapter.The Mail::Mailer module interacts with external mail programs. When you use Mail::Mailer or create a new Mail::Mailer object, you can specify which mail program you want your program to talk to:
use Mail::Mailer qw(mail);
Another way to specify the mailer is:use Mail::Mailer; $type = 'sendmail'; $mailprog = Mail::Mailer->new($type);
in which$typeis the mail program. Once you've created a new object, use theopenfunction to send the message headers to the mail program as a hash of key/value pairs, in which each key represents a header type, and the value is the value of that header:# Mail headers to use in the message %headers = ( 'To' => 'you@mail.somename.com', 'From' => 'me@mail.somename.com', 'Subject' => 'working?' );This code represents headers in which the recipient of the mail message is you@mail.somename.com, the mail was sent from me@mail.somename.com, and the subject of the mail message is working?.Once%headershas been defined, it is passed toopen:$mailprog->open(\%headers);
You then send the body of the message to the mail program:print $mailprog "This is the message body.\n";
Close the program when the message is finished:$mailprog->close;
A practical example of using Mail::Mailer might be a command line-driven application that works much like the Unix mail program, either reading STDIN until end-of-file or mailing a file specified on the command line.Mail::Mailer uses the environment variable PERL_MAILERS to augment or modify the built-in mailer selection. PERL_MAILERS is specified in the following format:"type1:mailbinary1;mailbinary2;...:type2:mailbinaryX;...:..."
The possible types are listed for thenewmethod below.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 17: Usenet News
- InhaltsvorschauUsenet is a collection of bulletin board-like newsgroups on the Internet, covering thousands of topics. Whatever your interest, chances are you'll find a newsgroup in which it is discussed .Usenet has been around since late 1979. The current implementation is based on the Network NewsTransfer Protocol (NNTP), defined in RFC 977 and released in March 1986. Information is propagated through Usenet by a system of newsfeeds in which one site requests a newsfeed from another site, and a third site requests a newsfeed from the second site, etc. There is no central Usenet authority—like Perl, it runs on the spirit of cooperation and sharing. When you run a news reader, such as tin or the news reader in a web browser, your client software talks to the NNTP server on the news host. When you post a message to a newsgroup, this posting is received by your NNTP server and passed on to other servers throughout the distribution area you specified for the posting. Each server periodically receives updated newsgroup information and newly posted news articles.This chapter explores NNTP commands and responses. It introduces Net::NNTP, which implements NNTP commands and simplifies the process of writing a Perl-based NNTP news client. It also describes News::Newsrc, a module that provides methods for managing a .newsrc file.There are two kinds of NNTP commands: the official set of commands as defined in RFC 977 and a number of extensions that have been added since the RFC was written. The extensions are described in an IETF Internet Draft document, "Common NNTP Extensions" by Stan Barber, which can be found at
ftp://ftp.academ.com/pub/nntp/ietf/nntpext.txt.Before you write your own news client, you should have some idea of how the NNTP protocol works. Like other servers, an NNTP server is bound to a port (usually port 119). It listens for incoming connections, takes the appropriate action, and returns a response to the client. When a news client connects with an NNTP server, or to the port on which the NNTP server is running, a message such as the following is produced:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The NNTP Protocol
- InhaltsvorschauBefore you write your own news client, you should have some idea of how the NNTP protocol works. Like other servers, an NNTP server is bound to a port (usually port 119). It listens for incoming connections, takes the appropriate action, and returns a response to the client. When a news client connects with an NNTP server, or to the port on which the NNTP server is running, a message such as the following is produced:
Trying 0.0.0.0... Connected to hostname.mydomain.com. Escape character is '^]'. 200 newshost.mydomain.com InterNetNews NNRP server INN 1.5.1 17-Dec-1996 ready (posting ok).
Many NNTP servers understand the help (or HELP) command. When a client issues a help command, many NNTP servers respond with a list of all available commands. For example:200 news.mydomain.com InterNetNews NNRP server INN 1.5.1 17-Dec-1996 ready (posting ok). HELP 100 Legal commands authinfo user Name|pass Password|generic <prog> <args> article [MessageID|Number] body [MessageID|Number] date group newsgroup head [MessageID|Number] help ihave last list [active|active.times|newsgroups|distributions|distrib.pats| overview.fmt|subscriptions] listgroup newsgroup mode reader newgroups yymmdd hhmmss ["GMT"] [<distributions>] newnews newsgroups yymmdd hhmmss ["GMT"] [<distributions>] next post slave stat [MessageID|Number] xgtitle [group_pattern] xhdr header [range|MessageID] xover [range] xpat header range|MessageID pat [morepat...] xpath MessageID Report problems to <usenet@news.mydomain.com> .
After connecting to the NNTP server, you can get a list of available newsgroups with the list active command, and you can then select a newsgroup. If you were to connect directly to news.mydomain.com and use the group command to select the newsgroup local.test, your session might look like this:200 news.mydomain.com InterNetNews NNRP server INN 1.5.1 17-Dec-1996 ready (posting ok). group local.test 211 4 1 4 local.test QUIT 205 .
The four numbers (in this example,211 4 1 4) preceding the group name (local.testEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::NNTP
- InhaltsvorschauNet::NNTP is one of the libnet modules. It provides methods for programming a news client to interface with an NNTP server. Net::NNTP implements the NNTP protocol as defined in RFC 977, as well as a number of extensions defined in the IETF Internet Draft document mentioned earlier.For example, the following code:
$nntp->post(@message);
is equivalent to issuing the post command and associated X-headers directly to an NNTP server on port 119.To use Net::NNTP, create a new Net::NNTP object:use Net::NNTP; $nntp = Net::NNTP->new; # Use default port and options
Once you've created the object, you can use any of the Net::NNTP methods on that object. The Net::NNTP methods generally parallel the functionality of the raw NNTP commands. Your news client can be written to perform many functions, including:- Authenticating a user to the server
- Listing available newsgroups
- Retrieving news headers and articles
- Extracting headers
- Checking for new articles
- Posting articles
- Listing information such as active messages in a newsgroup, new newsgroups, valid distribution areas, or message IDs of newly arrived messages
Net::NNTP includes methods that implement many of the extensions to RFC 977; the description indicates if a method is an extension. Extensions that are not supported by Net::NNTP are AUTHINFO, GENERIC, XINDEX, XSEARCH, and XTHREAD. In addition, some extensions supported by Net::NNTP may not be supported by a particular server.Unless otherwise stated, all the methods return either true or false to indicate success or failure. If a method returns a value instead, then it returnsundefor an empty list to indicate failure.In this list, message-spec refers to a single message ID, a single message number, or a reference to a list of two message numbers. It can also be passed as a list of two message numbers, but this is for compatibility only and is now deprecated.Where pattern-matching is indicated, the matching is done according to the NNTP specification. See the Net::NNTP documentation for details.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The News::Newsrc Module
- InhaltsvorschauMost Unix-based newsreaders parse and extract your newsgroup information from a .newsrc file. This file contains an entry for each newsgroup, with the name of the group and a comma-separated list of article numbers from 1 to the current article. The first entry in the list shows articles that have been read; the remaining entries list unread articles. Each entry also has a colon (:) following the name if you are subscribed to that newsgroup, or an exclamation point (
!) if you are currently unsubscribed.To read a newsgroup, your newsreader needs to be connected to an NNTP server. The newsreader then checks the .newsrc entry for that newsgroup to determine which articles you haven't read, and displays the first unread article. You can then read the articles sequentially or select which articles you want to read. When you "catch-up" a newsgroup by marking all the articles as "read", or when you exit from the newsreader program, your .newsrc file is updated to reflect your activity during that session.The News::Newsrc module provides methods for managing your .newsrc file. Some of the functions it provides include letting you add, remove, or reorder newsgroups; subscribe to or unsubscribe from newsgroups; and mark articles as read or unmark them. Unless you tell it to rearrange the order of the newsgroups in .newsrc, News::Newsrc leaves the order unchanged.new$newsrc = new News::NewsrcConstructor. Creates a new News::Newsrc object that contains no newsgroups.add_group$newsrc->add_group(groupname[, options])Adds newsgroup to .newsrc, as a subscribed group. Defaults to adding at the end. The arguments are:- groupname
- Name of the newsgroup to add.
- options
- Hash with one entry, indicating where to put the newsgroup. Key is
where, and possible values are:-
after =>
-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 18: FTP
- InhaltsvorschauThe File Transfer Protocol (FTP) is a popular means of transferring files between computers. FTP communication follows the client/server model: the client initiates a conversation by sending commands, and the server responds with messages and status codes, as well as by sending or receiving files. This chapter discusses two FTP-related modules included in the libnet distribution: Net::FTP, which provides a number of wrapper functions for implementing the client side of FTP, and Net::Netrc, which provides an interface for getting information from a .netrc file.The FTP protocol permits two-way file transactions, in which files can be sent to or taken from an FTP server. These transactions involve the local filesystem (on the client side) and the remote filesystem (on the server side). When a file is transferred between the local and remote systems, its filename on the destination system is the same as on the source system, unless you specify a new filename.The FTP protocol also lists the types of files that can be transferred. These types define (among many other things) how end-of-line characters are handled for different types of files.When a server accepts FTP requests, it opens a port (generally port 21) for incoming connections and authenticates clients based on account or anonymous privileges. A user may log in with a legitimate account on that machine, provide her own password, and access any file she normally has access to under the Unix shell. Many servers also allow "anonymous" FTP, in which users log in with the name "anonymous" and use their email address as the password. They are then granted restricted access to a limited portion of the filesystem.The FTP commands defined in RFC 959 are listed in the following table:CommandMeaningABORAbort previous FTP command.ACCTEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- The FTP Protocol
- InhaltsvorschauWhen a server accepts FTP requests, it opens a port (generally port 21) for incoming connections and authenticates clients based on account or anonymous privileges. A user may log in with a legitimate account on that machine, provide her own password, and access any file she normally has access to under the Unix shell. Many servers also allow "anonymous" FTP, in which users log in with the name "anonymous" and use their email address as the password. They are then granted restricted access to a limited portion of the filesystem.The FTP commands defined in RFC 959 are listed in the following table:CommandMeaningABORAbort previous FTP command.ACCTSpecify the user's account.ALLOTell server to allocate additional storage for new file.APPETell server to append to an existing file.CDUPChange to parent directory.CWDChange directory.DELEDelete a file.HELPGet help.LISTList files for display.MKDMake a directory.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- Net::FTP
- InhaltsvorschauNet::FTP is used to transfer files from remote hosts. With Net::FTP, you can write simple FTP clients that transfer files from remote servers based on information passed on the command line or from hardcoded variables. Here is an example of a client that connects to a remote FTP server and gets a file from the server:
#!/usr/local/bin/perl -w use Net::FTP; $hostname = 'remotehost.com'; $username = 'anonymous'; $password = 'myname@mydomain.com'; # Hardcode the directory and filename to get $home = '/pub'; $filename = 'TESTFILE'; # Open the connection to the host $ftp = Net::FTP->new($hostname); # Construct object $ftp->login($username, $password); # Log in $ftp->cwd($home),"\n"; # Change directory print $ftp->ls($home),"\n"; # Now get the file and leave $ftp->get($filename); $ftp->quit;
FTP clients have also been integrated with most World Wide Web browsers, using ftp:// in place of http://. When the URL points to a directory, the browser displays a listing of the directory, in which each filename is a link to that file. When the URL points directly to a file, the remote file is downloaded.Here's an example that uses Net::FTP to list files from a remote FTP server on a web page, with a link from each file to the URL of the file on the remote site:#!/usr/local/bin/perl -w use Net::FTP; $hostname = 'remotehost.com'; # FTP host $username = 'anonymous'; # Username $password = 'myname@mydomain.com'; # Password $home = '/pub'; $ftp = Net::FTP->new($hostname); # Net::FTP constructor $ftp->login($username, $password); # Log in w/username and password $pwd = $ftp->pwd; # Get current directory print <<HTML; # Output HTML page Content-type: text/html <HTML> <HEAD> <TITLE>Download Files</TITLE> </HEAD> <BODY> <B>Current working directory:</B> $pwd<BR> Files to download: <P> HTML @entries = $ftp->ls($home); # Slurp all entries into an array foreach (@entries) { # Output links for all files in the ftp area # as links print "<INPUT TYPE=hidden NAME=\"files\" VALUE=\"$_\">\n"; print "<A HREF=\"ftp://$hostname$_\">", "<IMG SRC=\"http://www/icons/f.gif\" border=0>\n"; print " $_</A><BR>\n"; } print <<HTML; </BODY> </HTML> HTML $ftp->quit; # end FTP sessionEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - FTP Configuration with Net::Netrc
- InhaltsvorschauUnix-based FTP clients use a file called .netrc, which you can configure to automate FTP access to sites you frequently visit. With a properly defined .netrc file, you can simply execute the FTP command to a favorite FTP host and be automatically logged in to the FTP server. Your .netrc file contains one line for each connection you want to make. The following tokens can be specified for each entry:
-
machinename - Specifies a remote machine to which you want to autologin:
machine remotehost.com
Instead ofmachinename, you can specify the single worddefaultto match any machine name. This is usually used for anonymous logins to machines not listed in .netrc. -
loginname - If present, identifies the user who logs in to the remote machine, in which name is the login name.
-
passwordpasswd - If present, gives the password for the user. The autologin process uses the specified password if the remote server requires one.
-
accountacctpw - If present, gives an additional password for the user. The autologin process uses this password if the remote server requires one.
-
macdefname - If present, defines a macro with the specified name. Net::Netrc simply parses this field, to maintain compatibility with FTP.
Here's an example of a typical .netrc entry:machine remotehost.com login username password userpasswd
Entering your username and password for remote sites in unencrypted form has serious security implications. Many sites consider .netrc files a violation of security policy and do not allow them. In addition, most FTP clients require that the .netrc file be owned by you and readable by only you, with permissions set to 0400 or 0600. If the permissions aren't correctly set, the autologin process aborts. Net::Netrc follows this security convention—if the permissions and ownership are not correct, theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Chapter 19: Lightweight Directory Access with Net::LDAP
- InhaltsvorschauLDAP was designed as a client/server protocol to provide quick and simple access to entries that live in a directory. Initially, LDAP was designed to provide a better interface to X.500 directory services, but its ease of implementation and IETF-based change control means that LDAP has carved its own niche as a directory service.What is a directory service? In short, the directory is where you store an entry. Each entry implements information about an object. Entries have attributes with a type and at least one value. These attributes have a strict syntax that determines the types of values allowed for the attributes. Such attribute syntaxes include strings, JPEG photographs, and URLs.If you've ever tried to solve a complex problem in a heterogenous computing environment, such as syncing user accounts between different computing platforms, managing a company-wide address book, or building a public-key infrastructure, you might be interested in what LDAP has to offer.While the IETF governs changes to the LDAP spec, you are not limited to a single source for the availability of an LDAP server. Companies such as iPlanet, Novell, and Microsoft sell commercial LDAP implementations, and you'll also find a good, free LDAP implemenation in OpenLDAP (
http://www.openldap.org).Net::LDAP implements the LDAP API for Perl programs. You can use Net::LDAP to search or modify the contents of your LDAP directory. In other words, Net::LDAP does everything that you need it to.This chapter covers Net::LDAP and how to operate on data in an LDAP directory, but it is not an LDAP tutorial. If you're unfamiliar with LDAP, it is strongly encouraged that you refer to your LDAP server documentation before attempting to make any changes to your directory.LDAP stores data in a structure as described in RFC 1617, which also offers guidelines as to how your naming style might look. While there are many ways to implement a data hierarchy in LADP, you can implement your directory structure so that all entries live under a single root that represents your organization. For example, you can import all your Unix account data forEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - How Data Is Stored in LDAP
- InhaltsvorschauLDAP stores data in a structure as described in RFC 1617, which also offers guidelines as to how your naming style might look. While there are many ways to implement a data hierarchy in LADP, you can implement your directory structure so that all entries live under a single root that represents your organization. For example, you can import all your Unix account data for your.domain into a directory server with the following:
object: your.domain Organizational Unit: People Type for login name: uid
Your Unix account information would be stored in LDAP like so:uid=youruser,ou=People,o=your.domain
At the simplest level, data as imported into LDAP by way of the LDAP Directory Interchange Format (LDIF). LDIF is a standard data format that specifies all the information about a record that you will insert into the directory. Take, for instance, a Unix account that lives in /etc/passwd:nvp:-password-:1000:1000:Nathan V. Patwardhan:/home/nvp:/usr/bin/bash
When you break the password entry down, the following fields exist:login nvp password -password- uid 1000 gid 1000 gecos Nathan V. Patwardhan home directory /users/nvp shell /usr/bin/bash
The Unix /etc/passwd entries correspond to entries that you've created in LDAP, with the following naming differences:UNIX LDAP equivalent login uid password userPassword uid uidNumber gid gidNumber gecos cn, gecos home directory homeDirectory shell loginShell
Every LDIF begins with a DN, or distinguished name, which describes where the entry will live in the directory. Without the distinguished name, the LDIF is invalid. Unix accounts might live underou=People, while addressbook entries might live underou=Addresses. The LDIF also contains all of the attributes for a given entry and their corresponding values. For the Unix password entry shown above, the LDIF would look like:dn: uid=nvp,ou=People,o=your.domain uid: nvp cn: Nathan Patwardhan givenname: Nathan sn: Patwardhan objectClass: person objectClass: organizationalPerson objectClass: account objectClass: shadowAccount objectClass: top userPassword: {crypt}/-password- loginShell: /usr/bin/bash uidNumber: 1000 gidNumber: 1000 homeDirectory: /users/nvpEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Searching an LDAP Directory with Net::LDAP
- InhaltsvorschauOne of the most common actions you'll perform against LDAP is searching. If you're using LDAP as a repository for your mail aliases, you'll search the directory each time mail is sent to a given address. If you're using LDAP as a repository for user accounts, you'll search the directory every time a user logs into your system, or when a user performs a task on the system that requires information that resides only in LDAP.Under LDAP, searching consists of three parts:
- Binding to a directory server by name (or by other credentials, such as Kerberos tokens) and port. You can provide a login and password for the authentication or bind anonymously if you have permissions to search or write a part of the directory.
- Passing your search request to the directory server.
- Unbinding from the directory server, thus closing the connection.
Let's say that you want to find a user callednvpin the directory server that's living on ldap.your.server. With Net::LDAP, do the following:use Net::LDAP; my $lsvr = 'ldap.your.domain'; my $ldap = Net::LDAP->new($lsvr) or die "error connecting to $lsvr: $@"; $ldap->bind; # Bind anonymously, that is, no login and pass my $results = $ldap->search ( # Perform a search for 'nvp' filter => "(&(uid=nvp) (o=your.domain))" ); if($results->code) { die "received LDAP error: @{[$results->error]}; } foreach my $entry ($results->all_entries) { $entry->dump; } $ldap->unbind; # Unbind and close connectionEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Adding an Entry to the Directory with Net::LDAP
- InhaltsvorschauNow that you've searched the directory with Net::LDAP, let's add an item. In the previous example, you bound to the directory anonymously, but when writing changes to the directory (that is, adding or deleting entries), you'll probably have to bind as an administrator or another user delegated with similar privileges. In this example, we'll use "Directory Manager" as the directory administrator.Adding to a directory with Net::LDAP is a two-phase process:
- Bind to the directory as a user who has privileges to write to the directory. In this instance, we'll use "Directory Manager".
- Use
Net::LDAP::add( )to add the entry.add( )takes the parts of the record that you will add to the directory as arguments.
This example, based on the following LDIF, usesadd( )to add an account for'nvp'to the directory:dn: uid=nvp,ou=People,o=your.domain uid: nvp cn: Nathan Patwardhan givenname: Nathan sn: Patwardhan objectClass: person objectClass: organizationalPerson objectClass: account objectClass: shadowAccount objectClass: top userPassword: {crypt}/-password- loginShell: /usr/bin/bash uidNumber: 1000 gidNumber: 1000 homeDirectory: /users/nvpHere's the code:my $admin = q[cn=Directory Manager]; my $ad_pw = q[adminpass]; my $lsvr = q[ldap.my.domain]; my $org = q[o=my.domain]; my $o_ou = q[ou=People]; my $o_act = q[uid=nvp]; my $ldap = Net::LDAP->new($lsvr); # Bind to a directory with DN and password $ldap->bind($admin, password => $ad_pw); my $l_rec = qq[$o_act, $o_ou, $org]; $result = $ldap->add($l_rec, attr => [ 'cn' => ['Nathan Patwardhan'], 'sn' => 'Patwardhan', 'mail' => 'nvp@my.domain', 'objectclass' => ['top', 'person', 'organizationalPerson', 'inetOrgPerson'], 'gecos' => ['Nathan Patwardhan'], 'loginShell' => '/usr/bin/bash', 'uidNumber' => 1000, 'gidNumber' => 1000, 'shadowPass' => 'XXXXXXXXX' ] ); if($result->code) { warn "failed to add entry: @{[$result->error]}"; } $ldap->unbind;Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Net::LDAP Methods
- InhaltsvorschauNet::LDAP implements the following methods:
-
new (host[, %options]) new( )creates a new Net::LDAP object and opens a connection to host.%options include:-
port - Port to connect to on the remote server.
-
timeout - The maximum time that Net::LDAP will take to connect to a host. The default is 120 seconds.
-
debug - Shows details of the conversion between Net::LDAP and the directory server.
-
async - Performs asynchronous entry retrieval so that search results are returned to the client as they are identified:
$ldap = Net::LDAP->new('ldap.my.domain', async => 1); -
onerror - If set to true, and if
asyncis also true, then Net::LDAP will check for errors on all methods. If an error exists in the resulting data, then one of the following actions will be taken:die( ),warn( ),undef. -
CODEREF - Calls the given coderef in a scalar context with the result message as the argument.
-
version( ) - Sets the version of the LDAP protocol to use. Values are
LDAPv2(default) andLDAPv3.
-
-
bind(dn[, %options]) - Binds to the server that's contained in the connection handle. dn is the DN to bind as. You'll end up binding anonymously if you call
bind( )without any arguments.As for%options, you should give no more than one of the following:-
noauth
-
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Chapter 20: The LWP Library
- InhaltsvorschauThe library for web access in Perl (LWP), is a bundle of modules that provide a consistent, object-oriented approach to creating web applications. The library, downloaded as the single file named libwww-perl, contains the following classes :
- File
- Parses directory listings.
- Font
- Handles Adobe Font Metrics.
- HTML
- Parses HTML files and converts them to printable or other forms.
- HTTP
- Provides client requests, server responses, and protocol implementation.
- LWP
- The core of all web client programs. It creates network connections and manages the communication and transactions between client and server.
- URI
- Creates, parses, and translates URLs.
- WWW
- Implements standards used for robots (automatic client programs).
Each module in LWP provides different building blocks that allow you to do basically anything you can do in a Web browser—from connection, to request, to response and returned data. These parts are then encapsulated by an object to give a standard interface to every web program you write.This chapter covers all the modules in the LWP distribution. While some modules are more useful than others, everything you need to know about LWP is included here. To begin with, the following section gives an overview of how LWP works to create a web client.Any web transaction requires an application that can establish a TCP/IP network connection and send and receive messages using the appropriate protocol (usually HTTP). TCP/IP connections are established using sockets, and messages are exchanged via socket filehandles. (See Chapter 15 for information on how to manually create socket applications.) LWP provides an object for this application with LWP:: UserAgent for clients; HTTP::Daemon provides a server object. The UserAgent object acts as the browser: it connects to a server, sends requests, receives responses, and manages the received data. This is how you create a UserAgent object:use LWP::UserAgent; $ua = LWP::UserAgent->new( );
The UserAgent now needs to send a message to a server requesting a Universal Resource Locator (URL) using theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - LWP Overview
- InhaltsvorschauAny web transaction requires an application that can establish a TCP/IP network connection and send and receive messages using the appropriate protocol (usually HTTP). TCP/IP connections are established using sockets, and messages are exchanged via socket filehandles. (See Chapter 15 for information on how to manually create socket applications.) LWP provides an object for this application with LWP:: UserAgent for clients; HTTP::Daemon provides a server object. The UserAgent object acts as the browser: it connects to a server, sends requests, receives responses, and manages the received data. This is how you create a UserAgent object:
use LWP::UserAgent; $ua = LWP::UserAgent->new( );
The UserAgent now needs to send a message to a server requesting a Universal Resource Locator (URL) using therequestmethod.requestforms an HTTP request from the object given as its argument. This request object is created by HTTP::Request .An HTTP request message contains three elements. The first line of a message always contains an HTTP command called a method; a Universal Resource Identifier (URI), which identifies the file or resource the client is querying; and the HTTP version number. The following lines of a client request contain header information, which provides information about the client and any data it is sending the server. The third part of a client request is the entity body, which is data sent to the server (for the POST method). The following is a sample HTTP request:GET /index.html HTTP/1.0 User-Agent: Mozilla/1.1N (Macintosh; I; 68K) Accept: */* Accept: image/gif Accept: image/jpeg
LWP::UserAgent->requestforms this message from an HTTP::Request object. A request object requires a method for the first argument. The GET method asks for a file, while the POST method supplies information such as form data to a server application. There are other methods, but these two are most commonly used.The second argument is the URL for the request. The URL must contain the server name because this is how the UserAgent knows where to connect. The URL argument can be represented as a string or as a URI::URL object, which allows more complex URLs to be formed and managed. Optional parameters for an HTTP::Request include your own headers, in the form of an HTTP::Headers object, and any POST data for the message. The following example creates a request object:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The LWP Modules
- InhaltsvorschauThe LWP modules provide the core of functionality for web programming in Perl. It contains the foundations for networking applications, protocol implementations, media type definitions, and debugging ability.The modules LWP::Simple and LWP::UserAgent define client applications that implement network connections, send requests, and receive response data from servers. LWP::RobotUA is another client application used to build automated web searchers following a specified set of guidelines.LWP::UserAgent is the primary module used in applications built with LWP. With it, you can build your own robust web client. It is also the base class for the Simple and RobotUA modules. These two modules provide a specialized set of functions for creating clients.Additional LWP modules provide the building blocks required for web communications, but you often don't need to use them directly in your applications. LWP::Protocol implements the actual socket connections with the appropriate protocol. The most common protocol is HTTP, but mail protocols (such as SMTP), FTP for file transfers, and others can be used across networks.LWP::MediaTypes implements the MIME definitions for media type identification and mapping to file extensions. The LWP::Debug module provides functions to help you debug your LWP applications.The following sections describe the RobotUA, Simple, and UserAgent modules of LWP.The Robot User Agent (LWP::RobotUA) is a subclass of LWP::UserAgent and is used to create robot client applications. A robot application requests resources in an automated fashion. Robots perform such activities as searching, mirroring, and surveying. Some robots collect statistics, while others wander the Web and summarize their findings for a search engine.The LWP::RobotUA module defines methods to help program robot applications and observes the Robot Exclusion Standards, which web server administrators can define on their web site to keep robots away from certain (or all) areas of the site.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
- The HTTP Modules
- InhaltsvorschauThe HTTP modules implement an interface to the HTTP messaging protocol used in web transactions. Its most useful modules are HTTP::Request and HTTP::Response, which create objects for client requests and server responses. Other modules provide means for manipulating headers, interpreting server response codes, managing cookies, converting date formats, and creating basic server applications.Client applications created with LWP::UserAgent use HTTP::Request objects to create and send requests to servers. The information returned from a server is saved as an HTTP::Response object. Both of these objects are subclasses of HTTP::Message, which provides general methods of creating and modifying HTTP messages. The header information included in HTTP messages can be represented by objects of the HTTP::Headers class.HTTP::Status includes functions to classify response codes into the categories of informational, successful, redirection, error, client error, or server error. It also exports symbolic aliases of HTTP response codes; one could refer to the status code of 200 as RC_OK and refer to 404 as RC_NOT_FOUND.The HTTP::Date module converts date strings from and to machine time. The HTTP::Daemon module can be used to create web server applications, utilizing the functionality of the rest of the LWP modules to communicate with clients.This module summarizes a web client's request. For a simple GET request, you define an object with the GET method and assign a URL to apply it to. Basic headers would be filled in automatically by LWP. For a POST or PUT request, you might want to specify a custom HTTP::Headers object for the request, or use the contents of a file for an entity body. Since HTTP::Request inherits everything in HTTP::Message, you can use the header and entity body manipulation methods from HTTP::Message in HTTP::Request objects.The constructor for HTTP::Request looks like this:
$req = http::Request->new (method, url, [$header
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The HTML Modules
- InhaltsvorschauHTML modules provide an interface to parse HTML documents. After you parse the document, you can print or display it according to the markup tags or extract specific information such as hyperlinks.The HTML::parser module provides methods for, literally, parsing HTML. It can handle HTML text from a string or file and can separate out the syntactic structures and data. You shouldn't use HTML::Parser directly, however, since its interface hasn't been designed to make your life easy when you parse HTML. It's merely a base class from which you can build your own parser to deal with HTML in any way you want. And if you don't want to roll your own HTML parser or parser class, then there's always HTML::TokeParser and HTML::TreeBuilder, both of which are covered in this chapter.HTML::TreeBuilder is a class that parses HTML into a syntax tree. In a syntax tree, each element of the HTML, such as container elements with beginning and end tags, is stored relative to other elements. This preserves the nested structure and behavior of HTML and its hierarchy.A syntax tree of the TreeBuilder class is formed of connected nodes that represent each element of the HTML document. These nodes are saved as objects from the HTML::Element class. An HTML::Element object stores all the information from an HTML tag: the start tag, end tag, attributes, plain text, and pointers to any nested elements.The remaining classes of the HTML modules use the syntax trees and its nodes of element objects to output useful information from the HTML documents. The format classes, such as HTML::FormatText and HTML::FormatPS, allow you to produce text and PostScript from HTML. The HTML::LinkExtor class extracts all of the links from a document. Additional modules provide means for replacing HTML character entities and implementing HTML tags as subroutines.This module implements the base class for the other HTML modules. A parser object is created with the
newconstructor:$p = HTML::Parser->new( );
The constructor takes no arguments.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - The URI Module
- InhaltsvorschauThe URI module contains functions and modules to specify and convert URIs. (URLs are a type of URI.) In addition to the URL module itself, there are also: URI::URL, URI::Escape, and URI::Heuristic. Of primary importance to many LWP applications is the URI::URL class, which creates the objects used by LWP::UserAgent to determine protocols, server locations, and resource names.The URI::Escape module replaces unsafe characters in URL strings with their appropriate escape sequences. URI::Heuristic provides convenience methods for creating proper URLs out of short strings and incomplete addresses.The URI module is a successor to URI::URL and was written by Gisle Aas. While not clearly stated in the LWP documentation, you should use the URI module whenever possible, since URI.pm has essentially deprecated URI::URL.The URI module implements the URI class. Objects created from the URI class represent Uniform Resource Identifiers (URIs). With the URI module, you can identify the key parts of a URI: scheme, scheme-specific parts, and fragment identifiers, which may be referred to respectfully as authority, path, and query components. For example, as shown in the URI module documentation:
<scheme>:<scheme-specific-part>#<fragment> <scheme>://<authority><path>?<query>#<fragment> <path>?<query>#<fragment>
You can break down http://www.oreilly.com/somefile.html as:scheme: http authority: www.oreilly.com path: /somefile.html
In the case of relative URIs, you can use the URI module to deal with only the query component of a URI. With the URI module, you can parse the above URI as follows:#!/usr/local/bin/perl -w use URI; my $url = 'http://www.oreilly.com/somefile.html'; my $u1 = URI->new($url); print "scheme: ", $u1->scheme, "\n"; print "authority: ", $u1->authority, "\n"; print "path: ", $u1->path, "\n";
Section 20.5.1.1: URI methods
The following methods give you access to components of a URI. These methods will return a string, unless the URI component is invalid, in which caseEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 21: Perl/Tk
- InhaltsvorschauPerl/Tk is an extension for writing Perl programs with a graphical user interface (GUI) on both Unix and Windows 95/NT. Tk was originally developed as an extension to the Tcl language, for use with the X Window System on Unix. With its port to Perl, Tk gives Perl programmers the same control over the graphical desktop that Tcl programmers have taken for granted .The Tk extension makes it easy to draw a window, put widgets into it (such as buttons, checkboxes, entry fields, menus, etc.), and have them perform certain actions based on user input. A simple "Hello World" program would look like this:
#!/usr/bin/perl -w use Tk; my $mw = MainWindow->new; $mw->Button(-text => "Hello World!", -command =>sub{exit})->pack; MainLoop;When you run it, it would look like Figure 21-1.
Figure 21-1: A simple Perl/Tk programClicking on the Hello World button exits the program, and your window disappears.Let's walk through these few lines of code. After calling the Perl interpreter, the program calls the Tk module. It then proceeds to build a generic, standard window (MainWindow) to act as a parent for any other widgets you create. Line 4 of the program creates a button and displays it using thepackgeometry manager. It also gives the button something to do when pushed (in this case, exit the program).The last line tells the program to "go do it."MainLoopstarts the event handler for the graphical interface, and the program draws windows until it reaches theMainLoopstatement. Everything up to that point is preparation; until you reach theMainLoopstatement, the program simply prepares its windows and defines what to do when certain events happen (such as a mouse click on the Hello World! button). Nothing is drawn until theMainLoopstatement is reached.Widgets in Perl/Tk are created with widget creation commands, which includeButton,Canvas,CheckButton,Entry,Frame,Label,Listbox,Menu,Menubutton,Message,Radiobutton,Scale,Scrollbar,Text, andToplevel, among many, many others.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Widgets
- InhaltsvorschauWidgets in Perl/Tk are created with widget creation commands, which include
Button,Canvas,CheckButton,Entry,Frame,Label,Listbox,Menu,Menubutton,Message,Radiobutton,Scale,Scrollbar,Text, andToplevel, among many, many others.Positioning widgets is done with geometry managers. In the "Hello World" example shown earlier, thepackcommand is the geometry manager. Geometry managers determine where in the window (or frame) the widget will sit. We'll talk more about the Perl/Tk geometry managers later in this chapter.Widgets can be configured, queried, or manipulated via various widget methods. For example, all widgets support theconfigurewidget method for changing widget properties after the widget is created. In addition, most widgets have specialized methods associated with them for manipulating the widget as needed throughout the program. For example, widgets that scroll support thexviewandyviewmethods for determining the viewable portion of the content when the scrollbar is moved. The Entry and Text widgets have methods for inserting and deleting values. The Canvas widget has a whole series of methods for drawing shapes and inserting text into the canvas. And so on.Widget methods are listed in the discussion of each widget later in this chapter. However, since all widgets support theconfigureandcgetmethods, we will cover them now.Section 21.1.1.1: The configure method
Theconfiguremethod can be used to set and retrieve widget configuration values. For example, to change the width of a button:$button->configure(-width => 100);
To get the value for a current widget, just supply it without a value:$button->configure(-width);
The result is an array of scalars; the important values are the last two, which represent the default value and its current value, respectively.You can also callconfigurewithout any options at all, which will give you a listing of all options and their values.Section 21.1.1.2: The cget method
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Geometry Managers
- InhaltsvorschauCreating widgets and determining how to display them are done with separate commands. You can create a widget with one of the widget creation methods (such as
Button,Canvas, etc.), but you display them using a geometry manager. The three geometry managers arepack,grid,place, andform.packis by far the most commonly used.You can either pack a widget as you create it or create the widget object and pack it separately. For example, the previous "Hello World" example might have read:#!/usr/bin/perl -w use Tk; my $mw = MainWindow->new; $button = $mw->Button(-text => "Hello World!", -command =>sub{exit}); $button->pack; MainLoop;With thepackgeometry manager, widgets cannot overlap or cover each other, either partially or completely. Once a widget is packed into a window, the next widget is packed in the remaining space around it.packsets up an "allocation rectangle" for each widget, determined by the dimensions of the parent window and the positioning of the widgets already packed into it. This means that the order in which you pack your widgets is very important.By default,packplaces widgets at the top center of the allocation rectangle. However, you can use options topackto control where a widget is placed and how much padding is placed around it. Options forpackare:-
-side =>side - Puts the widget against the specified side of the window. Values for side are
left,right,top, andbottom. The default istop. -
-fill =>direction - Causes the widget to fill the allocation rectangle in the specified direction. Values for direction are
none,x,y, andboth. The default isnone. -
-expand =>boolean - Causes the allocation rectangle to fill the remaining space available in the window. Values are
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Common Widget Configuration Options
- InhaltsvorschauIn the remainder of this chapter, we'll discuss each widget, the commands used to create each widget, the options used to configure them, and the methods for manipulating them.You'll find that there are many, many configuration options shared by multiple widgets. We could list them individually for each widget, but in the interest of saving a tree or two, we will instead list the shared options up front rather than repeating them over and over. That way, we can concentrate on the options that are crucial to the behavior of each particular widget and save the reader from being lost in a sea of options.The following options are supported by the widgets noted:
-
-activebackground =>color - Sets the background color when the mouse cursor is over the widget. Applicable widgets: Button, Checkbutton, Menu, Menubutton, Optionmenu, Radiobutton, Scale, Scrollbar.
-
-activeborderwidth =>borderwidth - Sets a 3-D border around active elements. Applicable widgets: Menu, Menubutton, Optionmenu.
-
-activeforeground =>color - Sets the text color when the mouse cursor is over the widget. Applicable widgets: Button, Checkbutton, Menu, Menubutton, Optionmenu, Radiobutton.
-
-anchor =>position - Causes the text to stick to that position in the widget. Values for position are
n,ne,e,se,s,sw,w,nw, andcenter. Applicable widgets: Button, Checkbutton, Label, Menubutton, Optionmenu, Radiobutton. -
-background =>color -
-bg =>color - Sets the background of the widget to the specified color. Applicable widgets: Button, Canvas, Checkbutton, Entry, Frame, Label, Listbox, Menu, Menubutton, Optionmenu, Radiobutton, Scale, Scrollbar, Text, Toplevel.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Button Widget
- InhaltsvorschauCreate a simple button with the
Buttonmethod:$parentwidget->Button (options)The standard configuration options that apply toButtonare:-activebackground,-activeforeground,-anchor,-background,-bg,-bitmap,-borderwidth,-bd,-cursor,-default,-disabledforeground,-font,-foreground,-fg,-height,-highlight-background,-highlightcolor,-highlightthickness,-image,-justify,-padx,-pady,-relief,-state,-takefocus,-underline,-width, and-wraplength.Other options are:-
-command =>callback - Pointer to a function that will be called when the button is pressed.
-
-text =>'text' - Defines the text string displayed on the button. See also
-textvariable. -
-textvariable =>\$variable - Points to the variable containing text to be displayed in the button. Button text will change as
$variable does.
In addition toconfigureandcget, the following methods can be used forButton:-
flash - Causes the button to flash from the normal to active state colors.
-
invoke - Invokes the callback command as if the button was clicked.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Checkbutton Widget
- InhaltsvorschauCreate a checkbutton with the
Checkbuttoncommand. A checkbutton has an indicator to the left of the label indicating whether the button is selected. The boolean status of the button (0,1, or values as specified by the-onvalueand-offvalueoptions) is stored in the variable specified with the-variableoption.$parentwidget->Checkbutton (options)The standard configuration options that apply toCheckbuttonare:-activeback-ground,-activeforeground,-anchor,-background,-bg,-bitmap,-borderwidth,-bd,-cursor,-disabledforeground,-font,-foreground,-fg,-height,-highlight-background,-highlightcolor,-highlightthickness,-image,-justify,-padx,-pady,-relief,-state,-takefocus,-underline,-width, and-wraplength.Other options are:-
-command =>callback - Pointer to a function that will be called when the checkbutton is pressed.
-
-indicatoron =>boolean - Determines whether to display the indicator. Default is on (
1). -
-offvalue =>newvalue - Specifies the value used when the checkbutton is off. Must be a scalar. Default is
0. -
-onvalue =>newvalue - Specifies the value used when the checkbutton is on. Must be a scalar. Default is
1. -
-selectcolor =>color - Color of the indicator when the checkbutton is on.
-
-selectimage =>imgptr - Defines the image to be displayed instead of text when the checkbutton is on. Ignored if
-imageis not used. -
-text =>'text' - Defines the text string displayed in the checkbutton. See also
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Radiobutton Widget
- InhaltsvorschauCreate a radiobutton with the
Radiobuttonmethod. A radiobutton has an indicator to the left of the label indicating whether the button is selected. It differs from a checkbutton in that only one button may be selected at a time. Each button in a group of radiobuttons uses the same variable specified with the-variableoption; when selected, the button assigns that variable the value specified by the-valueoption.$parentwidget->Radiobutton (options)The standard configuration options that apply toRadiobuttonare:-activeback-ground,-activeforeground,-anchor,-background,-bg,-bitmap,-borderwidth,-bd,-cursor,-disabledforeground,-font,-foreground,-fg,-height,-highlight-background,-highlightcolor,-highlightthickness,-image,-justify,-padx,-pady,-relief,-state,-underline,-width, and-wraplength.Other options are:-
-command =>callback - Pointer to a function that will be called when the radiobutton is pressed.
-
-indicatoron =>boolean - Determines whether to display the indicator. Default is on (
1). -
-selectcolor =>color - Color of the indicator when the radiobutton is on.
-
-selectimage =>imgptr - Defines the image to be displayed instead of text when the radiobutton is on. Ignored if
-imageis not used. -
-text =>'text' - Defines the text string displayed in the radiobutton. See also
-textvariable. -
-textvariable =>\$variable - Points to the variable containing text to be displayed in the radiobutton. Button text will change as
$
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Label Widget
- InhaltsvorschauCreate a noninteractive label with the
Labelcommand. A label is used to display text or an image.$parentwidget->Label (options)The standard configuration options that apply toLabelare:-anchor,-background,-bg,-bitmap,-borderwidth,-bd,-cursor,-font,-foreground,-fg,-height,-high-lightbackground,-highlightcolor,-highlightthickness,-image,-justify,-padx,-pady,-relief,-takefocus,-underline,-width, and-wraplength.Other options are:-
-text =>'text' - Defines the text string displayed in the label. See also
-textvariable. -
-textvariable =>\$variable - Points to the variable containing text to be displayed in the label. Button text will change as
$variable does.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Entry Widget
- InhaltsvorschauCreate an Entry widget with the
Entrymethod. An entry widget is a space for the user to enter text. The value that the user has typed into the widget is stored in the variable pointed to by the-textvariableoption.$parent->Entry (options)The standard configuration options that apply toEntryare:-background,-bg,-borderwidth,-bd,-cursor,-exportselection,-font,-foreground,-fg,-high-lightbackground,-highlightcolor,-highlightthickness,-insertbackground,-in-sertborderwidth,-insertofftime,-insertontime,-insertwidth,-justify,-relief,-selectbackground,-selectborderwidth,-selectforeground,-state,-takefocus, and-xscrollcommand.Other options are:-
-show =>x - Defines a character to be displayed in place of actual typed text (for use with passwords).
-
-textvariable =>\$variable - Points to the variable containing text to be displayed in the Entry widget. Button text will change as
$variable does.
In an Entry widget, several indexes are defined to identify positions in the entry text. These are used by the methods that retrieve and manipulate entry text.- n
- An integer representing a character position, with
0as the first character in the string. -
insert - The character directly after the insert cursor.
-
sel.first - The first character in the selection block.
-
sel.last - The character after the last character in the selection block.
-
anchor - The anchored position.
-
end - The position just after the last character in the entry string.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Scrollbar Widget
- InhaltsvorschauCreate a scrollbar with the
Scrollbarmethod:$parentwidget->Scrollbar (options)The standard configuration options that apply toScrollbarare:-ac-tivebackground,-background,-bg,-borderwidth,-bd,-cursor,-highlightback-ground,-highlightcolor,-highlightthickness,-relief,-takefocus, and-width.Other options are:-
-activerelief =>type - Changes how active elements (
arrow1,arrow2, andslider) in the scrollbar are drawn. Values for type areflat,groove,raised,ridge, andsunken. The default israised. -
-command =>callback - Pointer to a function that will be called when the scrollbar is clicked on.
-
-elementborderwidth =>amount - The width of the borders of the
arrow1,arrow2, andsliderelements. -
-jump =>boolean - Determines whether the scrollbar will jump scroll. Default is
0(jump scroll disabled). -
-orient =>orientation - Determines the orientation of the scrollbar. Possible orientations are
horizontalandvertical(default). -
-repeatdelay =>milliseconds - Determines the number of milliseconds to hold down an arrow before it will auto-repeat. Default is
300. -
-repeatinterval =>milliseconds - Determines the number of milliseconds between auto-repeats once it is started. Default is
100. -
-troughcolor =>color - Changes the color of the trough.
In addition toconfigureandcget, the following methods are supported by the Scrollbar widget:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Listbox Widget
- InhaltsvorschauCreate a listbox with the
Listboxmethod. You can then insert items into the listbox using theinsertmethod.$parentwidget->Listbox (options)The standard configuration options that apply toListboxare:-background,-bg,-borderwidth,-bd,-cursor,-exportselection,-font,-foreground,-fg,-height,-highlightbackground,-highlightcolor,-highlightthickness,-relief,-select-background,-selectborderwidth,-selectforeground,-takefocus,-width,-xscroll-command, and-yscrollcommand.Other options are:-
-selectmode =>mode - Determines the number of items that can be selected at once, as well as key/mouse bindings. mode can be any of:
-
single - Only one item can be selected at a time.
-
browse - Only one item can be selected at a time (default).
-
multiple - Multiple items can be selected at a time.
-
extended - Multiple items can be selected at a time.
-
-
-setgrid =>boolean - Turns on gridding for the listbox. If the widget is resized, only complete lines and characters are displayed. Default is
0(off).
In a Listbox widget, several indexes are defined to identify positions in the listbox. These are used by the methods that retrieve and manipulate listbox entries.- n
- An integer representing a position in the list, with
0as the first item. -
active - The item with the keyboard focus.
-
anchor - The anchored position.
-
end - The last element in the listbox.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Text Widget
- InhaltsvorschauCreate a Text widget with the
Textmethod:$parentwidget->Text ( options)The standard configuration options that apply toTextare:-background,-bg,-bor-derwidth,-bd,-cursor,-exportselection,-font,-foreground,-fg,-height,-high-lightbackground,-highlightcolor,-highlightthickness,-insertbackground,-in-sertborderwidth,-insertofftime,-insertontime,-insertwidth,-padx,-pady,-re-lief,-selectbackground,-selectborderwidth,-selectforeground,-state,-takefo-cus,-width,-xscrollcommand, and-yscrollcommand.Other options are:-
-setgrid =>boolean - Turns on gridding for the Text widget. Default is
0(off). -
-spacing1 =>amount - Defines the amount of space left on the top of a line of text that starts on its own line. Default is
0. -
-spacing2 =>amount - Defines the amount of space left on the top of a line of text after it has been automatically wrapped by the Text widget. Default is
0. -
-spacing3 =>amount - Defines the amount of space left after a line of text that has been ended by
\n. Default is0. -
-tabs =>list - Specifies a list of tab stops to use in the text widget. Default is undefined (no tab stops).
-
-wrap =>mode - Sets the mode for determining automatic line wrapping. Values are
none(no wrapping),char(wrap at any character), orword(wrap at a word boundary). Default ischar.
In a Text widget, several indexes are defined to identify positions in the text. These are used by the methods that retrieve and manipulate text.- n.m
- Numbers representing character m on line n
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Canvas Widget
- InhaltsvorschauCreate a canvas for drawing with the
Canvasmethod. The Canvas widget uses a coordinate system with the x coordinate increasing as you move right, and the y coordinate increasing as you move down (i.e., the y coordinate is mathematically upside-down). The x and y coordinates are specified in pixels by default.$parentwidget->Canvas (options)The standard configuration options that apply toCanvasare:-background,-bor-derwidth,-cursor,-height,-highlightbackground,-highlightcolor,-highlight-thickness,-insertbackground,-insertborderwidth,-insertofftime,-inserton-time,-insertwidth,-relief,-selectbackground,-selectborderwidth,-selectfore-ground,-state,-takefocus,-width,-xscrollcommand, and-yscrollcommand.Other options are:-
-closeenough =>amount - The distance considered "close enough" to an item to be judged to be within it. Default is 1 pixel.
-
-confine =>boolean - Whether to limit the canvas to the scroll region. Default is
1. -
-scrollregion => [x, y, w, h ] - Sets the region that the user is allowed to scroll. The option is a list reference that conveniently corresponds to the return value of the
bboxmethod. -
-xscrollincrement =>amount - The distance to use for scrolling in the x direction.
-
-yscrollincrement =>amount - The distance to use for scrolling in the y direction.
To place graphic elements in a canvas, there are several item creation methods:-
createArc - Creates an arc contained within the given bounding box. For example, to create an oval bounded by the box from (0,0) to (40,100):
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Scale Widget
- InhaltsvorschauCreate a "slider" widget representing a numeric value with the
Scalemethod.$parent->Scale(options);The standard configuration options that apply toScaleare:-activebackground,-background,-bg,-borderwidth,-bw,-cursor,-font,-foreground,-fg,-highlight-background,-highlightcolor,-highlightthickness,-relief,-state,-takefocus, and-width.Other options are:-
-bigincrement =>amount - The amount to change the slider when using large increments. Default is
0, which means 1/10 of the scale. -
-command =>callback - Pointer to a function that will be called for every incremental change in the slider.
-
-digits =>amount - The number of digits to keep when converting from a number to a string.
-
-from =>n - Low end of the scale (default is
0). -
-label =>string - The string to use as a label for the slider.
-
-length =>amount - The length of the scale.
-
-orient =>direction - The orientation of the slider. Values can be either
vertical(default) orhorizontal. -
-repeatdelay =>milliseconds - Determines the number of milliseconds to hold down an arrow before it auto-repeats. Default is
300. -
-repeatinterval =>milliseconds - Determines the number of milliseconds between auto-repeats once it is started. Default is
100. -
-resolution =>
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Menubutton Widget
- InhaltsvorschauCreate a menubutton with the
Menubuttonmethod. For example:$mainwindow->Menubutton(-text => "File", -menuitems => [ [ command => "New", -command => \&newfile, -underline => 0 ], [ command => "Open", -command => \&openfile, -underline => 0 ], "-", [ command => "Save", -command => \&savefile, -underline => 0 ], [ command => "SaveAs", -command => \&saveasfile, -underline => 4 ] ] );The-menuitemsoption takes a list of lists describing the menu items. For each menu item, an embedded anonymous list describes the type of menu item, the label to use, and the action to take when it is selected along with any other options desired to configure the menu item. In this example, each of the menu items is thecommandtype, and we use the-commandoption for each item to point to the callback to execute when the menu item is selected. We also use the-underlineoption to enable the user to select a menu item using keystrokes. (\[quotedbl]- represents a separator between menu items.)In addition tocommand, other types of menus are:-
cascade - Embeds a cascade menu
-
checkbutton - Treats the menu item as a checkbutton
-
radiobutton - Treats the menu item as a radiobutton
You can configure both the menu itself and the individual menu items. The configuration options that apply toMenubuttonare:-activebackground,-active-foreground,-anchor,-background,-bg,-bitmap,-borderwidth,-bw,-cursor,-disa-bledforeground,-font,-foreground,-fg,-height,-highlightbackground,-high-lightcolor,-highlightthickness,-image,-justify,-padx,-pady,-relief,-state,-takefocus,Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Menu Widget
- InhaltsvorschauCreate a menu with the
Menumethod, to be displayed later with thepostmethod.$menu = $parent->Menu(options)The standard configuration options that apply toMenuare:-activebackground,-activeforeground,-background,-bg,-borderwidth,-bw,-cursor,-disabledfore-ground,-font,-foreground,-fg,-relief, and-takefocus.Other options are:-
-activeborderwidth =>amount - Sets the width of the edges for the active menu item.
-
-menuitems =>list - Specifies items to create in the menu as a list of lists.
-
-postcommand =>callback - The command to invoke before the menu is posted. For example, to update the state of the menu items.
-
-tearoff =>boolean - Whether to allow the menu to be "torn off." Default is
1. -
-selectcolor =>color - Color of the selection box for checkbuttons or radiobuttons.
Menus have indexes for manipulating individual menu items. They are:- n
- Menu item n, with 0 representing the first item
-
active - The current menu item
-
endorlast - The last menu item
-
none - No menu item
-
@n - The menu item closest to the y coordinate specified by n
- pattern
- The first menu item with text that matches the pattern
In addition toconfigureandcget, the following methods are defined for the Menu widget:Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Optionmenu Widget
- InhaltsvorschauUse the
Optionmenumethod to create an option menu, in which the selected item is the value displayed. For example:$mainwindow->OptionMenu(-textvariable => \$platform, -options => [ [ "UNIX", "unix" ], [ "Windows NT", "winnt" ], [ "Macintosh", "mac" ] ]) -> pack;The-optionsargument takes a list of menu items. If the descriptions of the menu items displayed are different from those of the values stored, the menu items are themselves written as two-item lists.The standard configuration options that apply toOptionmenuare:-activeback-ground,-activeforeground,-background,-bg,-bitmap,-borderwidth,-bw,-cursor,-disabledforeground,-font,-foreground,-fg,-highlightbackground,-highlight-color,-highlightthickness,-image,-justify,-relief,-state,-takefocus,-un-derline,-width, and-wraplength.Other options are:-
-command =>callback - The command to execute when a selection is made. Its arguments are the values of the
-textvariableand-variableoptions. -
-indicatoron =>boolean - Determines whether to display an indicator.
-
-menu =>$menu - Displays the menu associated with
$menu. -
-options =>list - Lists the menu options, as described above.
-
-tearoff =>boolean - Whether to allow the menu to be "torn off." Default is
1. -
-text =>string - Specifies the text to display as a label for the option menu.
-
-textvariable =>\$variable - Points to the variable containing text to be displayed in the option menu.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Frame Widget
- InhaltsvorschauCreate a frame for enclosing other widgets using the
Framemethod. For example:$parent->Frame( options )The standard configuration options that apply toFrameare:-background,-bg,-borderwidth,-bw,-cursor,-height,-highlightbackground,-highlightcolor,-highlightthickness,-relief,-takefocus, and-width.Other options are:-
-class =>name - The class associated with the frame.
-
-colormap =>\$window - Specifies another window to share the colormap with. You can point to another window or use the value
newto specify a new colormap. Default isundef. -
-label =>string - The string to use as a label for the frame.
-
-labelPack - Specifies options for the
packcommand. -
-labelVariable =>\$variable - Specifies a variable containing the text for the label.
-
-visual =>type n - For the X Window System, changes the depth of colors.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- The Toplevel Widget
- InhaltsvorschauCreate a toplevel widget, displayed independently from the main window with the same decoration as the window system, using the
Toplevelmethod.The standard configuration options that apply toToplevelare:-background,-bg,-borderwidth,-bw,-cursor,-height,-highlightbackground,-highlightcolor,-highlightthickness,-relief,-takefocus, and-width.Other options are:-
-class =>name - The class associated with the Toplevel widget.
-
-colormap =>\$window - Specifies another window to share the colormap with. You can point to another window or use the value
newto specify a new colormap. Default isundef. -
-screen =>screen - The screen to place the toplevel widget on.
-
-visual =>type n - For the X Window System, changes the depth of colors.
In addition tocgetandconfigure, the following methods are supported by the Toplevel widget. Note that since the MainWindow is a Toplevel widget, each of these methods applies to the MainWindow as well.-
aspect - Returns the constraints to the aspect of the window. The four-item list returned corresponds to the minimum width, the minimum height, the maximum width, and the maximum height.
-
client - Assigns a name to the toplevel window.
-
colormapwindows - For the X Window System, passes a list of windows to the window manager that have private colormaps. Controls the WM_COLORMAP_WINDOWS property.
-
command - For the X Window System, returns the command used to start the application.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Chapter 22: Win32 Modules and Extensions
- InhaltsvorschauIf you use Perl on a Win32 system, a number of extension modules are available to provide Windows-specific functionality. Extension modules consist of a regular module written in Perl and a library written in C or C++ that can implement native Windows calls. The core of available modules is bundled together as lib-win32 on CPAN, and with ActivePerl, Activestate's version of Perl for Win32. They provide such functionality as managing Windows processes, NT user administration, registry modification, and OLE automation.The Win32 modules were originally written for Windows NT systems, so much of the functionality of the Win32 library is applicable only to Perl running on Windows NT. Many modules check to see which system they are on before installing. Many of the NT-specific modules such as NetAdmin and EventLog do not install at all on Windows 95. Modules such as Registry do their best to work on both systems, despite the differences in their registries.This chapter covers most of the modules and extensions included in lib-win32 and distributed with ActivePerl. Additional Windows modules are available at CPAN.The following modules are described in this chapter:
- Win32::Clipboard
- Provides Windows clipboard interaction
- Win32::Console
- Provides Windows console interaction
- Win32::ChangeNotify
- Creates and uses ChangeNotify objects
- Win32::EventLog
- Reads from and writes to the Windows NT event log
- Win32::File
- Manages file attributes (read-only, system, hidden, etc.)
- Win32::FileSecurity
- Manages ACLs in Perl
- Win32::Internet
- Provides extensions for Internet services
- Win32::IPC
- Waits for objects (processes, mutexes, semaphores)
- Win32::Mutex
- Creates and uses mutexes
- Win32::NetAdmin
- Administers users and groups
- Win32::NetResource
- Manages resources (servers, file shares, printers)
- Win32::PerfLib
- Accesses the Windows NT Performance Counter
- Win32::Pipe
- Creates a named pipe under Win32
- Win32::Process
- Starts and stops Win32 processes
- Win32::Registry
- Reads and manages the Win32 Registry
- Win32::Semaphore
- Creates and uses semaphores
- Win32::Service
- Manages Windows NT services
- Win32::Shortcut
- Provides shell link interface
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Clipboard
- InhaltsvorschauThe Win32::Clipboard module allows you to manipulate the Windows clipboard. You can use the clipboard as an object with the following syntax:
$clip = Win32::Clipboard( );
This functions as an implicit constructor. If you include a text string as an argument, that text will be placed on the clipboard. You can use the package-qualified method names instead of the object syntax, since the clipboard is a single entity:$text = Win32::Clipboard::Get( ); Win32::Clipboard::Set("blah blah blah"); Win32::Clipboard::Empty( );Alternatively, you can use the clipboard as an object with this syntax:$Clip = Win32::Clipboard( ); $text = $Clip->Get( ); $Clip->Set("blah blah blah"); $Clip->Empty( );Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Console
- InhaltsvorschauWin32::Console implements the Win32 console and character mode functions. They give you full control on the console input and output, including support of offscreen console buffers (e.g., multiple screen pages); reading and writing of characters, attributes, and whole portions of the screen; and complete processing of keyboard and mouse events.The
newconstructor is used to create a console object. It can take two forms:$con = Win32::Console->new(standard_handle); $con = Win32::Console->new(accessmode, sharemode);
The first form creates a handle to a standard channel. standard_handle can be one ofSTD_OUTPUT_HANDLE,STD_ERROR_HANDLE, orSTD_INPUT_HANDLE.The second form creates a console screen buffer in memory, which you can access for reading and writing as a normal console, and then redirect on the standard output (the screen) withDisplay. In this case, you can specify accessmode to beGENERIC_READ,GENERIC_WRITE, or both, determining the permissions you will have on the created buffer.sharemode affects how the console can be shared. It can be specified as eitherFILE_SHARE_READ,FILE_SHARE_WRITE, or both. If you don't specify any of those parameters, all four flags will be used.The following methods are supported by the Win32::Console module.Alloc$cons->AllocAllocates a new console for the process. Returnsundefon error or a nonzero value on success. A process cannot be associated with more than one console, so this method will fail if there is already an allocated console. UseFreeto detach the process from the console, and then callAllocto create a new console.Attr$cons->Attr([attr])Gets or sets the current console attribute. This attribute is used by theWritemethod.Cls$cons->Cls([attr])Clears the console with the specified attr, if given. UsesATTR_NORMALotherwise.Cursor$cons->Cursor([x, y, size, visible])Gets or sets cursor position and appearance. ReturnsEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::ChangeNotify
- InhaltsvorschauThis module provides access to Win32 change-notification objects, letting you monitor events relating to files and directory trees. The constructor for this class is
new, which creates a ChangeNotify object for a specified path and indicates how it should be monitored:$ntfy = Win32::ChangeNotify->new(path, subtree, events); $ntfy->wait or warn "Something has failed: $!");
The function returns a reference to the object as$ntfy. path is the pathname of the directory to monitor. subtree is a Boolean value that, if true, forces the object to monitor all subdirectories of the object's path. The eventsparameter indicates the type of events that will trigger a notification. It can be one of the following string values:ValueDescriptionATTRIBUTESAny attribute changeDIR_NAMEAny directory name changeFILE_NAMEAny filename change (creating/deleting/renaming)LAST_WRITEAny change to a file's last write timeSECURITYAny security descriptor changeSIZEAny change in a file's sizeThe following methods are used on notification objects created bynew.close$ntfy->close( )Stops the monitoring done by the notification object and destroys the object. This happens automatically when the program exits.reset$ntfy->reset( )Resets the object to begin monitoring again after a change has occurred.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Eventlog
- InhaltsvorschauThis module makes the Windows NT event log accessible to your Perl programs. It allows you to create new records, read records, and create backup logfiles. The
newconstructor opens a server's event log as an object:$log = Win32::EventLog->new(source, [server]);
This function opens an event log and returns an object reference. source specifies the name of the source event, and server specifies the name of the server (localis assumed if no server name is given).Many of the methods for this module require a reference to an empty variable as an argument. This is how the return value of the method will be placed, whether it is a hash or a scalar. The following methods can be used on event log objects.Backup$log->Backup(filename)Saves the current open event log to a file named by filename.Clear$log->Clear([filename])Writes the current event log to the file filename (if supplied) and clears the event log.GetNumber$log->GetNumber(\$number)Returns the number of events as the value of the scalar variable number.GetOldest$log->GetOldest(\$record)Returns the record number of the oldest record in the event log to the scalar$record.Read$log->Read(flags, offset, \%eventinfo)Reads an entry from the event log and returns the information in the eventinfo hash. offset specifies the record number you want to start at in the log. flags sets options for how you want to read the log, which can be any combination of the following:-
EVENTLOG_FORWARDS_READ - Eventlog is read in forward chronological order.
-
EVENTLOG_BACKWARDS_READ - Eventlog is read in reverse chronological order.
-
EVENTLOG_SEEK_READ - The read begins at the record specified by the
$RecordOffsetparameter. Must also specifyEVENT_LOG_FORWARDS_READorEVENTLOG_BACKWARDS_READ.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Win32::File
- InhaltsvorschauThe Win32::File module allows you to view or set the attributes for files. There are two functions that allow you to do this, which must be explicitly imported to your namespace:
use Win32::File qw/GetAttributes SetAttributes/;
The constant values for the attributes are exported by default.GetAttributesGetAttributes (filename, \$atts)Returns the attribute settings for file filename and saves them as the variable referenced by$atts, which will contain an ORed combination of one or more of the following values:ARCHIVE DIRECTORY HIDDEN NORMAL READONLY SYSTEM
SetAttributesSetAttributes (filename, atts)Sets the attributes for the file filename to the values contained in atts. The attributes are given as an ORed combination of one or more of the attribute values shown above.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::FileSecurity
- InhaltsvorschauThe Win32::FileSecurity module allows you to work with NT File System (NTFS) file permissions. File permissions are stored as Discretionary Access Control Lists (DACLs) for each file or directory. These lists contain a bitmask specifying the permission rights for users on the file or directory. This module implements a DACL as a permissions hash in which each key is a username, and the value is the bitmask for the permissions.The FileSecurity module exports the following constants to describe user permissions:
ACCESS_SYSTEM_SECURITY READ or R CHANGE or C SPECIFIC_RIGHTS_ALL DELETE STANDARD_RIGHTS_ALL FULL or F STANDARD_RIGHTS_EXECUTE GENERIC_ALL STANDARD_RIGHTS_READ GENERIC_EXECUTE STANDARD_RIGHTS_REQUIRED GENERIC_READ STANDARD_RIGHTS_WRITE GENERIC_WRITE SYNCHRONIZE MAXIMUM_ALLOWED WRITE_DAC READ_CONTROL WRITE_OWNER
Using theconstantfunction on one of these constants gives its value, and bitmasks or multiple permissions settings can be made by supplying a list of these constants to theMakeMaskfunction.The following functions are exported by the Win32::FileSecurity module.constantconstant (name $val)Takes the name of a permission constant and saves its value in the variable val.EnumerateRightsEnumerateRights (mask, \@rights)Takes a permissions bitmask (as returned byMakeMaskorconstant) and saves the corresponding list of string constants in rights.GetGet (filename, \%permissions)Gets the access control list for filename (or directory) and saves in the specified permissions hash.MakeMaskMakeMask (stringlist)Takes a list of permission string constants and returns the bitmask.SetSet (filename, \%permissions)Sets the access control list for the given filename (or directory) to the settings in the specified permissionshash.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Internet
- InhaltsvorschauThe Win32::Internet extension implements the Win32 Internet APIs (found in WININET.DLL), providing support for HTTP, FTP, and Gopher connections.All types of connections start as a basic Internet connection that must be opened with the following command:
use Win32::Internet; $Connection = Win32::Internet->new( );
This creates an Internet object in Perl on which you use the functions provided in this module to create more specific connection objects. The objects and functions that create them are:- Internet connections (the main object, with
new) - URLs (with
OpenURL) - FTP sessions (with
FTP) - HTTP sessions (with
HTTP) - HTTP requests (with
OpenRequest)
This module provides different levels of implementation of the Win32 Internet functions. Some routines use several Win32 API functions to perform a complex task in a single call; they are simpler to use, but less powerful. Other functions implement nothing more and nothing less than the corresponding API function, so you can use all of their power, but with some additional programming steps.For example, the functionFetchURLfetches the contents of any HTTP, FTP, or Gopher URL with a simple command:$inet = new Win32::Internet( ); $file = $inet->FetchURL("http://www.yahoo.com");You can achieve the same result with this series of commands, which is whatFetchURLactually does:$inet = new Win32::Internet( ); $url = $inet->OpenURL("http://www.yahoo.com"); $file = $url->ReadFile( ); $url->Close( );The methods described in this section are used on Internet connection objects created withnew:$inet = Win32::Internet->new( );
You can supplynewwith an optional list of arguments (or a reference to a hash containing them) that looks like this:Win32::Internet->new [useragent, opentype, proxy, proxybypass, flags] Win32::Internet->new [$hashref]
The parameters and their values are:- useragent
- The user agent string passed to HTTP requests. Default is
Perl-Win32Internet/version. - opentype
- How to access the Internet (e.g., directly or using a proxy). Default is
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::IPC
- InhaltsvorschauThe Win32::IPC module provides synchronization for multiple objects created from the Semaphore, Mutex, Process, and ChangeNotify classes. The
waitmethod of this class is inherited by objects of the preceding modules, as well as the functionswait_allandwait_any. You should not need to call Win32::IPC directly.wait$obj->wait([timeout])This method is used on any synchronization object. It waits for the object to become signaled. It returns1if the object is signaled,-1if the object is an abandoned mutex,0if the call times out, andundefon error. timeoutis the time to wait (in milliseconds). If no timeout is specified, the method waits indefinitely.Win32::IPC also defines the two functionswait_allandwait_any.wait_allwait_all(@objects, [timeout])Waits for all the synchronization objects contained in@objects to be signaled. The optional timeout parameter is the same as described forwait. The return value will be an integer that identifies the last object to be signaled (the nth object in the list, starting from 1). A negative integer (-n) indicates that the nth object was an abandoned mutex. A return of0means that the function timed out;undefis returned on error.wait_anywait_any(@objects, [timeout])Waits for at least one of the objects contained in @objects to be signaled. Return values are the same as forwait_all, above, indicating which object signaled.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Mutex
- InhaltsvorschauThis module provides access to Win32 mutex objects, which control access to common resources. The
newconstructor creates the mutex and determines its initial availability. It has the following syntax:$mut = Win32::Mutex->new(init, [name]);
The first argument determines the initial status of the mutex. If init is nonzero, the calling process has immediate ownership of the mutex object. A0value means that the mutex is available. The second argument assigns a name to the mutex that allows this object to be referenced by others via theopenfunction.Another object constructor for Win32::Mutex isopen:$mut = Win32::Mutex->open(name);This call creates a new mutex object to access an existing mutex identified by name.The following methods can be used on Win32::Mutex objects.release$mut->Release( )Releases ownership of the mutex from the calling process, allowing anyone waiting on the mutex to take ownership.wait$mut->wait([timeout])The Win32::IPC method inherited by this module. Makes the calling process wait for ownership of the mutex object for the number of milliseconds specified by timeout. If the mutex doesn't become available before the timeout, the call returns0.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::NetAdmin
- InhaltsvorschauThe Win32::NetAdmin module provides extensive functionality for administering users and groups on Windows NT servers. This module does not implement an object interface for administration; it exports several functions that execute administrative commands. (This module does not load on Windows 95 systems.)The following functions are provided by the Win32::NetAdmin module. The server argument of each function is optional; however, a placeholder for the argument must be used if you don't supply a name. An empty string ("") will work, indicating that the local machine should be used.GetDomainControllerGetDomainController (server, domain, $name)Returns the name of the domain controller for the specified serverand domain to the variable
$name.GroupAddUsersGroupAddUsers (server, name, users)Adds users to group name on server. userscan be a list of usernames or a list variable containing multiple usernames.GroupCreateGroupCreate (server, name, comment)Creates a group with the specified name on server. commentis a string used to provide a description about the group.GroupDeleteGroupDelete (server, name)Deletes a group named name from server.GroupDeleteUsersGroupDeleteUsers (server, name, users)Deletes a list of users from the group name on server.GroupGetAttributesGroupGetAttributes (server, name, comment)Returns the comment for group name on server to the variable comment.GroupGetMembersGroupGetMembers (server, name, $users)Returns the usernames that are members of group name on serverto the array referenced by users.GroupIsMemberGroupIsMember (server, name, user)Queries group name on server to see if user is a member. Returns true if user is a member, false if not.GroupSetAttributesGroupSetAttributes (server, name, comment)Sets the comment for group name on server to the string provided in comment.LocalGroupAddUsersLocalGroupAddUsers (server, name, users)Adds users to local group name on server. userscan be a list of usernames or a list variable containing multiple usernames.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::NetResource
- InhaltsvorschauThe Win32::NetResource module allows you to manage shared resources on a network, such as printers, disks, etc. Two data structures are used to provide or store information for many of the NetResource functions. The first is the
share_infohash. This hash contains parameters for setting up a share, using the following structure:%share_info = ( netname => "name of share", type => "type of share", remark => "a string comment", permissions => "permissions value", maxusers => "the max number of users", current-users => "the current number of users", path => "the path of the share", passwd => "password, if required" );Anetresourcedata structure contains information about the shared resource or device. It has the following structure:%netresource = ( 'Scope' => "Scope of a resource connection (see list below for values)", 'Type' => "The type of resource (see list below)", 'DisplayType' => "How the resource should be displayed (see list below)", 'Usage' => "How the resource should be used", 'LocalName' => "Name of the local device the resource is connected to", 'RemoteName' => "Network name of the resource", 'Comment' => "Comment string", 'Provider' => "Provider of the resource" );The first three elements of thenetresourcehash contain values described in the following lists. TheScopevalue can be one of the following:-
RESOURCE_CONNECTED - Resource is already connected
-
RESOURCE_REMEMBERED - Resource is reconnected each time the user logs on
-
RESOURCE_GLOBALNET - Resource is available to the entire network
TheTypeelement takes one of the following values:-
RESOURCETYPE_ANY - All resources
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Win32::PerfLib
- InhaltsvorschauThe Win32::PerfLib module allows you to retrieve the performance counter of any computer running Windows NT in the network. All of the functions return false if they fail, unless otherwise noted. If the
$serverargument isundef, the local machine is assumed.new$perflib->new($server)Creates a connection to the performance counters of the given server.Close$perflib->Close($hashref)Closes the connection to the performance counters.GetCounterHelpGetCounterHelp($server, $hashref)Retrieves the counter help strings and their indices from the registry and stores them in the hash reference.GetCounterNamesGetCounterNames($server, $hashref)Retrieves the counter names and their indices from the registry and stores them in the hash reference.GetCounterTypeGetCounterType(countertype)Converts the counter type to a readable string.GetObjectList$perflib->GetObjectList($objectid, $hashref)Retrieves the object and counter list of the given performance object.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Pipe
- InhaltsvorschauThis module gives Win32 Perl the ability to use named pipes. Under Windows NT, named pipes are used for processes to communicate with one another, and are not limited to the local machine.Named pipes are created with
new, which makes a new Win32::Pipe object and returns true on success.newhas the following syntax:my $named_pipe = Win32::Pipe->new($pipe_name);
The following methods are provided for objects of created by Win32::Pipe.BufferSize$named_pipe->BufferSize( )Returns the size of the instance of the buffer of the named pipe.Close$named_pipe->CloseCloses the named pipe.Connect$named_pipe->ConnectTells the named pipe to create an instance of the named pipe and wait until a client connects. Returns true on success, false on failure.Disconnect$named_pipe->DisconnectDisconnects (and destroys) the instance of the named pipe from the client. Returns true on success, false on failure.Error$named_pipe->ErrorReturns the last error messages pertaining to the named pipe, if used in context to the package. Returns a list containing ERROR_NUMBER and ERROR_TEXT.Read$named_pipe->ReadReads from the named pipe. Returns data read from the pipe on success,undefon failure.ResizeBuffer$named_pipe->ResizeBuffer(SIZE)Sets the size of the buffer of the instance of the named pipe to SIZE. Returns the size of the buffer on success, false on failure.Write$named_pipe->Write(DATA)Writes DATA to the named pipe. Returns true on success, false on failure.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Process
- InhaltsvorschauThis module provides access to extended Win32 process creation and management abilities. Process objects are created with the
Createmethod (the constructor). Additional methods can be used on objects to kill, suspend, resume, and set the priorities of processes.TheCreateconstructor has the following syntax:Win32::Process->Create($Proc, app, cmnd, hndls, opts, dir)
The arguments toCreateare as follows:-
$Proc - Name of the reference for the created process object.
- app
- Full pathname of the executable.
- cmnd
- Command line for executable.
- hndls
- Determines handle inheritance. A value of
1turns on inheritance; a0value turns it off. - opts
- Sets options to implement when the process is created. The available options for this argument are listed below.
- dir
- The working directory for the executable.
The process is created by passing the command line in cmnd to the executable named in app. For example, a process object for a text file running in Notepad is created like this:use Win32::Process; Win32::Process->Create($proc, 'C:\\windows\\Notepad.exe', "Notepad perlnut.txt", 1, DETACHED_PROCESS, ".");The process creation options given by the opts argument toCreateare:-
CREATE_DEFAULT_ERROR_MODE - Gives the process the default error mode.
-
CREATE_NEW_CONSOLE - Creates a new console for the process. Can't be used with
DETACHED_PROCESS. -
CREATE_NO_CONSOLE - Creates a new process, but without running the process in a new and visible window. That is, a new process will be created, but in the background.
-
CREATE_NEW_PROCESS_GROUP - Creates process as root of a new process group.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Win32::Registry
- InhaltsvorschauThis module provides access to the Windows Registry, the database that stores information about all parts of your system and software. Many operating-system and application behaviors are controlled by Registry data. The Win32::Registry module gives you a way to access and update registry information with Perl.Always be careful when making changes to the registry. If vital system information gets changed by mistake, your system could become inoperable. Always make certain you have a backup of your registry before you start making modifications.The Registry module automatically creates objects for the top-level registry trees. These objects are created in the
main:: namespace, and each key that you open or create is accessed via one of these root objects. The top-level objects are:$HKEY_CLASSES_ROOT $HKEY_CURRENT_USER $HKEY_LOCAL_MACHINE $HKEY_USERS $HKEY_PERFORMANCE_DATA $HKEY_CURRENT_CONFIG $HKEY_DYN_DATA
If you are outside of the main (default) namespace, you should package declare the keys, e.g.,$main::HKEY_USERS.TheOpenmethod creates new key objects for subtrees or subkeys under another open key object. Initially, a new key is opened from one of the main key objects. For example:use Win32::Registry; $p = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"; $HKEY_LOCAL_MACHINE->Open($p, $CurrVer) || die "Open $!";
This example creates a key object$CurrVerfor theCurrentVersionkey for Windows NT. This key contains several values for the current version of the operating system. With the new key open, you can read or change the values it contains (every key has at least one unnamed, default value), or open and create subkeys. TheOpenmethod can create key objects only for existing keys.Registry values are represented in Win32::Registry functions by three elements: the name of the value, the data type of the value, and the value itself. There are several different data types for the values. Win32::Registry defines the following constants for these types:-
REG_SZ - String data
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Win32::Semaphore
- InhaltsvorschauThe Win32::Semaphore module implements semaphores, synchronizing access to shared resources. The constructor
newcreates a new semaphore object and sets the initial count and the maximum count of the semaphore. The constructor has the following syntax:$sem = Win32::Semaphore->new(init, max, [name]);
The arguments are defined as follows:- init
- The initial count of the semaphore
- max
- The maximum count of the semaphore
- name
- A string containing a name of the semaphore
Theopenconstructor opens an existing semaphore object specified by name:$sem = Win32::Semaphore->open(name);The following methods can be used on Win32::Semaphore objects.release$sem->release(inc, [$var])Releases a semaphore and increments the count by the amount specified in inc. The last count (before the increment) is returned in the$var variable, if provided.wait$sem->wait([timeout])The inherited Win32::IPC call. Waits for the semaphore's count to be nonzero, then decrements it. Optional timeout is given in milliseconds.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Service
- InhaltsvorschauThe Win32::Service module provides a service control interface. It allows you to start, pause, resume, and stop Windows NT system services from Perl scripts.The following functions are exported by this module. The host argument in each function gives the hostname of the machine a service is running (or will run) on. If you supply a null string (""), the local machine will be assumed.GetServicesGetServices (host, \%hash)Returns a list of services on host to the hash referenced by hash.GetStatusGetStatus (host, service, \%status)Returns the status of service as a hash referenced by status. The keys for this hash are:
ServiceType CurrentState ControlsAccepted Win32ExitCode ServiceSpecificExitCode CheckPoint WaitHint
PauseServicePauseService (host, service)Pauses the named service on machine host (only if the service is able to pause).ResumeServiceResumeService (host, service)Resumes a paused service on host.StartServiceStartService (host, service)Starts the named service on the machine host. The specified service must be registered with the Service Control Manager.StopServiceStopService (host, service)Stops the named service on machine host.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::Shortcut
- InhaltsvorschauThis module allows you to create and manipulate Windows shortcut files (.lnk files) through Perl. The methods and properties of this module apply to shortcut objects created by
new:use Win32::Shortcut; $link = Win32::Shortcut->new( );
This creates the shortcut object$link, on which you can set properties and save into a file. If you supply a filename as an argument tonew, the file will be loaded into the shortcut object.The object can also be accessed as if it was a normal hash reference. The following properties (hash keys) are available:$link->{'File'} $link->{'Path'} $link->{'ShortPath'} $link->{'WorkingDirectory'} $link->{'Arguments'} $link->{'Description'} $link->{'ShowCmd'} $link->{'Hotkey'} $link->{'IconLocation'} $link->{'IconNumber'}See Section 22.18.1 for a description of each property.The following example assumes you have a shortcut file named test.lnk in your current directory. This simple script will tell you where this shortcut points to:use Win32::Shortcut; $link=new Win32::Shortcut( ); $link->Load("test.lnk"); print "Shortcut to: $link->{'Path'} $link->{'Arguments'} \n"; $link->Close( );But you can also modify its values:use Win32::Shortcut; $link=new Win32::Shortcut( ); $link->Load("test.lnk"); $link->{'Path'}=~s/C:/D:/i; # Move the target from C: to D: $link->{'ShowCmd'}=SW_NORMAL; # Runs in a normal windowThe methods provided by Win32::Shortcut are as follows.newnew Win32::Shortcut [file]Creates a new shortcut object. If a filename is passed in file, automaticallyLoads this file also. Returns the object created, orundefon error.Close$link->Close( )Closes a shortcut object. It is not strictly required to close the objects you created, since the Win32::Shortcut objects are automatically closed when the program ends (or when you otherwise destroy such an object).Also note that a shortcut is not automatically saved when it is closed, even if you modified it. You have to callSavein order to apply modifications to a shortcut file.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32 Extensions
- InhaltsvorschauIn addition to the modules listed previously, Perl for Win32 can use an additional set of functions from the Win32 extension. These functions provide useful tools for some Windows-specific tasks that don't require their own modules. They are exported from the Win32 package with:
use Win32;
Many of these functions do not take arguments and return the value (or values) of the requested information, unless otherwise noted.-
Win32::CopyFile(from,to,overwrite) - Copies an existing file to a new file, while preserving all attributes of the original file, except the security information. If to exists, overwriting will take place only if overwrite is true. Read-only files will never be overwritten; they will need to be
unlinked first. -
Win32::FreeLibrary(handle) - Unloads a previously loaded DLL. handle is no longer valid after
FreeLibrary( )is called. -
Win32::GetArchName( ) - Has been deprecated in favor of
$ENV{PROCESSOR_ARCHITECTURE}. -
Win32::GetChipName( ) - Returns the processor type of the machine under which the perl process is running. This string will be represented as 386, 486, 586, etc.
-
Win32::GetFullPathName(filename) - Combines filename with drive number and directory name. In a list context,
GetFulllPathName( )returns path and file. -
Win32::GetLastError( ) - Returns the last error value generated by a call to a Win32 API function.
-
Win32::GetLongPathName(pathname) - Returns
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- Chapter 23: OLE Automation
- InhaltsvorschauThe Win32::OLE modules give Perl support for OLE automation. OLE automation is a Microsoft technology based on COM that allows objects created by another application to be used and manipulated by a program through a common interface.The application (or DLL) that implements the automation interface is called the automation server. The application that creates and uses the interface is called the automation controller or automation client . Many popular applications expose their objects through automation. Microsoft Word, Excel, and other Office applications can be used as automation servers. Automation is widely used by Active Server Pages (ASP) and CGI scripts to access data repositories, perhaps via ActiveX Data Objects (ADO). You can even use automation to control many development environments and editors.To create an automation object, the server needs to be registered on the system. This is typically done by the server's installation program, but can be done manually using a utility such as regsvr32.exe. This involves adding entries to the system registry to tell COM how to find the component, the types of interfaces it provides, the type of server it is, etc. You should be able to find the object model, available methods, and properties of the interface in the documentation provided by the application. This object model can be used via Perl's object syntax to create and control objects in your programs.Four modules provide automation functionality to Perl:
- Win32::OLE
- Provides the main interface for OLE automation. You can create or open automation objects, use their methods, and set their properties.
- Win32::OLE::Enum
- Creates objects for collections and defines an interface for enumerating them.
- Win32::OLE::Variant
- Allows you to convert the Variant data type used in OLE.
- Win32::OLE::Const
- Imports constants from an automation object into your script.
Note that there are a few limitations to Win32::OLE. There is currently no support for OCXs or OLE events (notifications generated by the automation server). Win32::OLE implements theEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Creating Objects
- InhaltsvorschauAutomation objects are represented in Perl as instances of Win32::OLE objects. The module provides three constructors for creating objects from a registered automation server.newWin32::OLE->new(progid, [destructor])Creates a new automation object. This method always creates a new instance of the server, even if a previous instance of the server is running. If the object cannot be created,
newreturnsundef.progid, the program identifier (ProgID), is a string that uniquely identifies an automation object. progid is used to look up the object's class ID (CLSID), which is stored in the registry.The second, optional argument to thenewmethod describes a way to destroy the object in case the Perl program dies unexpectedly. destructor can be either a string with the name of the defined OLE destructor method, or a code reference that will destroy the object. You should use some form of destructor to close out all your objects, for they can be extremely expensive in terms of system resources. You can explicitly destroy an object using theundeffunction. If you don't explicitly destroy the object, Perl takes care of it for you when the last reference to the object goes away.Here is whatnewwould look like with the destructor arguments:# Quit is the OLE-defined destructor method $x1 = Win32::OLE->new("Excel.Application", 'Quit'); # The object reference is the first argument ($_[0]) passed to new # The code reference will undef it to destroy the object $x2 = Win32::OLE->new("Excel.Application", sub{undef $_[0];})Notice that we're supplying Excel.Application as the ProgID. Excel supports several different automation objects, including an Application object, WorkBook objects, and several more. You don't necessarily have to create the top-level object (Application, in this case) when dealing with automation objects (this is determined by the automation server). In Excel's case, we could have directly created a WorkSheet object (e.g., Excel.Sheet) or a Chart object, for example.GetActiveObjectWin32::OLE->GetActiveObject(Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Automation Methods and Properties
- InhaltsvorschauOnce you have created an automation object, you can use its methods or adjust its properties as you require. Automation methods are implemented as you'd expect with the Perl object syntax:
$obj->some_method(args);
Automation methods can often take a number of optional parameters. You can passundeffor any unwanted parameters in the arguments list. For example, you can save a WorkBook in Excel withSaveAs. Additional settings allow you to add the WorkBook to the MRU list and create a backup copy:$xl->WorkBooks(1)->SaveAs($f, undef, undef, undef, undef, 1, undef, undef, 1);
For simplification, you can also use just the named parameters you want to set by passing a reference to a hash containing them. You can do this right in the argument list by creating an anonymous hash reference with{}. The previous example can therefore be written like this:$xl->WorkBooks(1)->SaveAs($f, {AddtoMru => 1, CreateBackup => 1});Properties of automation objects are accessed via hash reference notation on the object. For example:$val = $obj->{"property"}; # Get a property value $obj->{"property"} = $val; # Set a property valueBe aware that properties may not be writable (or even readable). Many automation objects have read-only properties and will generate an exception if you try to write to them. You'll need to consult the documentation for the object to find out which properties you can safely set.You can enumerate the properties of an automation object using the normal methods for enumerating hashes, which arekeysandeach. Here's how you can print the properties and values contained within an object:$xl = Win32::OLE->new('Excel.Application', 'Quit'); while( ($key,$value) = each %$xl ) { print "$key=$value\n"; }Win32::OLE defines a couple of its own methods for dealing with the automation interface. These are not automation-defined methods, although they look the same. If a given method is not defined in Win32::OLE, the method call is dispatched to the automation object. If the method doesn't exist there, you will get an OLE error.The following methods are defined by Win32::OLE.Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::OLE::Enum
- InhaltsvorschauThe Win32::OLE::Enum module provides special support for collections. Collections are special automation data types that contain an array of objects or data. A collection supports enumeration; you can iterate through each item through a standard interface.Collection objects should always provide a
Countproperty (the number of items in the collection) and anItemmethod. TheItemmethod is used to access a particular collection item using a subscript, which may be an integer or a string, depending on the server. Collection objects may also optionally contain anAddand aRemovemethod.Collection objects also support a standard COM interface (IEnumVARIANT) that allows you to enumerate each item in a collection. It defines methods that let you advance the iteration to the next item, skip a given item, restart the enumeration, and create a new copy of the iterator. While all servers are supposed to provide this interface, some servers don't implement all of the methods (oftenResetandCloneare not implemented).Win32::OLE::Enum defines these methods for enumerating collections. The collection object should provide theCountandItemmethods, which are often all you need to use on collections. For example:$cnt = $coll->Count( ); if( $cnt) { $obj = $coll->Item(0); $obj->do_something( ); }Countwill tell you the number of items in the collection, andItemwill return the desired item as a Win32::OLE object.For the enumeration methods, you need to create an enumeration object for the collection object:$coll = $obj->some_coll( ); $enum = Win32::OLE::Enum->new($coll);
Now you can use the enumeration methods on the object.The following methods are defined in Win32::OLE::Enum.newWin32::OLE::Enum->new($obj)Creates a new Win32::OLE::Enum object. Provides it with a collection object or an existing Enum object, in which case it callsClone.All$Enum->All( )Returns a list of all objects in the collection. Note that to useEnde der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::OLE::Variant
- InhaltsvorschauAll automation data has to be coerced into a special type called a Variant. Most of the time, you don't need to worry about explicit type coercion. You just provide your scalar data, and the magic of automation takes care of the rest. However, there are times when you want to control the exact type of data you're sending to the automation server. The Win32::OLE::Variant module provides access to the Variant data type and lets you control exactly how the data is represented.A Variant is an OLE data structure that contains a type field and a data field. The flags are implemented in Perl (as are many constants) as subroutines that return an integer value. The following table lists the Variant type flags, along with a brief description of each:TypeDescription
VT_EMPTYNo value specified. Incidentally, automation does not useVT_EMPTYfor empty optional parameters. Rather, it uses VT_ERROR with a value ofDISP_E_PARAMNOTFOUND(which isn't exported by Perl: the value in current Win32 SDK headers is0x80020004).VT_NULLA propagatingNULLvalue was specified (not to be confused with a null pointer). This is used for things like the NULL in SQL.VT_I2A two-byte integer value.VT_I4A four-byte integer value.VT_R4Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Win32::OLE::Const
- InhaltsvorschauWhile browsing through the documentation for an automation object, you may have come across references to constant values. For example, if you're trying to save an Excel workbook to a different file format, you need to provide a file for- mat constant. Since the server documentation typically provides symbolic con- stants (e.g.,
xlExcel5orxlTemplate), we need a way to access those from Perl. This is the purpose of Win32::OLE::Const, which imports the constants from an automation object into your script.You can either import the constants directly into your namespace as subs that return the constant value, or you can have them returned as a hash reference with the constant name as the key and its value as the value. Here's an example of the former:use Win32::OLE::Const ("Microsoft Excel"); print "xlExcel5 = ", xlExcel5, "\n";This produces something like:xlExcel5 = 39
Here's an example using theLoadmethod to return a hash reference populated with the constants and their values (this produces the same output as the previ- ous example, of course):use Win32::OLE::Const; my $constants = Win32::OLE::Const->Load("Microsoft Excel"); print "xlExcel5 = $constants->{xlExcel5}\n";Notice that, in both cases, we're supplying a regular expression for the name of the type library from which we want to import.Win32::OLE::Constsearches the registry for matching type libraries and loads the one with the highest version number (you can override this by supplying the version you want). You can also specify the language you'd like. The parameters (for eitherLoadorWin32::OLE::Const) are the typelib regular expression, the major version number, the minor version number, and the locale (LCID).You can also provide theLoadmethod with an automation object, which is then queried for its type library. Interestingly, the documentation notes that this seems to be slower than searching the Registry (though neither is really speedy with a large automation server like Excel). Here's an example of that:use Win32::OLE; use Win32::OLE::Const; # Create an Excel application object my $xl = Win32::OLE->new('Excel.Application', 'Quit') || die "Can't create Excel: ", Win32::OLE->LastError; # Import the constants from it my $constants = Win32::OLE::Const->Load($xl);Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. - Chapter 24: ODBC Extension for Win32
- InhaltsvorschauWin32::ODBC allows you to make a connection to a database that supports ODBC under both Win32 and Unix. Win32::ODBC allows you to support as many ODBC connections as are allowed by memory and ODBC.Generally, you'll use Win32::ODBC to access databases such as those created under Microsoft Access, but there's also an ODBC driver available for MySQL if you want to connect to MySQL via ODBC and aren't able to use DBI and a DBD.To get started, you'll need to use
new( )to create a new Win32::ODBC object. As arguments,new( )takes a connection string (DSN) or an open ODBC object if one is given.new( )returns a database handle on success andundefon failure. For example:use Win32::ODBC; my $dsn = "DSN=Name of Database;UID=Your UID Here;PWD=dbpasswd;" my $DB = Win32::ODBC->new($dsn);
Once you have created an ODBC object, you can use its methods or adjust its properties as you require. ODBC methods are implemented as you'd expect with the Perl object syntax.The following methods are defined by Win32::ODBC.Catalog$obj->Catalog(qualifier, owner, name, type)Tells ODBC to create a data set that contains table information about the DSN. Use Fetch and Data or DataHash to retrieve the data. The returned format is:[qualifier] [owner] [name] [type]
Returns true on error.ColAttributesWin32::ODBC->ColAttributes(attributes, [field_names])Returns the attributes attributes on each of the fields in the list field_names in the current record set. If field_names is empty, then all fields are assumed. The attributes are returned as an associative array.ConfigDSNWin32::ODBC->ConfigDSN(option, driver, attribute1 [, attribute2, attribute3, ... ])Configures a DSN. option takes on one of the following values:-
ODBC_ADD_DSN - Adds a new DSN
-
ODBC_MODIFY_DSN - Modifies an existing DSN
-
ODBC_REMOVE_DSN - Removes an existing DSN
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
- ODBC Methods and Properties
- InhaltsvorschauOnce you have created an ODBC object, you can use its methods or adjust its properties as you require. ODBC methods are implemented as you'd expect with the Perl object syntax.The following methods are defined by Win32::ODBC.Catalog$obj->Catalog(qualifier, owner, name, type)Tells ODBC to create a data set that contains table information about the DSN. Use Fetch and Data or DataHash to retrieve the data. The returned format is:
[qualifier] [owner] [name] [type]
Returns true on error.ColAttributesWin32::ODBC->ColAttributes(attributes, [field_names])Returns the attributes attributes on each of the fields in the list field_names in the current record set. If field_names is empty, then all fields are assumed. The attributes are returned as an associative array.ConfigDSNWin32::ODBC->ConfigDSN(option, driver, attribute1 [, attribute2, attribute3, ... ])Configures a DSN. option takes on one of the following values:-
ODBC_ADD_DSN - Adds a new DSN
-
ODBC_MODIFY_DSN - Modifies an existing DSN
-
ODBC_REMOVE_DSN - Removes an existing DSN
-
ODBC_ADD_SYS_DSN - Adds a new System DSN
-
ODBC_MODIFY_SYS_DSN - Modifies an existing System DSN
-
ODBC_REMOVE_SYS_DSN - Removes an existing System DSN
driver is a required argument. attribute1 is the DSN, whose format is shown earlier.ConfigDSN( )returns true on success and false on failure.ConnectionWin32::ODBC->Connection( )Returns the connection number associated with the ODBC connection.CloseWin32::ODBC->Close( )Closes the ODBC connection. No return value.DataWin32::ODBC->Data([field_name])Returns the contents of column name field_name or the current row (if nothing is specified).Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar. -
Zurück zu Perl in a Nutshell
