File manager - Edit - /home/ferretapmx/public_html/pod.zip
Back
PK PU�\�x�t� t� perlfaq5.podnu �[��� =head1 NAME perlfaq5 - Files and Formats =head1 DESCRIPTION This section deals with I/O and the "f" issues: filehandles, flushing, formats, and footers. =head2 How do I flush/unbuffer an output filehandle? Why must I do this? X<flush> X<buffer> X<unbuffer> X<autoflush> (contributed by brian d foy) You might like to read Mark Jason Dominus's "Suffering From Buffering" at L<http://perl.plover.com/FAQs/Buffering.html> . Perl normally buffers output so it doesn't make a system call for every bit of output. By saving up output, it makes fewer expensive system calls. For instance, in this little bit of code, you want to print a dot to the screen for every line you process to watch the progress of your program. Instead of seeing a dot for every line, Perl buffers the output and you have a long wait before you see a row of 50 dots all at once: # long wait, then row of dots all at once while( <> ) { print "."; print "\n" unless ++$count % 50; #... expensive line processing operations } To get around this, you have to unbuffer the output filehandle, in this case, C<STDOUT>. You can set the special variable C<$|> to a true value (mnemonic: making your filehandles "piping hot"): $|++; # dot shown immediately while( <> ) { print "."; print "\n" unless ++$count % 50; #... expensive line processing operations } The C<$|> is one of the per-filehandle special variables, so each filehandle has its own copy of its value. If you want to merge standard output and standard error for instance, you have to unbuffer each (although STDERR might be unbuffered by default): { my $previous_default = select(STDOUT); # save previous default $|++; # autoflush STDOUT select(STDERR); $|++; # autoflush STDERR, to be sure select($previous_default); # restore previous default } # now should alternate . and + while( 1 ) { sleep 1; print STDOUT "."; print STDERR "+"; print STDOUT "\n" unless ++$count % 25; } Besides the C<$|> special variable, you can use C<binmode> to give your filehandle a C<:unix> layer, which is unbuffered: binmode( STDOUT, ":unix" ); while( 1 ) { sleep 1; print "."; print "\n" unless ++$count % 50; } For more information on output layers, see the entries for C<binmode> and L<open> in L<perlfunc>, and the L<PerlIO> module documentation. If you are using L<IO::Handle> or one of its subclasses, you can call the C<autoflush> method to change the settings of the filehandle: use IO::Handle; open my( $io_fh ), ">", "output.txt"; $io_fh->autoflush(1); The L<IO::Handle> objects also have a C<flush> method. You can flush the buffer any time you want without auto-buffering $io_fh->flush; =head2 How do I change, delete, or insert a line in a file, or append to the beginning of a file? X<file, editing> (contributed by brian d foy) The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Perl doesn't provide random access to lines (especially since the record input separator, C<$/>, is mutable), although modules such as L<Tie::File> can fake it. A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file: open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; while( <$in> ) { print $out $_; } close $out; Within that basic form, add the parts that you need to insert, change, or delete lines. To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines. open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC while( <$in> ) { print $out $_; } close $out; To change existing lines, insert the code to modify the lines inside the C<while> loop. In this case, the code finds all lowercased versions of "perl" and uppercases them. The happens for every line, so be sure that you're supposed to do that on every line! open my $in, '<', $file or die "Can't read old file: $!"; open my $out, '>', "$file.new" or die "Can't write new file: $!"; print $out "# Add this line to the top\n"; while( <$in> ) { s/\b(perl)\b/Perl/g; print $out $_; } close $out; To change only a particular line, the input line number, C<$.>, is useful. First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. After that, read the rest of the lines and print those: while( <$in> ) { # print the lines before the change print $out $_; last if $. == 4; # line number before change } my $line = <$in>; $line =~ s/\b(perl)\b/Perl/g; print $out $line; while( <$in> ) { # print the rest of the lines print $out $_; } To skip lines, use the looping controls. The C<next> in this example skips comment lines, and the C<last> stops all processing once it encounters either C<__END__> or C<__DATA__>. while( <$in> ) { next if /^\s+#/; # skip comment lines last if /^__(END|DATA)__$/; # stop at end of code marker print $out $_; } Do the same sort of thing to delete a particular line by using C<next> to skip the lines you don't want to show up in the output. This example skips every fifth line: while( <$in> ) { next unless $. % 5; print $out $_; } If, for some odd reason, you really want to see the whole file at once rather than processing line-by-line, you can slurp it in (as long as you can fit the whole thing in memory!): open my $in, '<', $file or die "Can't read old file: $!" open my $out, '>', "$file.new" or die "Can't write new file: $!"; my @lines = do { local $/; <$in> }; # slurp! # do your magic here print $out @lines; Modules such as L<File::Slurp> and L<Tie::File> can help with that too. If you can, however, avoid reading the entire file at once. Perl won't give that memory back to the operating system until the process finishes. You can also use Perl one-liners to modify a file in-place. The following changes all 'Fred' to 'Barney' in F<inFile.txt>, overwriting the file with the new contents. With the C<-p> switch, Perl wraps a C<while> loop around the code you specify with C<-e>, and C<-i> turns on in-place editing. The current line is in C<$_>. With C<-p>, Perl automatically prints the value of C<$_> at the end of the loop. See L<perlrun> for more details. perl -pi -e 's/Fred/Barney/' inFile.txt To make a backup of C<inFile.txt>, give C<-i> a file extension to add: perl -pi.bak -e 's/Fred/Barney/' inFile.txt To change only the fifth line, you can add a test checking C<$.>, the input line number, then only perform the operation when the test passes: perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt To add lines before a certain line, you can add a line (or lines!) before Perl prints C<$_>: perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt You can even add a line to the beginning of a file, since the current line prints at the end of the loop: perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt To insert a line after one already in the file, use the C<-n> switch. It's just like C<-p> except that it doesn't print C<$_> at the end of the loop, so you have to do that yourself. In this case, print C<$_> first, then print the line that you want to add. perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt To delete lines, only print the ones that you want. perl -ni -e 'print if /d/' inFile.txt =head2 How do I count the number of lines in a file? X<file, counting lines> X<lines> X<line> (contributed by brian d foy) Conceptually, the easiest way to count the lines in a file is to simply read them and count them: my $count = 0; while( <$fh> ) { $count++; } You don't really have to count them yourself, though, since Perl already does that with the C<$.> variable, which is the current line number from the last filehandle read: 1 while( <$fh> ); my $count = $.; If you want to use C<$.>, you can reduce it to a simple one-liner, like one of these: % perl -lne '} print $.; {' file % perl -lne 'END { print $. }' file Those can be rather inefficient though. If they aren't fast enough for you, you might just read chunks of data and count the number of newlines: my $lines = 0; open my($fh), '<:raw', $filename or die "Can't open $filename: $!"; while( sysread $fh, $buffer, 4096 ) { $lines += ( $buffer =~ tr/\n// ); } close FILE; However, that doesn't work if the line ending isn't a newline. You might change that C<tr///> to a C<s///> so you can count the number of times the input record separator, C<$/>, shows up: my $lines = 0; open my($fh), '<:raw', $filename or die "Can't open $filename: $!"; while( sysread $fh, $buffer, 4096 ) { $lines += ( $buffer =~ s|$/||g; ); } close FILE; If you don't mind shelling out, the C<wc> command is usually the fastest, even with the extra interprocess overhead. Ensure that you have an untainted filename though: #!perl -T $ENV{PATH} = undef; my $lines; if( $filename =~ /^([0-9a-z_.]+)\z/ ) { $lines = `/usr/bin/wc -l $1` chomp $lines; } =head2 How do I delete the last N lines from a file? X<lines> X<file> (contributed by brian d foy) The easiest conceptual solution is to count the lines in the file then start at the beginning and print the number of lines (minus the last N) to a new file. Most often, the real question is how you can delete the last N lines without making more than one pass over the file, or how to do it without a lot of copying. The easy concept is the hard reality when you might have millions of lines in your file. One trick is to use L<File::ReadBackwards>, which starts at the end of the file. That module provides an object that wraps the real filehandle to make it easy for you to move around the file. Once you get to the spot you need, you can get the actual filehandle and work with it as normal. In this case, you get the file position at the end of the last line you want to keep and truncate the file to that point: use File::ReadBackwards; my $filename = 'test.txt'; my $Lines_to_truncate = 2; my $bw = File::ReadBackwards->new( $filename ) or die "Could not read backwards in [$filename]: $!"; my $lines_from_end = 0; until( $bw->eof or $lines_from_end == $Lines_to_truncate ) { print "Got: ", $bw->readline; $lines_from_end++; } truncate( $filename, $bw->tell ); The L<File::ReadBackwards> module also has the advantage of setting the input record separator to a regular expression. You can also use the L<Tie::File> module which lets you access the lines through a tied array. You can use normal array operations to modify your file, including setting the last index and using C<splice>. =head2 How can I use Perl's C<-i> option from within a program? X<-i> X<in-place> C<-i> sets the value of Perl's C<$^I> variable, which in turn affects the behavior of C<< <> >>; see L<perlrun> for more details. By modifying the appropriate variables directly, you can get the same behavior within a larger program. For example: # ... { local($^I, @ARGV) = ('.orig', glob("*.c")); while (<>) { if ($. == 1) { print "This line should appear at the top of each file\n"; } s/\b(p)earl\b/${1}erl/i; # Correct typos, preserving case print; close ARGV if eof; # Reset $. } } # $^I and @ARGV return to their old values here This block modifies all the C<.c> files in the current directory, leaving a backup of the original data from each file in a new C<.c.orig> file. =head2 How can I copy a file? X<copy> X<file, copy> X<File::Copy> (contributed by brian d foy) Use the L<File::Copy> module. It comes with Perl and can do a true copy across file systems, and it does its magic in a portable fashion. use File::Copy; copy( $original, $new_copy ) or die "Copy failed: $!"; If you can't use L<File::Copy>, you'll have to do the work yourself: open the original file, open the destination file, then print to the destination file as you read the original. You also have to remember to copy the permissions, owner, and group to the new file. =head2 How do I make a temporary file name? X<file, temporary> If you don't need to know the name of the file, you can use C<open()> with C<undef> in place of the file name. In Perl 5.8 or later, the C<open()> function creates an anonymous temporary file: open my $tmp, '+>', undef or die $!; Otherwise, you can use the File::Temp module. use File::Temp qw/ tempfile tempdir /; my $dir = tempdir( CLEANUP => 1 ); ($fh, $filename) = tempfile( DIR => $dir ); # or if you don't need to know the filename my $fh = tempfile( DIR => $dir ); The File::Temp has been a standard module since Perl 5.6.1. If you don't have a modern enough Perl installed, use the C<new_tmpfile> class method from the IO::File module to get a filehandle opened for reading and writing. Use it if you don't need to know the file's name: use IO::File; my $fh = IO::File->new_tmpfile() or die "Unable to make new temporary file: $!"; If you're committed to creating a temporary file by hand, use the process ID and/or the current time-value. If you need to have many temporary files in one process, use a counter: BEGIN { use Fcntl; my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP}; my $base_name = sprintf "%s/%d-%d-0000", $temp_dir, $$, time; sub temp_file { my $fh; my $count = 0; until( defined(fileno($fh)) || $count++ > 100 ) { $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e; # O_EXCL is required for security reasons. sysopen $fh, $base_name, O_WRONLY|O_EXCL|O_CREAT; } if( defined fileno($fh) ) { return ($fh, $base_name); } else { return (); } } } =head2 How can I manipulate fixed-record-length files? X<fixed-length> X<file, fixed-length records> The most efficient way is using L<pack()|perlfunc/"pack"> and L<unpack()|perlfunc/"unpack">. This is faster than using L<substr()|perlfunc/"substr"> when taking many, many strings. It is slower for just a few. Here is a sample chunk of code to break up and put back together again some fixed-format input lines, in this case from the output of a normal, Berkeley-style ps: # sample input line: # 15158 p5 T 0:00 perl /home/tchrist/scripts/now-what my $PS_T = 'A6 A4 A7 A5 A*'; open my $ps, '-|', 'ps'; print scalar <$ps>; my @fields = qw( pid tt stat time command ); while (<$ps>) { my %process; @process{@fields} = unpack($PS_T, $_); for my $field ( @fields ) { print "$field: <$process{$field}>\n"; } print 'line=', pack($PS_T, @process{@fields} ), "\n"; } We've used a hash slice in order to easily handle the fields of each row. Storing the keys in an array makes it easy to operate on them as a group or loop over them with C<for>. It also avoids polluting the program with global variables and using symbolic references. =head2 How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? X<filehandle, local> X<filehandle, passing> X<filehandle, reference> As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable. You can then pass these references just like any other scalar, and use them in the place of named handles. open my $fh, $file_name; open local $fh, $file_name; print $fh "Hello World!\n"; process_file( $fh ); If you like, you can store these filehandles in an array or a hash. If you access them directly, they aren't simple scalars and you need to give C<print> a little help by placing the filehandle reference in braces. Perl can only figure it out on its own when the filehandle reference is a simple scalar. my @fhs = ( $fh1, $fh2, $fh3 ); for( $i = 0; $i <= $#fhs; $i++ ) { print {$fhs[$i]} "just another Perl answer, \n"; } Before perl5.6, you had to deal with various typeglob idioms which you may see in older code. open FILE, "> $filename"; process_typeglob( *FILE ); process_reference( \*FILE ); sub process_typeglob { local *FH = shift; print FH "Typeglob!" } sub process_reference { local $fh = shift; print $fh "Reference!" } If you want to create many anonymous handles, you should check out the Symbol or IO::Handle modules. =head2 How can I use a filehandle indirectly? X<filehandle, indirect> An indirect filehandle is the use of something other than a symbol in a place that a filehandle is expected. Here are ways to get indirect filehandles: $fh = SOME_FH; # bareword is strict-subs hostile $fh = "SOME_FH"; # strict-refs hostile; same package only $fh = *SOME_FH; # typeglob $fh = \*SOME_FH; # ref to typeglob (bless-able) $fh = *SOME_FH{IO}; # blessed IO::Handle from *SOME_FH typeglob Or, you can use the C<new> method from one of the IO::* modules to create an anonymous filehandle and store that in a scalar variable. use IO::Handle; # 5.004 or higher my $fh = IO::Handle->new(); Then use any of those as you would a normal filehandle. Anywhere that Perl is expecting a filehandle, an indirect filehandle may be used instead. An indirect filehandle is just a scalar variable that contains a filehandle. Functions like C<print>, C<open>, C<seek>, or the C<< <FH> >> diamond operator will accept either a named filehandle or a scalar variable containing one: ($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR); print $ofh "Type it: "; my $got = <$ifh> print $efh "What was that: $got"; If you're passing a filehandle to a function, you can write the function in two ways: sub accept_fh { my $fh = shift; print $fh "Sending to indirect filehandle\n"; } Or it can localize a typeglob and use the filehandle directly: sub accept_fh { local *FH = shift; print FH "Sending to localized filehandle\n"; } Both styles work with either objects or typeglobs of real filehandles. (They might also work with strings under some circumstances, but this is risky.) accept_fh(*STDOUT); accept_fh($handle); In the examples above, we assigned the filehandle to a scalar variable before using it. That is because only simple scalar variables, not expressions or subscripts of hashes or arrays, can be used with built-ins like C<print>, C<printf>, or the diamond operator. Using something other than a simple scalar variable as a filehandle is illegal and won't even compile: my @fd = (*STDIN, *STDOUT, *STDERR); print $fd[1] "Type it: "; # WRONG my $got = <$fd[0]> # WRONG print $fd[2] "What was that: $got"; # WRONG With C<print> and C<printf>, you get around this by using a block and an expression where you would place the filehandle: print { $fd[1] } "funny stuff\n"; printf { $fd[1] } "Pity the poor %x.\n", 3_735_928_559; # Pity the poor deadbeef. That block is a proper block like any other, so you can put more complicated code there. This sends the message out to one of two places: my $ok = -x "/bin/cat"; print { $ok ? $fd[1] : $fd[2] } "cat stat $ok\n"; print { $fd[ 1+ ($ok || 0) ] } "cat stat $ok\n"; This approach of treating C<print> and C<printf> like object methods calls doesn't work for the diamond operator. That's because it's a real operator, not just a function with a comma-less argument. Assuming you've been storing typeglobs in your structure as we did above, you can use the built-in function named C<readline> to read a record just as C<< <> >> does. Given the initialization shown above for @fd, this would work, but only because readline() requires a typeglob. It doesn't work with objects or strings, which might be a bug we haven't fixed yet. $got = readline($fd[0]); Let it be noted that the flakiness of indirect filehandles is not related to whether they're strings, typeglobs, objects, or anything else. It's the syntax of the fundamental operators. Playing the object game doesn't help you at all here. =head2 How can I set up a footer format to be used with write()? X<footer> There's no builtin way to do this, but L<perlform> has a couple of techniques to make it possible for the intrepid hacker. =head2 How can I write() into a string? X<write, into a string> (contributed by brian d foy) If you want to C<write> into a string, you just have to <open> a filehandle to a string, which Perl has been able to do since Perl 5.6: open FH, '>', \my $string; write( FH ); Since you want to be a good programmer, you probably want to use a lexical filehandle, even though formats are designed to work with bareword filehandles since the default format names take the filehandle name. However, you can control this with some Perl special per-filehandle variables: C<$^>, which names the top-of-page format, and C<$~> which shows the line format. You have to change the default filehandle to set these variables: open my($fh), '>', \my $string; { # set per-filehandle variables my $old_fh = select( $fh ); $~ = 'ANIMAL'; $^ = 'ANIMAL_TOP'; select( $old_fh ); } format ANIMAL_TOP = ID Type Name . format ANIMAL = @## @<<< @<<<<<<<<<<<<<< $id, $type, $name . Although write can work with lexical or package variables, whatever variables you use have to scope in the format. That most likely means you'll want to localize some package variables: { local( $id, $type, $name ) = qw( 12 cat Buster ); write( $fh ); } print $string; There are also some tricks that you can play with C<formline> and the accumulator variable C<$^A>, but you lose a lot of the value of formats since C<formline> won't handle paging and so on. You end up reimplementing formats when you use them. =head2 How can I open a filehandle to a string? X<string> X<open> X<IO::String> X<filehandle> (contributed by Peter J. Holzer, hjp-usenet2@hjp.at) Since Perl 5.8.0 a file handle referring to a string can be created by calling open with a reference to that string instead of the filename. This file handle can then be used to read from or write to the string: open(my $fh, '>', \$string) or die "Could not open string for writing"; print $fh "foo\n"; print $fh "bar\n"; # $string now contains "foo\nbar\n" open(my $fh, '<', \$string) or die "Could not open string for reading"; my $x = <$fh>; # $x now contains "foo\n" With older versions of Perl, the L<IO::String> module provides similar functionality. =head2 How can I output my numbers with commas added? X<number, commify> (contributed by brian d foy and Benjamin Goldberg) You can use L<Number::Format> to separate places in a number. It handles locale information for those of you who want to insert full stops instead (or anything else that they want to use, really). This subroutine will add commas to your number: sub commify { local $_ = shift; 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; return $_; } This regex from Benjamin Goldberg will add commas to numbers: s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g; It is easier to see with comments: s/( ^[-+]? # beginning of number. \d+? # first digits before first comma (?= # followed by, (but not included in the match) : (?>(?:\d{3})+) # some positive multiple of three digits. (?!\d) # an *exact* multiple, not x * 3 + 1 or whatever. ) | # or: \G\d{3} # after the last group, get three digits (?=\d) # but they have to have more digits after them. )/$1,/xg; =head2 How can I translate tildes (~) in a filename? X<tilde> X<tilde expansion> Use the E<lt>E<gt> (C<glob()>) operator, documented in L<perlfunc>. Versions of Perl older than 5.6 require that you have a shell installed that groks tildes. Later versions of Perl have this feature built in. The L<File::KGlob> module (available from CPAN) gives more portable glob functionality. Within Perl, you may use this directly: $filename =~ s{ ^ ~ # find a leading tilde ( # save this in $1 [^/] # a non-slash character * # repeated 0 or more times (0 means me) ) }{ $1 ? (getpwnam($1))[7] : ( $ENV{HOME} || $ENV{LOGDIR} ) }ex; =head2 How come when I open a file read-write it wipes it out? X<clobber> X<read-write> X<clobbering> X<truncate> X<truncating> Because you're using something like this, which truncates the file I<then> gives you read-write access: open my $fh, '+>', '/path/name'; # WRONG (almost always) Whoops. You should instead use this, which will fail if the file doesn't exist: open my $fh, '+<', '/path/name'; # open for update Using ">" always clobbers or creates. Using "<" never does either. The "+" doesn't change this. Here are examples of many kinds of file opens. Those using C<sysopen> all assume that you've pulled in the constants from L<Fcntl>: use Fcntl; To open file for reading: open my $fh, '<', $path or die $!; sysopen my $fh, $path, O_RDONLY or die $!; To open file for writing, create new file if needed or else truncate old file: open my $fh, '>', $path or die $!; sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT or die $!; sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666 or die $!; To open file for writing, create new file, file must not exist: sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT or die $!; sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT, 0666 or die $!; To open file for appending, create if necessary: open my $fh, '>>' $path or die $!; sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT or die $!; sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT, 0666 or die $!; To open file for appending, file must exist: sysopen my $fh, $path, O_WRONLY|O_APPEND or die $!; To open file for update, file must exist: open my $fh, '+<', $path or die $!; sysopen my $fh, $path, O_RDWR or die $!; To open file for update, create file if necessary: sysopen my $fh, $path, O_RDWR|O_CREAT or die $!; sysopen my $fh, $path, O_RDWR|O_CREAT, 0666 or die $!; To open file for update, file must not exist: sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT or die $!; sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT, 0666 or die $!; To open a file without blocking, creating if necessary: sysopen my $fh, '/foo/somefile', O_WRONLY|O_NDELAY|O_CREAT or die "can't open /foo/somefile: $!": Be warned that neither creation nor deletion of files is guaranteed to be an atomic operation over NFS. That is, two processes might both successfully create or unlink the same file! Therefore O_EXCL isn't as exclusive as you might wish. See also L<perlopentut>. =head2 Why do I sometimes get an "Argument list too long" when I use E<lt>*E<gt>? X<argument list too long> The C<< <> >> operator performs a globbing operation (see above). In Perl versions earlier than v5.6.0, the internal glob() operator forks csh(1) to do the actual glob expansion, but csh can't handle more than 127 items and so gives the error message C<Argument list too long>. People who installed tcsh as csh won't have this problem, but their users may be surprised by it. To get around this, either upgrade to Perl v5.6.0 or later, do the glob yourself with readdir() and patterns, or use a module like L<File::Glob>, one that doesn't use the shell to do globbing. =head2 How can I open a file with a leading ">" or trailing blanks? X<filename, special characters> (contributed by Brian McCauley) The special two-argument form of Perl's open() function ignores trailing blanks in filenames and infers the mode from certain leading characters (or a trailing "|"). In older versions of Perl this was the only version of open() and so it is prevalent in old code and books. Unless you have a particular reason to use the two-argument form you should use the three-argument form of open() which does not treat any characters in the filename as special. open my $fh, "<", " file "; # filename is " file " open my $fh, ">", ">file"; # filename is ">file" =head2 How can I reliably rename a file? X<rename> X<mv> X<move> X<file, rename> If your operating system supports a proper mv(1) utility or its functional equivalent, this works: rename($old, $new) or system("mv", $old, $new); It may be more portable to use the L<File::Copy> module instead. You just copy to the new file to the new name (checking return values), then delete the old one. This isn't really the same semantically as a C<rename()>, which preserves meta-information like permissions, timestamps, inode info, etc. =head2 How can I lock a file? X<lock> X<file, lock> X<flock> Perl's builtin flock() function (see L<perlfunc> for details) will call flock(2) if that exists, fcntl(2) if it doesn't (on perl version 5.004 and later), and lockf(3) if neither of the two previous system calls exists. On some systems, it may even use a different form of native locking. Here are some gotchas with Perl's flock(): =over 4 =item 1 Produces a fatal error if none of the three system calls (or their close equivalent) exists. =item 2 lockf(3) does not provide shared locking, and requires that the filehandle be open for writing (or appending, or read/writing). =item 3 Some versions of flock() can't lock files over a network (e.g. on NFS file systems), so you'd need to force the use of fcntl(2) when you build Perl. But even this is dubious at best. See the flock entry of L<perlfunc> and the F<INSTALL> file in the source distribution for information on building Perl to do this. Two potentially non-obvious but traditional flock semantics are that it waits indefinitely until the lock is granted, and that its locks are I<merely advisory>. Such discretionary locks are more flexible, but offer fewer guarantees. This means that files locked with flock() may be modified by programs that do not also use flock(). Cars that stop for red lights get on well with each other, but not with cars that don't stop for red lights. See the perlport manpage, your port's specific documentation, or your system-specific local manpages for details. It's best to assume traditional behavior if you're writing portable programs. (If you're not, you should as always feel perfectly free to write for your own system's idiosyncrasies (sometimes called "features"). Slavish adherence to portability concerns shouldn't get in the way of your getting your job done.) For more information on file locking, see also L<perlopentut/"File Locking"> if you have it (new for 5.6). =back =head2 Why can't I just open(FH, "E<gt>file.lock")? X<lock, lockfile race condition> A common bit of code B<NOT TO USE> is this: sleep(3) while -e 'file.lock'; # PLEASE DO NOT USE open my $lock, '>', 'file.lock'; # THIS BROKEN CODE This is a classic race condition: you take two steps to do something which must be done in one. That's why computer hardware provides an atomic test-and-set instruction. In theory, this "ought" to work: sysopen my $fh, "file.lock", O_WRONLY|O_EXCL|O_CREAT or die "can't open file.lock: $!"; except that lamentably, file creation (and deletion) is not atomic over NFS, so this won't work (at least, not every time) over the net. Various schemes involving link() have been suggested, but these tend to involve busy-wait, which is also less than desirable. =head2 I still don't get locking. I just want to increment the number in the file. How can I do this? X<counter> X<file, counter> Didn't anyone ever tell you web-page hit counters were useless? They don't count number of hits, they're a waste of time, and they serve only to stroke the writer's vanity. It's better to pick a random number; they're more realistic. Anyway, this is what you can do if you can't help yourself. use Fcntl qw(:DEFAULT :flock); sysopen my $fh, "numfile", O_RDWR|O_CREAT or die "can't open numfile: $!"; flock $fh, LOCK_EX or die "can't flock numfile: $!"; my $num = <$fh> || 0; seek $fh, 0, 0 or die "can't rewind numfile: $!"; truncate $fh, 0 or die "can't truncate numfile: $!"; (print $fh $num+1, "\n") or die "can't write numfile: $!"; close $fh or die "can't close numfile: $!"; Here's a much better web-page hit counter: $hits = int( (time() - 850_000_000) / rand(1_000) ); If the count doesn't impress your friends, then the code might. :-) =head2 All I want to do is append a small amount of text to the end of a file. Do I still have to use locking? X<append> X<file, append> If you are on a system that correctly implements C<flock> and you use the example appending code from "perldoc -f flock" everything will be OK even if the OS you are on doesn't implement append mode correctly (if such a system exists). So if you are happy to restrict yourself to OSs that implement C<flock> (and that's not really much of a restriction) then that is what you should do. If you know you are only going to use a system that does correctly implement appending (i.e. not Win32) then you can omit the C<seek> from the code in the previous answer. If you know you are only writing code to run on an OS and filesystem that does implement append mode correctly (a local filesystem on a modern Unix for example), and you keep the file in block-buffered mode and you write less than one buffer-full of output between each manual flushing of the buffer then each bufferload is almost guaranteed to be written to the end of the file in one chunk without getting intermingled with anyone else's output. You can also use the C<syswrite> function which is simply a wrapper around your system's C<write(2)> system call. There is still a small theoretical chance that a signal will interrupt the system-level C<write()> operation before completion. There is also a possibility that some STDIO implementations may call multiple system level C<write()>s even if the buffer was empty to start. There may be some systems where this probability is reduced to zero, and this is not a concern when using C<:perlio> instead of your system's STDIO. =head2 How do I randomly update a binary file? X<file, binary patch> If you're just trying to patch a binary, in many cases something as simple as this works: perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs However, if you have fixed sized records, then you might do something more like this: my $RECSIZE = 220; # size of record, in bytes my $recno = 37; # which record to update open my $fh, '+<', 'somewhere' or die "can't update somewhere: $!"; seek $fh, $recno * $RECSIZE, 0; read $fh, $record, $RECSIZE == $RECSIZE or die "can't read record $recno: $!"; # munge the record seek $fh, -$RECSIZE, 1; print $fh $record; close $fh; Locking and error checking are left as an exercise for the reader. Don't forget them or you'll be quite sorry. =head2 How do I get a file's timestamp in perl? X<timestamp> X<file, timestamp> If you want to retrieve the time at which the file was last read, written, or had its meta-data (owner, etc) changed, you use the B<-A>, B<-M>, or B<-C> file test operations as documented in L<perlfunc>. These retrieve the age of the file (measured against the start-time of your program) in days as a floating point number. Some platforms may not have all of these times. See L<perlport> for details. To retrieve the "raw" time in seconds since the epoch, you would call the stat function, then use C<localtime()>, C<gmtime()>, or C<POSIX::strftime()> to convert this into human-readable form. Here's an example: my $write_secs = (stat($file))[9]; printf "file %s updated at %s\n", $file, scalar localtime($write_secs); If you prefer something more legible, use the File::stat module (part of the standard distribution in version 5.004 and later): # error checking left as an exercise for reader. use File::stat; use Time::localtime; my $date_string = ctime(stat($file)->mtime); print "file $file updated at $date_string\n"; The POSIX::strftime() approach has the benefit of being, in theory, independent of the current locale. See L<perllocale> for details. =head2 How do I set a file's timestamp in perl? X<timestamp> X<file, timestamp> You use the utime() function documented in L<perlfunc/utime>. By way of example, here's a little program that copies the read and write times from its first argument to all the rest of them. if (@ARGV < 2) { die "usage: cptimes timestamp_file other_files ...\n"; } my $timestamp = shift; my($atime, $mtime) = (stat($timestamp))[8,9]; utime $atime, $mtime, @ARGV; Error checking is, as usual, left as an exercise for the reader. The perldoc for utime also has an example that has the same effect as touch(1) on files that I<already exist>. Certain file systems have a limited ability to store the times on a file at the expected level of precision. For example, the FAT and HPFS filesystem are unable to create dates on files with a finer granularity than two seconds. This is a limitation of the filesystems, not of utime(). =head2 How do I print to more than one file at once? X<print, to multiple files> To connect one filehandle to several output filehandles, you can use the L<IO::Tee> or L<Tie::FileHandle::Multiplex> modules. If you only have to do this once, you can print individually to each filehandle. for my $fh ($fh1, $fh2, $fh3) { print $fh "whatever\n" } =head2 How can I read in an entire file all at once? X<slurp> X<file, slurping> The customary Perl approach for processing all the lines in a file is to do so one line at a time: open my $input, '<', $file or die "can't open $file: $!"; while (<$input>) { chomp; # do something with $_ } close $input or die "can't close $file: $!"; This is tremendously more efficient than reading the entire file into memory as an array of lines and then processing it one element at a time, which is often--if not almost always--the wrong approach. Whenever you see someone do this: my @lines = <INPUT>; You should think long and hard about why you need everything loaded at once. It's just not a scalable solution. If you "mmap" the file with the File::Map module from CPAN, you can virtually load the entire file into a string without actually storing it in memory: use File::Map qw(map_file); map_file my $string, $filename; Once mapped, you can treat C<$string> as you would any other string. Since you don't necessarily have to load the data, mmap-ing can be very fast and may not increase your memory footprint. You might also find it more fun to use the standard L<Tie::File> module, or the L<DB_File> module's C<$DB_RECNO> bindings, which allow you to tie an array to a file so that accessing an element of the array actually accesses the corresponding line in the file. If you want to load the entire file, you can use the L<File::Slurp> module to do it in one one simple and efficient step: use File::Slurp; my $all_of_it = read_file($filename); # entire file in scalar my @all_lines = read_file($filename); # one line per element Or you can read the entire file contents into a scalar like this: my $var; { local $/; open my $fh, '<', $file or die "can't open $file: $!"; $var = <$fh>; } That temporarily undefs your record separator, and will automatically close the file at block exit. If the file is already open, just use this: my $var = do { local $/; <$fh> }; You can also use a localized C<@ARGV> to eliminate the C<open>: my $var = do { local( @ARGV, $/ ) = $file; <> }; For ordinary files you can also use the C<read> function. read( $fh, $var, -s $fh ); That third argument tests the byte size of the data on the C<$fh> filehandle and reads that many bytes into the buffer C<$var>. =head2 How can I read in a file by paragraphs? X<file, reading by paragraphs> Use the C<$/> variable (see L<perlvar> for details). You can either set it to C<""> to eliminate empty paragraphs (C<"abc\n\n\n\ndef">, for instance, gets treated as two paragraphs and not three), or C<"\n\n"> to accept empty paragraphs. Note that a blank line must have no blanks in it. Thus S<C<"fred\n \nstuff\n\n">> is one paragraph, but C<"fred\n\nstuff\n\n"> is two. =head2 How can I read a single character from a file? From the keyboard? X<getc> X<file, reading one character at a time> You can use the builtin C<getc()> function for most filehandles, but it won't (easily) work on a terminal device. For STDIN, either use the Term::ReadKey module from CPAN or use the sample code in L<perlfunc/getc>. If your system supports the portable operating system programming interface (POSIX), you can use the following code, which you'll note turns off echo processing as well. #!/usr/bin/perl -w use strict; $| = 1; for (1..4) { print "gimme: "; my $got = getone(); print "--> $got\n"; } exit; BEGIN { use POSIX qw(:termios_h); my ($term, $oterm, $echo, $noecho, $fd_stdin); my $fd_stdin = fileno(STDIN); $term = POSIX::Termios->new(); $term->getattr($fd_stdin); $oterm = $term->getlflag(); $echo = ECHO | ECHOK | ICANON; $noecho = $oterm & ~$echo; sub cbreak { $term->setlflag($noecho); $term->setcc(VTIME, 1); $term->setattr($fd_stdin, TCSANOW); } sub cooked { $term->setlflag($oterm); $term->setcc(VTIME, 0); $term->setattr($fd_stdin, TCSANOW); } sub getone { my $key = ''; cbreak(); sysread(STDIN, $key, 1); cooked(); return $key; } } END { cooked() } The Term::ReadKey module from CPAN may be easier to use. Recent versions include also support for non-portable systems as well. use Term::ReadKey; open my $tty, '<', '/dev/tty'; print "Gimme a char: "; ReadMode "raw"; my $key = ReadKey 0, $tty; ReadMode "normal"; printf "\nYou said %s, char number %03d\n", $key, ord $key; =head2 How can I tell whether there's a character waiting on a filehandle? The very first thing you should do is look into getting the Term::ReadKey extension from CPAN. As we mentioned earlier, it now even has limited support for non-portable (read: not open systems, closed, proprietary, not POSIX, not Unix, etc.) systems. You should also check out the Frequently Asked Questions list in comp.unix.* for things like this: the answer is essentially the same. It's very system-dependent. Here's one solution that works on BSD systems: sub key_ready { my($rin, $nfd); vec($rin, fileno(STDIN), 1) = 1; return $nfd = select($rin,undef,undef,0); } If you want to find out how many characters are waiting, there's also the FIONREAD ioctl call to be looked at. The I<h2ph> tool that comes with Perl tries to convert C include files to Perl code, which can be C<require>d. FIONREAD ends up defined as a function in the I<sys/ioctl.ph> file: require 'sys/ioctl.ph'; $size = pack("L", 0); ioctl(FH, FIONREAD(), $size) or die "Couldn't call ioctl: $!\n"; $size = unpack("L", $size); If I<h2ph> wasn't installed or doesn't work for you, you can I<grep> the include files by hand: % grep FIONREAD /usr/include/*/* /usr/include/asm/ioctls.h:#define FIONREAD 0x541B Or write a small C program using the editor of champions: % cat > fionread.c #include <sys/ioctl.h> main() { printf("%#08x\n", FIONREAD); } ^D % cc -o fionread fionread.c % ./fionread 0x4004667f And then hard-code it, leaving porting as an exercise to your successor. $FIONREAD = 0x4004667f; # XXX: opsys dependent $size = pack("L", 0); ioctl(FH, $FIONREAD, $size) or die "Couldn't call ioctl: $!\n"; $size = unpack("L", $size); FIONREAD requires a filehandle connected to a stream, meaning that sockets, pipes, and tty devices work, but I<not> files. =head2 How do I do a C<tail -f> in perl? X<tail> X<IO::Handle> X<File::Tail> X<clearerr> First try seek($gw_fh, 0, 1); The statement C<seek($gw_fh, 0, 1)> doesn't change the current position, but it does clear the end-of-file condition on the handle, so that the next C<< <$gw_fh> >> makes Perl try again to read something. If that doesn't work (it relies on features of your stdio implementation), then you need something more like this: for (;;) { for ($curpos = tell($gw_fh); <$gw_fh>; $curpos =tell($gw_fh)) { # search for some stuff and put it into files } # sleep for a while seek($gw_fh, $curpos, 0); # seek to where we had been } If this still doesn't work, look into the C<clearerr> method from L<IO::Handle>, which resets the error and end-of-file states on the handle. There's also a L<File::Tail> module from CPAN. =head2 How do I dup() a filehandle in Perl? X<dup> If you check L<perlfunc/open>, you'll see that several of the ways to call open() should do the trick. For example: open my $log, '>>', '/foo/logfile'; open STDERR, '>&', $log; Or even with a literal numeric descriptor: my $fd = $ENV{MHCONTEXTFD}; open $mhcontext, "<&=$fd"; # like fdopen(3S) Note that "<&STDIN" makes a copy, but "<&=STDIN" makes an alias. That means if you close an aliased handle, all aliases become inaccessible. This is not true with a copied one. Error checking, as always, has been left as an exercise for the reader. =head2 How do I close a file descriptor by number? X<file, closing file descriptors> X<POSIX> X<close> If, for some reason, you have a file descriptor instead of a filehandle (perhaps you used C<POSIX::open>), you can use the C<close()> function from the L<POSIX> module: use POSIX (); POSIX::close( $fd ); This should rarely be necessary, as the Perl C<close()> function is to be used for things that Perl opened itself, even if it was a dup of a numeric descriptor as with C<MHCONTEXT> above. But if you really have to, you may be able to do this: require 'sys/syscall.ph'; my $rc = syscall(&SYS_close, $fd + 0); # must force numeric die "can't sysclose $fd: $!" unless $rc == -1; Or, just use the fdopen(3S) feature of C<open()>: { open my $fh, "<&=$fd" or die "Cannot reopen fd=$fd: $!"; close $fh; } =head2 Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work? X<filename, DOS issues> Whoops! You just put a tab and a formfeed into that filename! Remember that within double quoted strings ("like\this"), the backslash is an escape character. The full list of these is in L<perlop/Quote and Quote-like Operators>. Unsurprisingly, you don't have a file called "c:(tab)emp(formfeed)oo" or "c:(tab)emp(formfeed)oo.exe" on your legacy DOS filesystem. Either single-quote your strings, or (preferably) use forward slashes. Since all DOS and Windows versions since something like MS-DOS 2.0 or so have treated C</> and C<\> the same in a path, you might as well use the one that doesn't clash with Perl--or the POSIX shell, ANSI C and C++, awk, Tcl, Java, or Python, just to mention a few. POSIX paths are more portable, too. =head2 Why doesn't glob("*.*") get all the files? X<glob> Because even on non-Unix ports, Perl's glob function follows standard Unix globbing semantics. You'll need C<glob("*")> to get all (non-hidden) files. This makes glob() portable even to legacy systems. Your port may include proprietary globbing functions as well. Check its documentation for details. =head2 Why does Perl let me delete read-only files? Why does C<-i> clobber protected files? Isn't this a bug in Perl? This is elaborately and painstakingly described in the F<file-dir-perms> article in the "Far More Than You Ever Wanted To Know" collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . The executive summary: learn how your filesystem works. The permissions on a file say what can happen to the data in that file. The permissions on a directory say what can happen to the list of files in that directory. If you delete a file, you're removing its name from the directory (so the operation depends on the permissions of the directory, not of the file). If you try to write to the file, the permissions of the file govern whether you're allowed to. =head2 How do I select a random line from a file? X<file, selecting a random line> Short of loading the file into a database or pre-indexing the lines in the file, there are a couple of things that you can do. Here's a reservoir-sampling algorithm from the Camel Book: srand; rand($.) < 1 && ($line = $_) while <>; This has a significant advantage in space over reading the whole file in. You can find a proof of this method in I<The Art of Computer Programming>, Volume 2, Section 3.4.2, by Donald E. Knuth. You can use the L<File::Random> module which provides a function for that algorithm: use File::Random qw/random_line/; my $line = random_line($filename); Another way is to use the L<Tie::File> module, which treats the entire file as an array. Simply access a random array element. =head2 Why do I get weird spaces when I print an array of lines? (contributed by brian d foy) If you are seeing spaces between the elements of your array when you print the array, you are probably interpolating the array in double quotes: my @animals = qw(camel llama alpaca vicuna); print "animals are: @animals\n"; It's the double quotes, not the C<print>, doing this. Whenever you interpolate an array in a double quote context, Perl joins the elements with spaces (or whatever is in C<$">, which is a space by default): animals are: camel llama alpaca vicuna This is different than printing the array without the interpolation: my @animals = qw(camel llama alpaca vicuna); print "animals are: ", @animals, "\n"; Now the output doesn't have the spaces between the elements because the elements of C<@animals> simply become part of the list to C<print>: animals are: camelllamaalpacavicuna You might notice this when each of the elements of C<@array> end with a newline. You expect to print one element per line, but notice that every line after the first is indented: this is a line this is another line this is the third line That extra space comes from the interpolation of the array. If you don't want to put anything between your array elements, don't use the array in double quotes. You can send it to print without them: print @lines; =head2 How do I traverse a directory tree? (contributed by brian d foy) The L<File::Find> module, which comes with Perl, does all of the hard work to traverse a directory structure. It comes with Perl. You simply call the C<find> subroutine with a callback subroutine and the directories you want to traverse: use File::Find; find( \&wanted, @directories ); sub wanted { # full path in $File::Find::name # just filename in $_ ... do whatever you want to do ... } The L<File::Find::Closures>, which you can download from CPAN, provides many ready-to-use subroutines that you can use with L<File::Find>. The L<File::Finder>, which you can download from CPAN, can help you create the callback subroutine using something closer to the syntax of the C<find> command-line utility: use File::Find; use File::Finder; my $deep_dirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}'); find( $deep_dirs->as_options, @places ); The L<File::Find::Rule> module, which you can download from CPAN, has a similar interface, but does the traversal for you too: use File::Find::Rule; my @files = File::Find::Rule->file() ->name( '*.pm' ) ->in( @INC ); =head2 How do I delete a directory tree? (contributed by brian d foy) If you have an empty directory, you can use Perl's built-in C<rmdir>. If the directory is not empty (so, no files or subdirectories), you either have to empty it yourself (a lot of work) or use a module to help you. The L<File::Path> module, which comes with Perl, has a C<remove_tree> which can take care of all of the hard work for you: use File::Path qw(remove_tree); remove_tree( @directories ); The L<File::Path> module also has a legacy interface to the older C<rmtree> subroutine. =head2 How do I copy an entire directory? (contributed by Shlomi Fish) To do the equivalent of C<cp -R> (i.e. copy an entire directory tree recursively) in portable Perl, you'll either need to write something yourself or find a good CPAN module such as L<File::Copy::Recursive>. =head1 AUTHOR AND COPYRIGHT Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved. This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples here are in the public domain. You are permitted and encouraged to use this code and any derivatives thereof in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit to the FAQ would be courteous but is not required. PK PU�\�E ��+ �+ perllol.podnu �[��� =head1 NAME perllol - Manipulating Arrays of Arrays in Perl =head1 DESCRIPTION =head2 Declaration and Access of Arrays of Arrays The simplest two-level data structure to build in Perl is an array of arrays, sometimes casually called a list of lists. It's reasonably easy to understand, and almost everything that applies here will also be applicable later on with the fancier data structures. An array of an array is just a regular old array @AoA that you can get at with two subscripts, like C<$AoA[3][2]>. Here's a declaration of the array: use 5.010; # so we can use say() # assign to our array, an array of array references @AoA = ( [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "george", "jane", "elroy", "judy", ], [ "homer", "bart", "marge", "maggie", ], ); say $AoA[2][1]; bart Now you should be very careful that the outer bracket type is a round one, that is, a parenthesis. That's because you're assigning to an @array, so you need parentheses. If you wanted there I<not> to be an @AoA, but rather just a reference to it, you could do something more like this: # assign a reference to array of array references $ref_to_AoA = [ [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "george", "jane", "elroy", "judy", ], [ "homer", "bart", "marge", "maggie", ], ]; say $ref_to_AoA->[2][1]; bart Notice that the outer bracket type has changed, and so our access syntax has also changed. That's because unlike C, in perl you can't freely interchange arrays and references thereto. $ref_to_AoA is a reference to an array, whereas @AoA is an array proper. Likewise, C<$AoA[2]> is not an array, but an array ref. So how come you can write these: $AoA[2][2] $ref_to_AoA->[2][2] instead of having to write these: $AoA[2]->[2] $ref_to_AoA->[2]->[2] Well, that's because the rule is that on adjacent brackets only (whether square or curly), you are free to omit the pointer dereferencing arrow. But you cannot do so for the very first one if it's a scalar containing a reference, which means that $ref_to_AoA always needs it. =head2 Growing Your Own That's all well and good for declaration of a fixed data structure, but what if you wanted to add new elements on the fly, or build it up entirely from scratch? First, let's look at reading it in from a file. This is something like adding a row at a time. We'll assume that there's a flat file in which each line is a row and each word an element. If you're trying to develop an @AoA array containing all these, here's the right way to do that: while (<>) { @tmp = split; push @AoA, [ @tmp ]; } You might also have loaded that from a function: for $i ( 1 .. 10 ) { $AoA[$i] = [ somefunc($i) ]; } Or you might have had a temporary variable sitting around with the array in it. for $i ( 1 .. 10 ) { @tmp = somefunc($i); $AoA[$i] = [ @tmp ]; } It's important you make sure to use the C<[ ]> array reference constructor. That's because this wouldn't work: $AoA[$i] = @tmp; # WRONG! The reason that doesn't do what you want is because assigning a named array like that to a scalar is taking an array in scalar context, which means just counts the number of elements in @tmp. If you are running under C<use strict> (and if you aren't, why in the world aren't you?), you'll have to add some declarations to make it happy: use strict; my(@AoA, @tmp); while (<>) { @tmp = split; push @AoA, [ @tmp ]; } Of course, you don't need the temporary array to have a name at all: while (<>) { push @AoA, [ split ]; } You also don't have to use push(). You could just make a direct assignment if you knew where you wanted to put it: my (@AoA, $i, $line); for $i ( 0 .. 10 ) { $line = <>; $AoA[$i] = [ split " ", $line ]; } or even just my (@AoA, $i); for $i ( 0 .. 10 ) { $AoA[$i] = [ split " ", <> ]; } You should in general be leery of using functions that could potentially return lists in scalar context without explicitly stating such. This would be clearer to the casual reader: my (@AoA, $i); for $i ( 0 .. 10 ) { $AoA[$i] = [ split " ", scalar(<>) ]; } If you wanted to have a $ref_to_AoA variable as a reference to an array, you'd have to do something like this: while (<>) { push @$ref_to_AoA, [ split ]; } Now you can add new rows. What about adding new columns? If you're dealing with just matrices, it's often easiest to use simple assignment: for $x (1 .. 10) { for $y (1 .. 10) { $AoA[$x][$y] = func($x, $y); } } for $x ( 3, 7, 9 ) { $AoA[$x][20] += func2($x); } It doesn't matter whether those elements are already there or not: it'll gladly create them for you, setting intervening elements to C<undef> as need be. If you wanted just to append to a row, you'd have to do something a bit funnier looking: # add new columns to an existing row push @{ $AoA[0] }, "wilma", "betty"; # explicit deref Prior to Perl 5.14, this wouldn't even compile: push $AoA[0], "wilma", "betty"; # implicit deref How come? Because once upon a time, the argument to push() had to be a real array, not just a reference to one. That's no longer true. In fact, the line marked "implicit deref" above works just fine--in this instance--to do what the one that says explicit deref did. The reason I said "in this instance" is because that I<only> works because C<$AoA[0]> already held an array reference. If you try that on an undefined variable, you'll take an exception. That's because the implicit derefererence will never autovivify an undefined variable the way C<@{ }> always will: my $aref = undef; push $aref, qw(some more values); # WRONG! push @$aref, qw(a few more); # ok If you want to take advantage of this new implicit dereferencing behavior, go right ahead: it makes code easier on the eye and wrist. Just understand that older releases will choke on it during compilation. Whenever you make use of something that works only in some given release of Perl and later, but not earlier, you should place a prominent use v5.14; # needed for implicit deref of array refs by array ops directive at the top of the file that needs it. That way when somebody tries to run the new code under an old perl, rather than getting an error like Type of arg 1 to push must be array (not array element) at /tmp/a line 8, near ""betty";" Execution of /tmp/a aborted due to compilation errors. they'll be politely informed that Perl v5.14.0 required--this is only v5.12.3, stopped at /tmp/a line 1. BEGIN failed--compilation aborted at /tmp/a line 1. =head2 Access and Printing Now it's time to print your data structure out. How are you going to do that? Well, if you want only one of the elements, it's trivial: print $AoA[0][0]; If you want to print the whole thing, though, you can't say print @AoA; # WRONG because you'll get just references listed, and perl will never automatically dereference things for you. Instead, you have to roll yourself a loop or two. This prints the whole structure, using the shell-style for() construct to loop across the outer set of subscripts. for $aref ( @AoA ) { say "\t [ @$aref ],"; } If you wanted to keep track of subscripts, you might do this: for $i ( 0 .. $#AoA ) { say "\t elt $i is [ @{$AoA[$i]} ],"; } or maybe even this. Notice the inner loop. for $i ( 0 .. $#AoA ) { for $j ( 0 .. $#{$AoA[$i]} ) { say "elt $i $j is $AoA[$i][$j]"; } } As you can see, it's getting a bit complicated. That's why sometimes is easier to take a temporary on your way through: for $i ( 0 .. $#AoA ) { $aref = $AoA[$i]; for $j ( 0 .. $#{$aref} ) { say "elt $i $j is $AoA[$i][$j]"; } } Hmm... that's still a bit ugly. How about this: for $i ( 0 .. $#AoA ) { $aref = $AoA[$i]; $n = @$aref - 1; for $j ( 0 .. $n ) { say "elt $i $j is $AoA[$i][$j]"; } } When you get tired of writing a custom print for your data structures, you might look at the standard L<Dumpvalue> or L<Data::Dumper> modules. The former is what the Perl debugger uses, while the latter generates parsable Perl code. For example: use v5.14; # using the + prototype, new to v5.14 sub show(+) { require Dumpvalue; state $prettily = new Dumpvalue:: tick => q("), compactDump => 1, # comment these two lines out veryCompact => 1, # if you want a bigger dump ; dumpValue $prettily @_; } # Assign a list of array references to an array. my @AoA = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], ); push $AoA[0], "wilma", "betty"; show @AoA; will print out: 0 0..3 "fred" "barney" "wilma" "betty" 1 0..2 "george" "jane" "elroy" 2 0..2 "homer" "marge" "bart" Whereas if you comment out the two lines I said you might wish to, then it shows it to you this way instead: 0 ARRAY(0x8031d0) 0 "fred" 1 "barney" 2 "wilma" 3 "betty" 1 ARRAY(0x803d40) 0 "george" 1 "jane" 2 "elroy" 2 ARRAY(0x803e10) 0 "homer" 1 "marge" 2 "bart" =head2 Slices If you want to get at a slice (part of a row) in a multidimensional array, you're going to have to do some fancy subscripting. That's because while we have a nice synonym for single elements via the pointer arrow for dereferencing, no such convenience exists for slices. Here's how to do one operation using a loop. We'll assume an @AoA variable as before. @part = (); $x = 4; for ($y = 7; $y < 13; $y++) { push @part, $AoA[$x][$y]; } That same loop could be replaced with a slice operation: @part = @{$AoA[4]}[7..12]; or spaced out a bit: @part = @{ $AoA[4] } [ 7..12 ]; But as you might well imagine, this can get pretty rough on the reader. Ah, but what if you wanted a I<two-dimensional slice>, such as having $x run from 4..8 and $y run from 7 to 12? Hmm... here's the simple way: @newAoA = (); for ($startx = $x = 4; $x <= 8; $x++) { for ($starty = $y = 7; $y <= 12; $y++) { $newAoA[$x - $startx][$y - $starty] = $AoA[$x][$y]; } } We can reduce some of the looping through slices for ($x = 4; $x <= 8; $x++) { push @newAoA, [ @{ $AoA[$x] } [ 7..12 ] ]; } If you were into Schwartzian Transforms, you would probably have selected map for that @newAoA = map { [ @{ $AoA[$_] } [ 7..12 ] ] } 4 .. 8; Although if your manager accused you of seeking job security (or rapid insecurity) through inscrutable code, it would be hard to argue. :-) If I were you, I'd put that in a function: @newAoA = splice_2D( \@AoA, 4 => 8, 7 => 12 ); sub splice_2D { my $lrr = shift; # ref to array of array refs! my ($x_lo, $x_hi, $y_lo, $y_hi) = @_; return map { [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ] } $x_lo .. $x_hi; } =head1 SEE ALSO L<perldata>, L<perlref>, L<perldsc> =head1 AUTHOR Tom Christiansen <F<tchrist@perl.com>> Last update: Tue Apr 26 18:30:55 MDT 2011 PK PU�\k�:�5 5 perltru64.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see pod/perlpod.pod) which is specially designed to be readable as is. =head1 NAME perltru64 - Perl version 5 on Tru64 (formerly known as Digital UNIX formerly known as DEC OSF/1) systems =head1 DESCRIPTION This document describes various features of HP's (formerly Compaq's, formerly Digital's) Unix operating system (Tru64) that will affect how Perl version 5 (hereafter just Perl) is configured, compiled and/or runs. =head2 Compiling Perl 5 on Tru64 The recommended compiler to use in Tru64 is the native C compiler. The native compiler produces much faster code (the speed difference is noticeable: several dozen percentages) and also more correct code: if you are considering using the GNU C compiler you should use at the very least the release of 2.95.3 since all older gcc releases are known to produce broken code when compiling Perl. One manifestation of this brokenness is the lib/sdbm test dumping core; another is many of the op/regexp and op/pat, or ext/Storable tests dumping core (the exact pattern of failures depending on the GCC release and optimization flags). gcc 3.2.1 is known to work okay with Perl 5.8.0. However, when optimizing the toke.c gcc likes to have a lot of memory, 256 megabytes seems to be enough. The default setting of the process data section in Tru64 should be one gigabyte, but some sites/setups might have lowered that. The configuration process of Perl checks for too low process limits, and lowers the optimization for the toke.c if necessary, and also gives advice on how to raise the process limits. Also, Configure might abort with Build a threading Perl? [n] Configure[2437]: Syntax error at line 1 : 'config.sh' is not expected. This indicates that Configure is being run with a broken Korn shell (even though you think you are using a Bourne shell by using "sh Configure" or "./Configure"). The Korn shell bug has been reported to Compaq as of February 1999 but in the meanwhile, the reason ksh is being used is that you have the environment variable BIN_SH set to 'xpg4'. This causes /bin/sh to delegate its duties to /bin/posix/sh (a ksh). Unset the environment variable and rerun Configure. =head2 Using Large Files with Perl on Tru64 In Tru64 Perl is automatically able to use large files, that is, files larger than 2 gigabytes, there is no need to use the Configure -Duselargefiles option as described in INSTALL (though using the option is harmless). =head2 Threaded Perl on Tru64 If you want to use threads, you should primarily use the Perl 5.8.0 threads model by running Configure with -Duseithreads. Perl threading is going to work only in Tru64 4.0 and newer releases, older operating releases like 3.2 aren't probably going to work properly with threads. In Tru64 V5 (at least V5.1A, V5.1B) you cannot build threaded Perl with gcc because the system header <pthread.h> explicitly checks for supported C compilers, gcc (at least 3.2.2) not being one of them. But the system C compiler should work just fine. =head2 Long Doubles on Tru64 You cannot Configure Perl to use long doubles unless you have at least Tru64 V5.0, the long double support simply wasn't functional enough before that. Perl's Configure will override attempts to use the long doubles (you can notice this by Configure finding out that the modfl() function does not work as it should). At the time of this writing (June 2002), there is a known bug in the Tru64 libc printing of long doubles when not using "e" notation. The values are correct and usable, but you only get a limited number of digits displayed unless you force the issue by using C<printf "%.33e",$num> or the like. For Tru64 versions V5.0A through V5.1A, a patch is expected sometime after perl 5.8.0 is released. If your libc has not yet been patched, you'll get a warning from Configure when selecting long doubles. =head2 DB_File tests failing on Tru64 The DB_File tests (db-btree.t, db-hash.t, db-recno.t) may fail you have installed a newer version of Berkeley DB into the system and the -I and -L compiler and linker flags introduce version conflicts with the DB 1.85 headers and libraries that came with the Tru64. For example, mixing a DB v2 library with the DB v1 headers is a bad idea. Watch out for Configure options -Dlocincpth and -Dloclibpth, and check your /usr/local/include and /usr/local/lib since they are included by default. The second option is to explicitly instruct Configure to detect the newer Berkeley DB installation, by supplying the right directories with C<-Dlocincpth=/some/include> and C<-Dloclibpth=/some/lib> B<and> before running "make test" setting your LD_LIBRARY_PATH to F</some/lib>. The third option is to work around the problem by disabling the DB_File completely when build Perl by specifying -Ui_db to Configure, and then using the BerkeleyDB module from CPAN instead of DB_File. The BerkeleyDB works with Berkeley DB versions 2.* or greater. The Berkeley DB 4.1.25 has been tested with Tru64 V5.1A and found to work. The latest Berkeley DB can be found from L<http://www.sleepycat.com>. =head2 64-bit Perl on Tru64 In Tru64 Perl's integers are automatically 64-bit wide, there is no need to use the Configure -Duse64bitint option as described in INSTALL. Similarly, there is no need for -Duse64bitall since pointers are automatically 64-bit wide. =head2 Warnings about floating-point overflow when compiling Perl on Tru64 When compiling Perl in Tru64 you may (depending on the compiler release) see two warnings like this cc: Warning: numeric.c, line 104: In this statement, floating-point overflow occurs in evaluating the expression "1.8e308". (floatoverfl) return HUGE_VAL; -----------^ and when compiling the POSIX extension cc: Warning: const-c.inc, line 2007: In this statement, floating-point overflow occurs in evaluating the expression "1.8e308". (floatoverfl) return HUGE_VAL; -------------------^ The exact line numbers may vary between Perl releases. The warnings are benign and can be ignored: in later C compiler releases the warnings should be gone. When the file F<pp_sys.c> is being compiled you may (depending on the operating system release) see an additional compiler flag being used: C<-DNO_EFF_ONLY_OK>. This is normal and refers to a feature that is relevant only if you use the C<filetest> pragma. In older releases of the operating system the feature was broken and the NO_EFF_ONLY_OK instructs Perl not to use the feature. =head1 Testing Perl on Tru64 During "make test" the C<comp/cpp> will be skipped because on Tru64 it cannot be tested before Perl has been installed. The test refers to the use of the C<-P> option of Perl. =head1 ext/ODBM_File/odbm Test Failing With Static Builds The ext/ODBM_File/odbm is known to fail with static builds (Configure -Uusedl) due to a known bug in Tru64's static libdbm library. The good news is that you very probably don't need to ever use the ODBM_File extension since more advanced NDBM_File works fine, not to mention the even more advanced DB_File. =head1 Perl Fails Because Of Unresolved Symbol sockatmark If you get an error like Can't load '.../OSF1/lib/perl5/5.8.0/alpha-dec_osf/auto/IO/IO.so' for module IO: Unresolved symbol in .../lib/perl5/5.8.0/alpha-dec_osf/auto/IO/IO.so: sockatmark at .../lib/perl5/5.8.0/alpha-dec_osf/XSLoader.pm line 75. you need to either recompile your Perl in Tru64 4.0D or upgrade your Tru64 4.0D to at least 4.0F: the sockatmark() system call was added in Tru64 4.0F, and the IO extension refers that symbol. =head1 AUTHOR Jarkko Hietaniemi <jhi@iki.fi> =cut PK PU�\�#ʫ�8 �8 perlreref.podnu �[��� =head1 NAME perlreref - Perl Regular Expressions Reference =head1 DESCRIPTION This is a quick reference to Perl's regular expressions. For full information see L<perlre> and L<perlop>, as well as the L</"SEE ALSO"> section in this document. =head2 OPERATORS C<=~> determines to which variable the regex is applied. In its absence, $_ is used. $var =~ /foo/; C<!~> determines to which variable the regex is applied, and negates the result of the match; it returns false if the match succeeds, and true if it fails. $var !~ /foo/; C<m/pattern/msixpogcdual> searches a string for a pattern match, applying the given options. m Multiline mode - ^ and $ match internal lines s match as a Single line - . matches \n i case-Insensitive x eXtended legibility - free whitespace and comments p Preserve a copy of the matched string - ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined. o compile pattern Once g Global - all occurrences c don't reset pos on failed matches when using /g a restrict \d, \s, \w and [:posix:] to match ASCII only aa (two a's) also /i matches exclude ASCII/non-ASCII l match according to current locale u match according to Unicode rules d match according to native rules unless something indicates Unicode If 'pattern' is an empty string, the last I<successfully> matched regex is used. Delimiters other than '/' may be used for both this operator and the following ones. The leading C<m> can be omitted if the delimiter is '/'. C<qr/pattern/msixpodual> lets you store a regex in a variable, or pass one around. Modifiers as for C<m//>, and are stored within the regex. C<s/pattern/replacement/msixpogcedual> substitutes matches of 'pattern' with 'replacement'. Modifiers as for C<m//>, with two additions: e Evaluate 'replacement' as an expression r Return substitution and leave the original string untouched. 'e' may be specified multiple times. 'replacement' is interpreted as a double quoted string unless a single-quote (C<'>) is the delimiter. C<?pattern?> is like C<m/pattern/> but matches only once. No alternate delimiters can be used. Must be reset with reset(). =head2 SYNTAX \ Escapes the character immediately following it . Matches any single character except a newline (unless /s is used) ^ Matches at the beginning of the string (or line, if /m is used) $ Matches at the end of the string (or line, if /m is used) * Matches the preceding element 0 or more times + Matches the preceding element 1 or more times ? Matches the preceding element 0 or 1 times {...} Specifies a range of occurrences for the element preceding it [...] Matches any one of the characters contained within the brackets (...) Groups subexpressions for capturing to $1, $2... (?:...) Groups subexpressions without capturing (cluster) | Matches either the subexpression preceding or following it \g1 or \g{1}, \g2 ... Matches the text from the Nth group \1, \2, \3 ... Matches the text from the Nth group \g-1 or \g{-1}, \g-2 ... Matches the text from the Nth previous group \g{name} Named backreference \k<name> Named backreference \k'name' Named backreference (?P=name) Named backreference (python syntax) =head2 ESCAPE SEQUENCES These work as in normal strings. \a Alarm (beep) \e Escape \f Formfeed \n Newline \r Carriage return \t Tab \037 Char whose ordinal is the 3 octal digits, max \777 \o{2307} Char whose ordinal is the octal number, unrestricted \x7f Char whose ordinal is the 2 hex digits, max \xFF \x{263a} Char whose ordinal is the hex number, unrestricted \cx Control-x \N{name} A named Unicode character or character sequence \N{U+263D} A Unicode character by hex ordinal \l Lowercase next character \u Titlecase next character \L Lowercase until \E \U Uppercase until \E \F Foldcase until \E \Q Disable pattern metacharacters until \E \E End modification For Titlecase, see L</Titlecase>. This one works differently from normal strings: \b An assertion, not backspace, except in a character class =head2 CHARACTER CLASSES [amy] Match 'a', 'm' or 'y' [f-j] Dash specifies "range" [f-j-] Dash escaped or at start or end means 'dash' [^f-j] Caret indicates "match any character _except_ these" The following sequences (except C<\N>) work within or without a character class. The first six are locale aware, all are Unicode aware. See L<perllocale> and L<perlunicode> for details. \d A digit \D A nondigit \w A word character \W A non-word character \s A whitespace character \S A non-whitespace character \h An horizontal whitespace \H A non horizontal whitespace \N A non newline (when not followed by '{NAME}'; experimental; not valid in a character class; equivalent to [^\n]; it's like '.' without /s modifier) \v A vertical whitespace \V A non vertical whitespace \R A generic newline (?>\v|\x0D\x0A) \C Match a byte (with Unicode, '.' matches a character) \pP Match P-named (Unicode) property \p{...} Match Unicode property with name longer than 1 character \PP Match non-P \P{...} Match lack of Unicode property with name longer than 1 char \X Match Unicode extended grapheme cluster POSIX character classes and their Unicode and Perl equivalents: ASCII- Full- POSIX range range backslash [[:...:]] \p{...} \p{...} sequence Description ----------------------------------------------------------------------- alnum PosixAlnum XPosixAlnum Alpha plus Digit alpha PosixAlpha XPosixAlpha Alphabetic characters ascii ASCII Any ASCII character blank PosixBlank XPosixBlank \h Horizontal whitespace; full-range also written as \p{HorizSpace} (GNU extension) cntrl PosixCntrl XPosixCntrl Control characters digit PosixDigit XPosixDigit \d Decimal digits graph PosixGraph XPosixGraph Alnum plus Punct lower PosixLower XPosixLower Lowercase characters print PosixPrint XPosixPrint Graph plus Print, but not any Cntrls punct PosixPunct XPosixPunct Punctuation and Symbols in ASCII-range; just punct outside it space PosixSpace XPosixSpace [\s\cK] PerlSpace XPerlSpace \s Perl's whitespace def'n upper PosixUpper XPosixUpper Uppercase characters word PosixWord XPosixWord \w Alnum + Unicode marks + connectors, like '_' (Perl extension) xdigit ASCII_Hex_Digit XPosixDigit Hexadecimal digit, ASCII-range is [0-9A-Fa-f] Also, various synonyms like C<\p{Alpha}> for C<\p{XPosixAlpha}>; all listed in L<perluniprops/Properties accessible through \p{} and \P{}> Within a character class: POSIX traditional Unicode [:digit:] \d \p{Digit} [:^digit:] \D \P{Digit} =head2 ANCHORS All are zero-width assertions. ^ Match string start (or line, if /m is used) $ Match string end (or line, if /m is used) or before newline \b Match word boundary (between \w and \W) \B Match except at word boundary (between \w and \w or \W and \W) \A Match string start (regardless of /m) \Z Match string end (before optional newline) \z Match absolute string end \G Match where previous m//g left off \K Keep the stuff left of the \K, don't include it in $& =head2 QUANTIFIERS Quantifiers are greedy by default and match the B<longest> leftmost. Maximal Minimal Possessive Allowed range ------- ------- ---------- ------------- {n,m} {n,m}? {n,m}+ Must occur at least n times but no more than m times {n,} {n,}? {n,}+ Must occur at least n times {n} {n}? {n}+ Must occur exactly n times * *? *+ 0 or more times (same as {0,}) + +? ++ 1 or more times (same as {1,}) ? ?? ?+ 0 or 1 time (same as {0,1}) The possessive forms (new in Perl 5.10) prevent backtracking: what gets matched by a pattern with a possessive quantifier will not be backtracked into, even if that causes the whole match to fail. There is no quantifier C<{,n}>. That's interpreted as a literal string. =head2 EXTENDED CONSTRUCTS (?#text) A comment (?:...) Groups subexpressions without capturing (cluster) (?pimsx-imsx:...) Enable/disable option (as per m// modifiers) (?=...) Zero-width positive lookahead assertion (?!...) Zero-width negative lookahead assertion (?<=...) Zero-width positive lookbehind assertion (?<!...) Zero-width negative lookbehind assertion (?>...) Grab what we can, prohibit backtracking (?|...) Branch reset (?<name>...) Named capture (?'name'...) Named capture (?P<name>...) Named capture (python syntax) (?{ code }) Embedded code, return value becomes $^R (??{ code }) Dynamic regex, return value used as regex (?N) Recurse into subpattern number N (?-N), (?+N) Recurse into Nth previous/next subpattern (?R), (?0) Recurse at the beginning of the whole pattern (?&name) Recurse into a named subpattern (?P>name) Recurse into a named subpattern (python syntax) (?(cond)yes|no) (?(cond)yes) Conditional expression, where "cond" can be: (?=pat) look-ahead (?!pat) negative look-ahead (?<=pat) look-behind (?<!pat) negative look-behind (N) subpattern N has matched something (<name>) named subpattern has matched something ('name') named subpattern has matched something (?{code}) code condition (R) true if recursing (RN) true if recursing into Nth subpattern (R&name) true if recursing into named subpattern (DEFINE) always false, no no-pattern allowed =head2 VARIABLES $_ Default variable for operators to use $` Everything prior to matched string $& Entire matched string $' Everything after to matched string ${^PREMATCH} Everything prior to matched string ${^MATCH} Entire matched string ${^POSTMATCH} Everything after to matched string The use of C<$`>, C<$&> or C<$'> will slow down B<all> regex use within your program. Consult L<perlvar> for C<@-> to see equivalent expressions that won't cause slow down. See also L<Devel::SawAmpersand>. Starting with Perl 5.10, you can also use the equivalent variables C<${^PREMATCH}>, C<${^MATCH}> and C<${^POSTMATCH}>, but for them to be defined, you have to specify the C</p> (preserve) modifier on your regular expression. $1, $2 ... hold the Xth captured expr $+ Last parenthesized pattern match $^N Holds the most recently closed capture $^R Holds the result of the last (?{...}) expr @- Offsets of starts of groups. $-[0] holds start of whole match @+ Offsets of ends of groups. $+[0] holds end of whole match %+ Named capture groups %- Named capture groups, as array refs Captured groups are numbered according to their I<opening> paren. =head2 FUNCTIONS lc Lowercase a string lcfirst Lowercase first char of a string uc Uppercase a string ucfirst Titlecase first char of a string fc Foldcase a string pos Return or set current match position quotemeta Quote metacharacters reset Reset ?pattern? status study Analyze string for optimizing matching split Use a regex to split a string into parts The first five of these are like the escape sequences C<\L>, C<\l>, C<\U>, C<\u>, and C<\F>. For Titlecase, see L</Titlecase>; For Foldcase, see L</Foldcase>. =head2 TERMINOLOGY =head3 Titlecase Unicode concept which most often is equal to uppercase, but for certain characters like the German "sharp s" there is a difference. =head3 Foldcase Unicode form that is useful when comparing strings regardless of case, as certain characters have compex one-to-many case mappings. Primarily a variant of lowercase. =head1 AUTHOR Iain Truskett. Updated by the Perl 5 Porters. This document may be distributed under the same terms as Perl itself. =head1 SEE ALSO =over 4 =item * L<perlretut> for a tutorial on regular expressions. =item * L<perlrequick> for a rapid tutorial. =item * L<perlre> for more details. =item * L<perlvar> for details on the variables. =item * L<perlop> for details on the operators. =item * L<perlfunc> for details on the functions. =item * L<perlfaq6> for FAQs on regular expressions. =item * L<perlrebackslash> for a reference on backslash sequences. =item * L<perlrecharclass> for a reference on character classes. =item * The L<re> module to alter behaviour and aid debugging. =item * L<perldebug/"Debugging Regular Expressions"> =item * L<perluniintro>, L<perlunicode>, L<charnames> and L<perllocale> for details on regexes and internationalisation. =item * I<Mastering Regular Expressions> by Jeffrey Friedl (F<http://oreilly.com/catalog/9780596528126/>) for a thorough grounding and reference on the topic. =back =head1 THANKS David P.C. Wollmann, Richard Soderberg, Sean M. Burke, Tom Christiansen, Jim Cromie, and Jeffrey Goff for useful advice. =cut PK PU�\���*` *` perlmod.podnu �[��� =head1 NAME perlmod - Perl modules (packages and symbol tables) =head1 DESCRIPTION =head2 Packages X<package> X<namespace> X<variable, global> X<global variable> X<global> Perl provides a mechanism for alternative namespaces to protect packages from stomping on each other's variables. In fact, there's really no such thing as a global variable in Perl. The package statement declares the compilation unit as being in the given namespace. The scope of the package declaration is from the declaration itself through the end of the enclosing block, C<eval>, or file, whichever comes first (the same scope as the my() and local() operators). Unqualified dynamic identifiers will be in this namespace, except for those few identifiers that if unqualified, default to the main package instead of the current one as described below. A package statement affects only dynamic variables--including those you've used local() on--but I<not> lexical variables created with my(). Typically it would be the first declaration in a file included by the C<do>, C<require>, or C<use> operators. You can switch into a package in more than one place; it merely influences which symbol table is used by the compiler for the rest of that block. You can refer to variables and filehandles in other packages by prefixing the identifier with the package name and a double colon: C<$Package::Variable>. If the package name is null, the C<main> package is assumed. That is, C<$::sail> is equivalent to C<$main::sail>. The old package delimiter was a single quote, but double colon is now the preferred delimiter, in part because it's more readable to humans, and in part because it's more readable to B<emacs> macros. It also makes C++ programmers feel like they know what's going on--as opposed to using the single quote as separator, which was there to make Ada programmers feel like they knew what was going on. Because the old-fashioned syntax is still supported for backwards compatibility, if you try to use a string like C<"This is $owner's house">, you'll be accessing C<$owner::s>; that is, the $s variable in package C<owner>, which is probably not what you meant. Use braces to disambiguate, as in C<"This is ${owner}'s house">. X<::> X<'> Packages may themselves contain package separators, as in C<$OUTER::INNER::var>. This implies nothing about the order of name lookups, however. There are no relative packages: all symbols are either local to the current package, or must be fully qualified from the outer package name down. For instance, there is nowhere within package C<OUTER> that C<$INNER::var> refers to C<$OUTER::INNER::var>. C<INNER> refers to a totally separate global package. Only identifiers starting with letters (or underscore) are stored in a package's symbol table. All other symbols are kept in package C<main>, including all punctuation variables, like $_. In addition, when unqualified, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, and SIG are forced to be in package C<main>, even when used for other purposes than their built-in ones. If you have a package called C<m>, C<s>, or C<y>, then you can't use the qualified form of an identifier because it would be instead interpreted as a pattern match, a substitution, or a transliteration. X<variable, punctuation> Variables beginning with underscore used to be forced into package main, but we decided it was more useful for package writers to be able to use leading underscore to indicate private variables and method names. However, variables and functions named with a single C<_>, such as $_ and C<sub _>, are still forced into the package C<main>. See also L<perlvar/"The Syntax of Variable Names">. C<eval>ed strings are compiled in the package in which the eval() was compiled. (Assignments to C<$SIG{}>, however, assume the signal handler specified is in the C<main> package. Qualify the signal handler name if you wish to have a signal handler in a package.) For an example, examine F<perldb.pl> in the Perl library. It initially switches to the C<DB> package so that the debugger doesn't interfere with variables in the program you are trying to debug. At various points, however, it temporarily switches back to the C<main> package to evaluate various expressions in the context of the C<main> package (or wherever you came from). See L<perldebug>. The special symbol C<__PACKAGE__> contains the current package, but cannot (easily) be used to construct variable names. See L<perlsub> for other scoping issues related to my() and local(), and L<perlref> regarding closures. =head2 Symbol Tables X<symbol table> X<stash> X<%::> X<%main::> X<typeglob> X<glob> X<alias> The symbol table for a package happens to be stored in the hash of that name with two colons appended. The main symbol table's name is thus C<%main::>, or C<%::> for short. Likewise the symbol table for the nested package mentioned earlier is named C<%OUTER::INNER::>. The value in each entry of the hash is what you are referring to when you use the C<*name> typeglob notation. local *main::foo = *main::bar; You can use this to print out all the variables in a package, for instance. The standard but antiquated F<dumpvar.pl> library and the CPAN module Devel::Symdump make use of this. The results of creating new symbol table entries directly or modifying any entries that are not already typeglobs are undefined and subject to change between releases of perl. Assignment to a typeglob performs an aliasing operation, i.e., *dick = *richard; causes variables, subroutines, formats, and file and directory handles accessible via the identifier C<richard> also to be accessible via the identifier C<dick>. If you want to alias only a particular variable or subroutine, assign a reference instead: *dick = \$richard; Which makes $richard and $dick the same variable, but leaves @richard and @dick as separate arrays. Tricky, eh? There is one subtle difference between the following statements: *foo = *bar; *foo = \$bar; C<*foo = *bar> makes the typeglobs themselves synonymous while C<*foo = \$bar> makes the SCALAR portions of two distinct typeglobs refer to the same scalar value. This means that the following code: $bar = 1; *foo = \$bar; # Make $foo an alias for $bar { local $bar = 2; # Restrict changes to block print $foo; # Prints '1'! } Would print '1', because C<$foo> holds a reference to the I<original> C<$bar>. The one that was stuffed away by C<local()> and which will be restored when the block ends. Because variables are accessed through the typeglob, you can use C<*foo = *bar> to create an alias which can be localized. (But be aware that this means you can't have a separate C<@foo> and C<@bar>, etc.) What makes all of this important is that the Exporter module uses glob aliasing as the import/export mechanism. Whether or not you can properly localize a variable that has been exported from a module depends on how it was exported: @EXPORT = qw($FOO); # Usual form, can't be localized @EXPORT = qw(*FOO); # Can be localized You can work around the first case by using the fully qualified name (C<$Package::FOO>) where you need a local value, or by overriding it by saying C<*FOO = *Package::FOO> in your script. The C<*x = \$y> mechanism may be used to pass and return cheap references into or from subroutines if you don't want to copy the whole thing. It only works when assigning to dynamic variables, not lexicals. %some_hash = (); # can't be my() *some_hash = fn( \%another_hash ); sub fn { local *hashsym = shift; # now use %hashsym normally, and you # will affect the caller's %another_hash my %nhash = (); # do what you want return \%nhash; } On return, the reference will overwrite the hash slot in the symbol table specified by the *some_hash typeglob. This is a somewhat tricky way of passing around references cheaply when you don't want to have to remember to dereference variables explicitly. Another use of symbol tables is for making "constant" scalars. X<constant> X<scalar, constant> *PI = \3.14159265358979; Now you cannot alter C<$PI>, which is probably a good thing all in all. This isn't the same as a constant subroutine, which is subject to optimization at compile-time. A constant subroutine is one prototyped to take no arguments and to return a constant expression. See L<perlsub> for details on these. The C<use constant> pragma is a convenient shorthand for these. You can say C<*foo{PACKAGE}> and C<*foo{NAME}> to find out what name and package the *foo symbol table entry comes from. This may be useful in a subroutine that gets passed typeglobs as arguments: sub identify_typeglob { my $glob = shift; print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\n"; } identify_typeglob *foo; identify_typeglob *bar::baz; This prints You gave me main::foo You gave me bar::baz The C<*foo{THING}> notation can also be used to obtain references to the individual elements of *foo. See L<perlref>. Subroutine definitions (and declarations, for that matter) need not necessarily be situated in the package whose symbol table they occupy. You can define a subroutine outside its package by explicitly qualifying the name of the subroutine: package main; sub Some_package::foo { ... } # &foo defined in Some_package This is just a shorthand for a typeglob assignment at compile time: BEGIN { *Some_package::foo = sub { ... } } and is I<not> the same as writing: { package Some_package; sub foo { ... } } In the first two versions, the body of the subroutine is lexically in the main package, I<not> in Some_package. So something like this: package main; $Some_package::name = "fred"; $main::name = "barney"; sub Some_package::foo { print "in ", __PACKAGE__, ": \$name is '$name'\n"; } Some_package::foo(); prints: in main: $name is 'barney' rather than: in Some_package: $name is 'fred' This also has implications for the use of the SUPER:: qualifier (see L<perlobj>). =head2 BEGIN, UNITCHECK, CHECK, INIT and END X<BEGIN> X<UNITCHECK> X<CHECK> X<INIT> X<END> Five specially named code blocks are executed at the beginning and at the end of a running Perl program. These are the C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT>, and C<END> blocks. These code blocks can be prefixed with C<sub> to give the appearance of a subroutine (although this is not considered good style). One should note that these code blocks don't really exist as named subroutines (despite their appearance). The thing that gives this away is the fact that you can have B<more than one> of these code blocks in a program, and they will get B<all> executed at the appropriate moment. So you can't execute any of these code blocks by name. A C<BEGIN> code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed. You may have multiple C<BEGIN> blocks within a file (or eval'ed string); they will execute in order of definition. Because a C<BEGIN> code block executes immediately, it can pull in definitions of subroutines and such from other files in time to be visible to the rest of the compile and run time. Once a C<BEGIN> has run, it is immediately undefined and any code it used is returned to Perl's memory pool. An C<END> code block is executed as late as possible, that is, after perl has finished running the program and just before the interpreter is being exited, even if it is exiting as a result of a die() function. (But not if it's morphing into another program via C<exec>, or being blown out of the water by a signal--you have to trap that yourself (if you can).) You may have multiple C<END> blocks within a file--they will execute in reverse order of definition; that is: last in, first out (LIFO). C<END> blocks are not executed when you run perl with the C<-c> switch, or if compilation fails. Note that C<END> code blocks are B<not> executed at the end of a string C<eval()>: if any C<END> code blocks are created in a string C<eval()>, they will be executed just as any other C<END> code block of that package in LIFO order just before the interpreter is being exited. Inside an C<END> code block, C<$?> contains the value that the program is going to pass to C<exit()>. You can modify C<$?> to change the exit value of the program. Beware of changing C<$?> by accident (e.g. by running something via C<system>). X<$?> Inside of a C<END> block, the value of C<${^GLOBAL_PHASE}> will be C<"END">. C<UNITCHECK>, C<CHECK> and C<INIT> code blocks are useful to catch the transition between the compilation phase and the execution phase of the main program. C<UNITCHECK> blocks are run just after the unit which defined them has been compiled. The main program file and each module it loads are compilation units, as are string C<eval>s, code compiled using the C<(?{ })> construct in a regex, calls to C<do FILE>, C<require FILE>, and code after the C<-e> switch on the command line. C<BEGIN> and C<UNITCHECK> blocks are not directly related to the phase of the interpreter. They can be created and executed during any phase. C<CHECK> code blocks are run just after the B<initial> Perl compile phase ends and before the run time begins, in LIFO order. C<CHECK> code blocks are used in the Perl compiler suite to save the compiled state of the program. Inside of a C<CHECK> block, the value of C<${^GLOBAL_PHASE}> will be C<"CHECK">. C<INIT> blocks are run just before the Perl runtime begins execution, in "first in, first out" (FIFO) order. Inside of an C<INIT> block, the value of C<${^GLOBAL_PHASE}> will be C<"INIT">. The C<CHECK> and C<INIT> blocks in code compiled by C<require>, string C<do>, or string C<eval> will not be executed if they occur after the end of the main compilation phase; that can be a problem in mod_perl and other persistent environments which use those functions to load code at runtime. When you use the B<-n> and B<-p> switches to Perl, C<BEGIN> and C<END> work just as they do in B<awk>, as a degenerate case. Both C<BEGIN> and C<CHECK> blocks are run when you use the B<-c> switch for a compile-only syntax check, although your main code is not. The B<begincheck> program makes it all clear, eventually: #!/usr/bin/perl # begincheck print "10. Ordinary code runs at runtime.\n"; END { print "16. So this is the end of the tale.\n" } INIT { print " 7. INIT blocks run FIFO just before runtime.\n" } UNITCHECK { print " 4. And therefore before any CHECK blocks.\n" } CHECK { print " 6. So this is the sixth line.\n" } print "11. It runs in order, of course.\n"; BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" } END { print "15. Read perlmod for the rest of the story.\n" } CHECK { print " 5. CHECK blocks run LIFO after all compilation.\n" } INIT { print " 8. Run this again, using Perl's -c switch.\n" } print "12. This is anti-obfuscated code.\n"; END { print "14. END blocks run LIFO at quitting time.\n" } BEGIN { print " 2. So this line comes out second.\n" } UNITCHECK { print " 3. UNITCHECK blocks run LIFO after each file is compiled.\n" } INIT { print " 9. You'll see the difference right away.\n" } print "13. It merely _looks_ like it should be confusing.\n"; __END__ =head2 Perl Classes X<class> X<@ISA> There is no special class syntax in Perl, but a package may act as a class if it provides subroutines to act as methods. Such a package may also derive some of its methods from another class (package) by listing the other package name(s) in its global @ISA array (which must be a package global, not a lexical). For more on this, see L<perlootut> and L<perlobj>. =head2 Perl Modules X<module> A module is just a set of related functions in a library file, i.e., a Perl package with the same name as the file. It is specifically designed to be reusable by other modules or programs. It may do this by providing a mechanism for exporting some of its symbols into the symbol table of any package using it, or it may function as a class definition and make its semantics available implicitly through method calls on the class and its objects, without explicitly exporting anything. Or it can do a little of both. For example, to start a traditional, non-OO module called Some::Module, create a file called F<Some/Module.pm> and start with this template: package Some::Module; # assumes Some/Module.pm use strict; use warnings; BEGIN { require Exporter; # set the version for version checking our $VERSION = 1.00; # Inherit from Exporter to export functions and variables our @ISA = qw(Exporter); # Functions and variables which are exported by default our @EXPORT = qw(func1 func2); # Functions and variables which can be optionally exported our @EXPORT_OK = qw($Var1 %Hashit func3); } # exported package globals go here our $Var1 = ''; our %Hashit = (); # non-exported package globals go here # (they are still accessible as $Some::Module::stuff) our @more = (); our $stuff = ''; # file-private lexicals go here, before any functions which use them my $priv_var = ''; my %secret_hash = (); # here's a file-private function as a closure, # callable as $priv_func->(); my $priv_func = sub { ... }; # make all your functions, whether exported or not; # remember to put something interesting in the {} stubs sub func1 { ... } sub func2 { ... } # this one isn't exported, but could be called directly # as Some::Module::func3() sub func3 { ... } END { ... } # module clean-up code here (global destructor) 1; # don't forget to return a true value from the file Then go on to declare and use your variables in functions without any qualifications. See L<Exporter> and the L<perlmodlib> for details on mechanics and style issues in module creation. Perl modules are included into your program by saying use Module; or use Module LIST; This is exactly equivalent to BEGIN { require 'Module.pm'; 'Module'->import; } or BEGIN { require 'Module.pm'; 'Module'->import( LIST ); } As a special case use Module (); is exactly equivalent to BEGIN { require 'Module.pm'; } All Perl module files have the extension F<.pm>. The C<use> operator assumes this so you don't have to spell out "F<Module.pm>" in quotes. This also helps to differentiate new modules from old F<.pl> and F<.ph> files. Module names are also capitalized unless they're functioning as pragmas; pragmas are in effect compiler directives, and are sometimes called "pragmatic modules" (or even "pragmata" if you're a classicist). The two statements: require SomeModule; require "SomeModule.pm"; differ from each other in two ways. In the first case, any double colons in the module name, such as C<Some::Module>, are translated into your system's directory separator, usually "/". The second case does not, and would have to be specified literally. The other difference is that seeing the first C<require> clues in the compiler that uses of indirect object notation involving "SomeModule", as in C<$ob = purge SomeModule>, are method calls, not function calls. (Yes, this really can make a difference.) Because the C<use> statement implies a C<BEGIN> block, the importing of semantics happens as soon as the C<use> statement is compiled, before the rest of the file is compiled. This is how it is able to function as a pragma mechanism, and also how modules are able to declare subroutines that are then visible as list or unary operators for the rest of the current file. This will not work if you use C<require> instead of C<use>. With C<require> you can get into this problem: require Cwd; # make Cwd:: accessible $here = Cwd::getcwd(); use Cwd; # import names from Cwd:: $here = getcwd(); require Cwd; # make Cwd:: accessible $here = getcwd(); # oops! no main::getcwd() In general, C<use Module ()> is recommended over C<require Module>, because it determines module availability at compile time, not in the middle of your program's execution. An exception would be if two modules each tried to C<use> each other, and each also called a function from that other module. In that case, it's easy to use C<require> instead. Perl packages may be nested inside other package names, so we can have package names containing C<::>. But if we used that package name directly as a filename it would make for unwieldy or impossible filenames on some systems. Therefore, if a module's name is, say, C<Text::Soundex>, then its definition is actually found in the library file F<Text/Soundex.pm>. Perl modules always have a F<.pm> file, but there may also be dynamically linked executables (often ending in F<.so>) or autoloaded subroutine definitions (often ending in F<.al>) associated with the module. If so, these will be entirely transparent to the user of the module. It is the responsibility of the F<.pm> file to load (or arrange to autoload) any additional functionality. For example, although the POSIX module happens to do both dynamic loading and autoloading, the user can say just C<use POSIX> to get it all. =head2 Making your module threadsafe X<threadsafe> X<thread safe> X<module, threadsafe> X<module, thread safe> X<CLONE> X<CLONE_SKIP> X<thread> X<threads> X<ithread> Since 5.6.0, Perl has had support for a new type of threads called interpreter threads (ithreads). These threads can be used explicitly and implicitly. Ithreads work by cloning the data tree so that no data is shared between different threads. These threads can be used by using the C<threads> module or by doing fork() on win32 (fake fork() support). When a thread is cloned all Perl data is cloned, however non-Perl data cannot be cloned automatically. Perl after 5.7.2 has support for the C<CLONE> special subroutine. In C<CLONE> you can do whatever you need to do, like for example handle the cloning of non-Perl data, if necessary. C<CLONE> will be called once as a class method for every package that has it defined (or inherits it). It will be called in the context of the new thread, so all modifications are made in the new area. Currently CLONE is called with no parameters other than the invocant package name, but code should not assume that this will remain unchanged, as it is likely that in future extra parameters will be passed in to give more information about the state of cloning. If you want to CLONE all objects you will need to keep track of them per package. This is simply done using a hash and Scalar::Util::weaken(). Perl after 5.8.7 has support for the C<CLONE_SKIP> special subroutine. Like C<CLONE>, C<CLONE_SKIP> is called once per package; however, it is called just before cloning starts, and in the context of the parent thread. If it returns a true value, then no objects of that class will be cloned; or rather, they will be copied as unblessed, undef values. For example: if in the parent there are two references to a single blessed hash, then in the child there will be two references to a single undefined scalar value instead. This provides a simple mechanism for making a module threadsafe; just add C<sub CLONE_SKIP { 1 }> at the top of the class, and C<DESTROY()> will now only be called once per object. Of course, if the child thread needs to make use of the objects, then a more sophisticated approach is needed. Like C<CLONE>, C<CLONE_SKIP> is currently called with no parameters other than the invocant package name, although that may change. Similarly, to allow for future expansion, the return value should be a single C<0> or C<1> value. =head1 SEE ALSO See L<perlmodlib> for general style issues related to building Perl modules and classes, as well as descriptions of the standard library and CPAN, L<Exporter> for how Perl's standard import/export mechanism works, L<perlootut> and L<perlobj> for in-depth information on creating classes, L<perlobj> for a hard-core reference document on objects, L<perlsub> for an explanation of functions and scoping, and L<perlxstut> and L<perlguts> for more information on writing extension modules. PK PU�\�G�) �) perlmacosx.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see pod/perlpod.pod) which is specially designed to be readable as is. =head1 NAME perlmacosx - Perl under Mac OS X =head1 SYNOPSIS This document briefly describes Perl under Mac OS X. curl http://www.cpan.org/src/perl-5.12.3.tar.gz > perl-5.12.3.tar.gz tar -xzf perl-5.12.3.tar.gz cd perl-5.12.3 ./Configure -des -Dprefix=/usr/local/ make make test sudo make install =head1 DESCRIPTION The latest Perl release (5.12.3 as of this writing) builds without changes under all versions of Mac OS X from 10.3 "Panther" onwards. In order to build your own version of Perl you will need 'make' this is part of the Apples developer tools (you only need the 'unix tools'), usually supplied with Mac OS install DVDs. You do not need the latest version of Xcode (which is now charged for) in order to install make. Earlier Mac OS X releases (10.2 "Jaguar" and older) did not include a completely thread-safe libc, so threading is not fully supported. Also, earlier releases included a buggy libdb, so some of the DB_File tests are known to fail on those releases. =head2 Installation Prefix The default installation location for this release uses the traditional UNIX directory layout under /usr/local. This is the recommended location for most users, and will leave the Apple-supplied Perl and its modules undisturbed. Using an installation prefix of '/usr' will result in a directory layout that mirrors that of Apple's default Perl, with core modules stored in '/System/Library/Perl/${version}', CPAN modules stored in '/Library/Perl/${version}', and the addition of '/Network/Library/Perl/${version}' to @INC for modules that are stored on a file server and used by many Macs. =head2 SDK support First, export the path to the SDK into the build environment: export SDK=/Developer/SDKs/MacOSX10.3.9.sdk Use an SDK by exporting some additions to Perl's 'ccflags' and '..flags' config variables: ./Configure -Accflags="-nostdinc -B$SDK/usr/include/gcc \ -B$SDK/usr/lib/gcc -isystem$SDK/usr/include \ -F$SDK/System/Library/Frameworks" \ -Aldflags="-Wl,-syslibroot,$SDK" \ -de =head2 Universal Binary support To compile perl as a universal binary (built for both ppc and intel), export the SDK variable as above, selecting the 10.4u SDK: export SDK=/Developer/SDKs/MacOSX10.4u.sdk In addition to the compiler flags used to select the SDK, also add the flags for creating a universal binary: ./Configure -Accflags="-arch i686 -arch ppc -nostdinc -B$SDK/usr/include/gcc \ -B$SDK/usr/lib/gcc -isystem$SDK/usr/include \ -F$SDK/System/Library/Frameworks" \ -Aldflags="-arch i686 -arch ppc -Wl,-syslibroot,$SDK" \ -de In Leopard (MacOSX 10.5.6 at the time of this writing) you must use the 10.5 SDK: export SDK=/Developer/SDKs/MacOSX10.5.sdk You can use the same compiler flags you would use with the 10.4u SDK. Keep in mind that these compiler and linker settings will also be used when building CPAN modules. For XS modules to be compiled as a universal binary, any libraries it links to must also be universal binaries. The system libraries that Apple includes with the 10.4u SDK are all universal, but user-installed libraries may need to be re-installed as universal binaries. =head2 64-bit PPC support Follow the instructions in F<INSTALL> to build perl with support for 64-bit integers (C<use64bitint>) or both 64-bit integers and 64-bit addressing (C<use64bitall>). In the latter case, the resulting binary will run only on G5-based hosts. Support for 64-bit addressing is experimental: some aspects of Perl may be omitted or buggy. Note the messages output by F<Configure> for further information. Please use C<perlbug> to submit a problem report in the event that you encounter difficulties. When building 64-bit modules, it is your responsibility to ensure that linked external libraries and frameworks provide 64-bit support: if they do not, module building may appear to succeed, but attempts to use the module will result in run-time dynamic linking errors, and subsequent test failures. You can use C<file> to discover the architectures supported by a library: $ file libgdbm.3.0.0.dylib libgdbm.3.0.0.dylib: Mach-O fat file with 2 architectures libgdbm.3.0.0.dylib (for architecture ppc): Mach-O dynamically linked shared library ppc libgdbm.3.0.0.dylib (for architecture ppc64): Mach-O 64-bit dynamically linked shared library ppc64 Note that this issue precludes the building of many Macintosh-specific CPAN modules (C<Mac::*>), as the required Apple frameworks do not provide PPC64 support. Similarly, downloads from Fink or Darwinports are unlikely to provide 64-bit support; the libraries must be rebuilt from source with the appropriate compiler and linker flags. For further information, see Apple's I<64-Bit Transition Guide> at L<http://developer.apple.com/documentation/Darwin/Conceptual/64bitPorting/index.html>. =head2 libperl and Prebinding Mac OS X ships with a dynamically-loaded libperl, but the default for this release is to compile a static libperl. The reason for this is pre-binding. Dynamic libraries can be pre-bound to a specific address in memory in order to decrease load time. To do this, one needs to be aware of the location and size of all previously-loaded libraries. Apple collects this information as part of their overall OS build process, and thus has easy access to it when building Perl, but ordinary users would need to go to a great deal of effort to obtain the information needed for pre-binding. You can override the default and build a shared libperl if you wish (S<Configure ... -Duseshrplib>), but the load time on pre-10.4 OS releases will be greater than either the static library, or Apple's pre-bound dynamic library. With 10.4 "Tiger" and newer, Apple has all but eliminated the performance penalty for non-prebound libraries. =head2 Updating Apple's Perl In a word - don't, at least without a *very* good reason. Your scripts can just as easily begin with "#!/usr/local/bin/perl" as with "#!/usr/bin/perl". Scripts supplied by Apple and other third parties as part of installation packages and such have generally only been tested with the /usr/bin/perl that's installed by Apple. If you find that you do need to update the system Perl, one issue worth keeping in mind is the question of static vs. dynamic libraries. If you upgrade using the default static libperl, you will find that the dynamic libperl supplied by Apple will not be deleted. If both libraries are present when an application that links against libperl is built, ld will link against the dynamic library by default. So, if you need to replace Apple's dynamic libperl with a static libperl, you need to be sure to delete the older dynamic library after you've installed the update. =head2 Known problems If you have installed extra libraries such as GDBM through Fink (in other words, you have libraries under F</sw/lib>), or libdlcompat to F</usr/local/lib>, you may need to be extra careful when running Configure to not to confuse Configure and Perl about which libraries to use. Being confused will show up for example as "dyld" errors about symbol problems, for example during "make test". The safest bet is to run Configure as Configure ... -Uloclibpth -Dlibpth=/usr/lib to make Configure look only into the system libraries. If you have some extra library directories that you really want to use (such as newer Berkeley DB libraries in pre-Panther systems), add those to the libpth: Configure ... -Uloclibpth -Dlibpth='/usr/lib /opt/lib' The default of building Perl statically may cause problems with complex applications like Tk: in that case consider building shared Perl Configure ... -Duseshrplib but remember that there's a startup cost to pay in that case (see above "libperl and Prebinding"). Starting with Tiger (Mac OS X 10.4), Apple shipped broken locale files for the eu_ES locale (Basque-Spain). In previous releases of Perl, this resulted in failures in the F<lib/locale> test. These failures have been suppressed in the current release of Perl by making the test ignore the broken locale. If you need to use the eu_ES locale, you should contact Apple support. =head2 Cocoa There are two ways to use Cocoa from Perl. Apple's PerlObjCBridge module, included with Mac OS X, can be used by standalone scripts to access Foundation (i.e. non-GUI) classes and objects. An alternative is CamelBones, a framework that allows access to both Foundation and AppKit classes and objects, so that full GUI applications can be built in Perl. CamelBones can be found on SourceForge, at L<http://www.sourceforge.net/projects/camelbones/>. =head1 Starting From Scratch Unfortunately it is not that difficult somehow manage to break one's Mac OS X Perl rather severely. If all else fails and you want to really, B<REALLY>, start from scratch and remove even your Apple Perl installation (which has become corrupted somehow), the following instructions should do it. B<Please think twice before following these instructions: they are much like conducting brain surgery to yourself. Without anesthesia.> We will B<not> come to fix your system if you do this. First, get rid of the libperl.dylib: # cd /System/Library/Perl/darwin/CORE # rm libperl.dylib Then delete every .bundle file found anywhere in the folders: /System/Library/Perl /Library/Perl You can find them for example by # find /System/Library/Perl /Library/Perl -name '*.bundle' -print After this you can either copy Perl from your operating system media (you will need at least the /System/Library/Perl and /usr/bin/perl), or rebuild Perl from the source code with C<Configure -Dprefix=/usr -Duseshrplib> NOTE: the C<-Dprefix=/usr> to replace the system Perl works much better with Perl 5.8.1 and later, in Perl 5.8.0 the settings were not quite right. "Pacifist" from CharlesSoft (L<http://www.charlessoft.com/>) is a nice way to extract the Perl binaries from the OS media, without having to reinstall the entire OS. =head1 AUTHOR This README was written by Sherm Pendley E<lt>sherm@dot-app.orgE<gt>, and subsequently updated by Dominic Dunlop E<lt>domo@computer.orgE<gt>. The "Starting From Scratch" recipe was contributed by John Montbriand E<lt>montbriand@apple.comE<gt>. =head1 DATE Last modified 2006-02-24. PK PU�\����U U perlpod.podnu �[��� =for comment This document is in Pod format. To read this, use a Pod formatter, like "perldoc perlpod". =head1 NAME X<POD> X<plain old documentation> perlpod - the Plain Old Documentation format =head1 DESCRIPTION Pod is a simple-to-use markup language used for writing documentation for Perl, Perl programs, and Perl modules. Translators are available for converting Pod to various formats like plain text, HTML, man pages, and more. Pod markup consists of three basic kinds of paragraphs: L<ordinary|/"Ordinary Paragraph">, L<verbatim|/"Verbatim Paragraph">, and L<command|/"Command Paragraph">. =head2 Ordinary Paragraph X<POD, ordinary paragraph> Most paragraphs in your documentation will be ordinary blocks of text, like this one. You can simply type in your text without any markup whatsoever, and with just a blank line before and after. When it gets formatted, it will undergo minimal formatting, like being rewrapped, probably put into a proportionally spaced font, and maybe even justified. You can use formatting codes in ordinary paragraphs, for B<bold>, I<italic>, C<code-style>, L<hyperlinks|perlfaq>, and more. Such codes are explained in the "L<Formatting Codes|/"Formatting Codes">" section, below. =head2 Verbatim Paragraph X<POD, verbatim paragraph> X<verbatim> Verbatim paragraphs are usually used for presenting a codeblock or other text which does not require any special parsing or formatting, and which shouldn't be wrapped. A verbatim paragraph is distinguished by having its first character be a space or a tab. (And commonly, all its lines begin with spaces and/or tabs.) It should be reproduced exactly, with tabs assumed to be on 8-column boundaries. There are no special formatting codes, so you can't italicize or anything like that. A \ means \, and nothing else. =head2 Command Paragraph X<POD, command> A command paragraph is used for special treatment of whole chunks of text, usually as headings or parts of lists. All command paragraphs (which are typically only one line long) start with "=", followed by an identifier, followed by arbitrary text that the command can use however it pleases. Currently recognized commands are =pod =head1 Heading Text =head2 Heading Text =head3 Heading Text =head4 Heading Text =over indentlevel =item stuff =back =begin format =end format =for format text... =encoding type =cut To explain them each in detail: =over =item C<=head1 I<Heading Text>> X<=head1> X<=head2> X<=head3> X<=head4> X<head1> X<head2> X<head3> X<head4> =item C<=head2 I<Heading Text>> =item C<=head3 I<Heading Text>> =item C<=head4 I<Heading Text>> Head1 through head4 produce headings, head1 being the highest level. The text in the rest of this paragraph is the content of the heading. For example: =head2 Object Attributes The text "Object Attributes" comprises the heading there. (Note that head3 and head4 are recent additions, not supported in older Pod translators.) The text in these heading commands can use formatting codes, as seen here: =head2 Possible Values for C<$/> Such commands are explained in the "L<Formatting Codes|/"Formatting Codes">" section, below. =item C<=over I<indentlevel>> X<=over> X<=item> X<=back> X<over> X<item> X<back> =item C<=item I<stuff...>> =item C<=back> Item, over, and back require a little more explanation: "=over" starts a region specifically for the generation of a list using "=item" commands, or for indenting (groups of) normal paragraphs. At the end of your list, use "=back" to end it. The I<indentlevel> option to "=over" indicates how far over to indent, generally in ems (where one em is the width of an "M" in the document's base font) or roughly comparable units; if there is no I<indentlevel> option, it defaults to four. (And some formatters may just ignore whatever I<indentlevel> you provide.) In the I<stuff> in C<=item I<stuff...>>, you may use formatting codes, as seen here: =item Using C<$|> to Control Buffering Such commands are explained in the "L<Formatting Codes|/"Formatting Codes">" section, below. Note also that there are some basic rules to using "=over" ... "=back" regions: =over =item * Don't use "=item"s outside of an "=over" ... "=back" region. =item * The first thing after the "=over" command should be an "=item", unless there aren't going to be any items at all in this "=over" ... "=back" region. =item * Don't put "=headI<n>" commands inside an "=over" ... "=back" region. =item * And perhaps most importantly, keep the items consistent: either use "=item *" for all of them, to produce bullets; or use "=item 1.", "=item 2.", etc., to produce numbered lists; or use "=item foo", "=item bar", etc.--namely, things that look nothing like bullets or numbers. If you start with bullets or numbers, stick with them, as formatters use the first "=item" type to decide how to format the list. =back =item C<=cut> X<=cut> X<cut> To end a Pod block, use a blank line, then a line beginning with "=cut", and a blank line after it. This lets Perl (and the Pod formatter) know that this is where Perl code is resuming. (The blank line before the "=cut" is not technically necessary, but many older Pod processors require it.) =item C<=pod> X<=pod> X<pod> The "=pod" command by itself doesn't do much of anything, but it signals to Perl (and Pod formatters) that a Pod block starts here. A Pod block starts with I<any> command paragraph, so a "=pod" command is usually used just when you want to start a Pod block with an ordinary paragraph or a verbatim paragraph. For example: =item stuff() This function does stuff. =cut sub stuff { ... } =pod Remember to check its return value, as in: stuff() || die "Couldn't do stuff!"; =cut =item C<=begin I<formatname>> X<=begin> X<=end> X<=for> X<begin> X<end> X<for> =item C<=end I<formatname>> =item C<=for I<formatname> I<text...>> For, begin, and end will let you have regions of text/code/data that are not generally interpreted as normal Pod text, but are passed directly to particular formatters, or are otherwise special. A formatter that can use that format will use the region, otherwise it will be completely ignored. A command "=begin I<formatname>", some paragraphs, and a command "=end I<formatname>", mean that the text/data in between is meant for formatters that understand the special format called I<formatname>. For example, =begin html <hr> <img src="thang.png"> <p> This is a raw HTML paragraph </p> =end html The command "=for I<formatname> I<text...>" specifies that the remainder of just this paragraph (starting right after I<formatname>) is in that special format. =for html <hr> <img src="thang.png"> <p> This is a raw HTML paragraph </p> This means the same thing as the above "=begin html" ... "=end html" region. That is, with "=for", you can have only one paragraph's worth of text (i.e., the text in "=foo targetname text..."), but with "=begin targetname" ... "=end targetname", you can have any amount of stuff in between. (Note that there still must be a blank line after the "=begin" command and a blank line before the "=end" command. Here are some examples of how to use these: =begin html <br>Figure 1.<br><IMG SRC="figure1.png"><br> =end html =begin text --------------- | foo | | bar | --------------- ^^^^ Figure 1. ^^^^ =end text Some format names that formatters currently are known to accept include "roff", "man", "latex", "tex", "text", and "html". (Some formatters will treat some of these as synonyms.) A format name of "comment" is common for just making notes (presumably to yourself) that won't appear in any formatted version of the Pod document: =for comment Make sure that all the available options are documented! Some I<formatnames> will require a leading colon (as in C<"=for :formatname">, or C<"=begin :formatname" ... "=end :formatname">), to signal that the text is not raw data, but instead I<is> Pod text (i.e., possibly containing formatting codes) that's just not for normal formatting (e.g., may not be a normal-use paragraph, but might be for formatting as a footnote). =item C<=encoding I<encodingname>> X<=encoding> X<encoding> This command is used for declaring the encoding of a document. Most users won't need this; but if your encoding isn't US-ASCII or Latin-1, then put a C<=encoding I<encodingname>> command early in the document so that pod formatters will know how to decode the document. For I<encodingname>, use a name recognized by the L<Encode::Supported> module. Examples: =encoding utf8 =encoding koi8-r =encoding ShiftJIS =encoding big5 =back C<=encoding> affects the whole document, and must occur only once. And don't forget, when using any other command, that the command lasts up until the end of its I<paragraph>, not its line. So in the examples below, you can see that every command needs the blank line after it, to end its paragraph. Some examples of lists include: =over =item * First item =item * Second item =back =over =item Foo() Description of Foo function =item Bar() Description of Bar function =back =head2 Formatting Codes X<POD, formatting code> X<formatting code> X<POD, interior sequence> X<interior sequence> In ordinary paragraphs and in some command paragraphs, various formatting codes (a.k.a. "interior sequences") can be used: =for comment "interior sequences" is such an opaque term. Prefer "formatting codes" instead. =over =item C<IE<lt>textE<gt>> -- italic text X<I> X<< IZ<><> >> X<POD, formatting code, italic> X<italic> Used for emphasis ("C<be IE<lt>careful!E<gt>>") and parameters ("C<redo IE<lt>LABELE<gt>>") =item C<BE<lt>textE<gt>> -- bold text X<B> X<< BZ<><> >> X<POD, formatting code, bold> X<bold> Used for switches ("C<perl's BE<lt>-nE<gt> switch>"), programs ("C<some systems provide a BE<lt>chfnE<gt> for that>"), emphasis ("C<be BE<lt>careful!E<gt>>"), and so on ("C<and that feature is known as BE<lt>autovivificationE<gt>>"). =item C<CE<lt>codeE<gt>> -- code text X<C> X<< CZ<><> >> X<POD, formatting code, code> X<code> Renders code in a typewriter font, or gives some other indication that this represents program text ("C<CE<lt>gmtime($^T)E<gt>>") or some other form of computerese ("C<CE<lt>drwxr-xr-xE<gt>>"). =item C<LE<lt>nameE<gt>> -- a hyperlink X<L> X<< LZ<><> >> X<POD, formatting code, hyperlink> X<hyperlink> There are various syntaxes, listed below. In the syntaxes given, C<text>, C<name>, and C<section> cannot contain the characters '/' and '|'; and any '<' or '>' should be matched. =over =item * C<LE<lt>nameE<gt>> Link to a Perl manual page (e.g., C<LE<lt>Net::PingE<gt>>). Note that C<name> should not contain spaces. This syntax is also occasionally used for references to Unix man pages, as in C<LE<lt>crontab(5)E<gt>>. =item * C<LE<lt>name/"sec"E<gt>> or C<LE<lt>name/secE<gt>> Link to a section in other manual page. E.g., C<LE<lt>perlsyn/"For Loops"E<gt>> =item * C<LE<lt>/"sec"E<gt>> or C<LE<lt>/secE<gt>> Link to a section in this manual page. E.g., C<LE<lt>/"Object Methods"E<gt>> =back A section is started by the named heading or item. For example, C<LE<lt>perlvar/$.E<gt>> or C<LE<lt>perlvar/"$."E<gt>> both link to the section started by "C<=item $.>" in perlvar. And C<LE<lt>perlsyn/For LoopsE<gt>> or C<LE<lt>perlsyn/"For Loops"E<gt>> both link to the section started by "C<=head2 For Loops>" in perlsyn. To control what text is used for display, you use "C<LE<lt>text|...E<gt>>", as in: =over =item * C<LE<lt>text|nameE<gt>> Link this text to that manual page. E.g., C<LE<lt>Perl Error Messages|perldiagE<gt>> =item * C<LE<lt>text|name/"sec"E<gt>> or C<LE<lt>text|name/secE<gt>> Link this text to that section in that manual page. E.g., C<LE<lt>postfix "if"|perlsyn/"Statement Modifiers"E<gt>> =item * C<LE<lt>text|/"sec"E<gt>> or C<LE<lt>text|/secE<gt>> or C<LE<lt>text|"sec"E<gt>> Link this text to that section in this manual page. E.g., C<LE<lt>the various attributes|/"Member Data"E<gt>> =back Or you can link to a web page: =over =item * C<LE<lt>scheme:...E<gt>> C<LE<lt>text|scheme:...E<gt>> Links to an absolute URL. For example, C<LE<lt>http://www.perl.org/E<gt>> or C<LE<lt>The Perl Home Page|http://www.perl.org/E<gt>>. =back =item C<EE<lt>escapeE<gt>> -- a character escape X<E> X<< EZ<><> >> X<POD, formatting code, escape> X<escape> Very similar to HTML/XML C<&I<foo>;> "entity references": =over =item * C<EE<lt>ltE<gt>> -- a literal E<lt> (less than) =item * C<EE<lt>gtE<gt>> -- a literal E<gt> (greater than) =item * C<EE<lt>verbarE<gt>> -- a literal | (I<ver>tical I<bar>) =item * C<EE<lt>solE<gt>> -- a literal / (I<sol>idus) The above four are optional except in other formatting codes, notably C<LE<lt>...E<gt>>, and when preceded by a capital letter. =item * C<EE<lt>htmlnameE<gt>> Some non-numeric HTML entity name, such as C<EE<lt>eacuteE<gt>>, meaning the same thing as C<é> in HTML -- i.e., a lowercase e with an acute (/-shaped) accent. =item * C<EE<lt>numberE<gt>> The ASCII/Latin-1/Unicode character with that number. A leading "0x" means that I<number> is hex, as in C<EE<lt>0x201EE<gt>>. A leading "0" means that I<number> is octal, as in C<EE<lt>075E<gt>>. Otherwise I<number> is interpreted as being in decimal, as in C<EE<lt>181E<gt>>. Note that older Pod formatters might not recognize octal or hex numeric escapes, and that many formatters cannot reliably render characters above 255. (Some formatters may even have to use compromised renderings of Latin-1 characters, like rendering C<EE<lt>eacuteE<gt>> as just a plain "e".) =back =item C<FE<lt>filenameE<gt>> -- used for filenames X<F> X<< FZ<><> >> X<POD, formatting code, filename> X<filename> Typically displayed in italics. Example: "C<FE<lt>.cshrcE<gt>>" =item C<SE<lt>textE<gt>> -- text contains non-breaking spaces X<S> X<< SZ<><> >> X<POD, formatting code, non-breaking space> X<non-breaking space> This means that the words in I<text> should not be broken across lines. Example: S<C<SE<lt>$x ? $y : $zE<gt>>>. =item C<XE<lt>topic nameE<gt>> -- an index entry X<X> X<< XZ<><> >> X<POD, formatting code, index entry> X<index entry> This is ignored by most formatters, but some may use it for building indexes. It always renders as empty-string. Example: C<XE<lt>absolutizing relative URLsE<gt>> =item C<ZE<lt>E<gt>> -- a null (zero-effect) formatting code X<Z> X<< ZZ<><> >> X<POD, formatting code, null> X<null> This is rarely used. It's one way to get around using an EE<lt>...E<gt> code sometimes. For example, instead of "C<NEE<lt>ltE<gt>3>" (for "NE<lt>3") you could write "C<NZE<lt>E<gt>E<lt>3>" (the "ZE<lt>E<gt>" breaks up the "N" and the "E<lt>" so they can't be considered the part of a (fictitious) "NE<lt>...E<gt>" code. =for comment This was formerly explained as a "zero-width character". But it in most parser models, it parses to nothing at all, as opposed to parsing as if it were a E<zwnj> or E<zwj>, which are REAL zero-width characters. So "width" and "character" are exactly the wrong words. =back Most of the time, you will need only a single set of angle brackets to delimit the beginning and end of formatting codes. However, sometimes you will want to put a real right angle bracket (a greater-than sign, '>') inside of a formatting code. This is particularly common when using a formatting code to provide a different font-type for a snippet of code. As with all things in Perl, there is more than one way to do it. One way is to simply escape the closing bracket using an C<E> code: C<$a E<lt>=E<gt> $b> This will produce: "C<$a E<lt>=E<gt> $b>" A more readable, and perhaps more "plain" way is to use an alternate set of delimiters that doesn't require a single ">" to be escaped. Doubled angle brackets ("<<" and ">>") may be used I<if and only if there is whitespace right after the opening delimiter and whitespace right before the closing delimiter!> For example, the following will do the trick: X<POD, formatting code, escaping with multiple brackets> C<< $a <=> $b >> In fact, you can use as many repeated angle-brackets as you like so long as you have the same number of them in the opening and closing delimiters, and make sure that whitespace immediately follows the last '<' of the opening delimiter, and immediately precedes the first '>' of the closing delimiter. (The whitespace is ignored.) So the following will also work: X<POD, formatting code, escaping with multiple brackets> C<<< $a <=> $b >>> C<<<< $a <=> $b >>>> And they all mean exactly the same as this: C<$a E<lt>=E<gt> $b> The multiple-bracket form does not affect the interpretation of the contents of the formatting code, only how it must end. That means that the examples above are also exactly the same as this: C<< $a E<lt>=E<gt> $b >> As a further example, this means that if you wanted to put these bits of code in C<C> (code) style: open(X, ">>thing.dat") || die $! $foo->bar(); you could do it like so: C<<< open(X, ">>thing.dat") || die $! >>> C<< $foo->bar(); >> which is presumably easier to read than the old way: C<open(X, "E<gt>E<gt>thing.dat") || die $!> C<$foo-E<gt>bar();> This is currently supported by pod2text (Pod::Text), pod2man (Pod::Man), and any other pod2xxx or Pod::Xxxx translators that use Pod::Parser 1.093 or later, or Pod::Tree 1.02 or later. =head2 The Intent X<POD, intent of> The intent is simplicity of use, not power of expression. Paragraphs look like paragraphs (block format), so that they stand out visually, and so that I could run them through C<fmt> easily to reformat them (that's F7 in my version of B<vi>, or Esc Q in my version of B<emacs>). I wanted the translator to always leave the C<'> and C<`> and C<"> quotes alone, in verbatim mode, so I could slurp in a working program, shift it over four spaces, and have it print out, er, verbatim. And presumably in a monospace font. The Pod format is not necessarily sufficient for writing a book. Pod is just meant to be an idiot-proof common source for nroff, HTML, TeX, and other markup languages, as used for online documentation. Translators exist for B<pod2text>, B<pod2html>, B<pod2man> (that's for nroff(1) and troff(1)), B<pod2latex>, and B<pod2fm>. Various others are available in CPAN. =head2 Embedding Pods in Perl Modules X<POD, embedding> You can embed Pod documentation in your Perl modules and scripts. Start your documentation with an empty line, a "=head1" command at the beginning, and end it with a "=cut" command and an empty line. Perl will ignore the Pod text. See any of the supplied library modules for examples. If you're going to put your Pod at the end of the file, and you're using an __END__ or __DATA__ cut mark, make sure to put an empty line there before the first Pod command. __END__ =head1 NAME Time::Local - efficiently compute time from local and GMT time Without that empty line before the "=head1", many translators wouldn't have recognized the "=head1" as starting a Pod block. =head2 Hints for Writing Pod =over =item * X<podchecker> X<POD, validating> The B<podchecker> command is provided for checking Pod syntax for errors and warnings. For example, it checks for completely blank lines in Pod blocks and for unknown commands and formatting codes. You should still also pass your document through one or more translators and proofread the result, or print out the result and proofread that. Some of the problems found may be bugs in the translators, which you may or may not wish to work around. =item * If you're more familiar with writing in HTML than with writing in Pod, you can try your hand at writing documentation in simple HTML, and converting it to Pod with the experimental L<Pod::HTML2Pod|Pod::HTML2Pod> module, (available in CPAN), and looking at the resulting code. The experimental L<Pod::PXML|Pod::PXML> module in CPAN might also be useful. =item * Many older Pod translators require the lines before every Pod command and after every Pod command (including "=cut"!) to be a blank line. Having something like this: # - - - - - - - - - - - - =item $firecracker->boom() This noisily detonates the firecracker object. =cut sub boom { ... ...will make such Pod translators completely fail to see the Pod block at all. Instead, have it like this: # - - - - - - - - - - - - =item $firecracker->boom() This noisily detonates the firecracker object. =cut sub boom { ... =item * Some older Pod translators require paragraphs (including command paragraphs like "=head2 Functions") to be separated by I<completely> empty lines. If you have an apparently empty line with some spaces on it, this might not count as a separator for those translators, and that could cause odd formatting. =item * Older translators might add wording around an LE<lt>E<gt> link, so that C<LE<lt>Foo::BarE<gt>> may become "the Foo::Bar manpage", for example. So you shouldn't write things like C<the LE<lt>fooE<gt> documentation>, if you want the translated document to read sensibly. Instead, write C<the LE<lt>Foo::Bar|Foo::BarE<gt> documentation> or C<LE<lt>the Foo::Bar documentation|Foo::BarE<gt>>, to control how the link comes out. =item * Going past the 70th column in a verbatim block might be ungracefully wrapped by some formatters. =back =head1 SEE ALSO L<perlpodspec>, L<perlsyn/"PODs: Embedded Documentation">, L<perlnewmod>, L<perldoc>, L<pod2html>, L<pod2man>, L<podchecker>. =head1 AUTHOR Larry Wall, Sean M. Burke =cut PK PU�\��u perl5162delta.podnu �[��� =encoding utf8 =head1 NAME perl5162delta - what is new for perl v5.16.2 =head1 DESCRIPTION This document describes differences between the 5.16.1 release and the 5.16.2 release. If you are upgrading from an earlier release such as 5.16.0, first read L<perl5161delta>, which describes differences between 5.16.0 and 5.16.1. =head1 Incompatible Changes There are no changes intentionally incompatible with 5.16.0 If any exist, they are bugs, and we request that you submit a report. See L</Reporting Bugs> below. =head1 Modules and Pragmata =head2 Updated Modules and Pragmata =over 4 =item * L<Module::CoreList> has been upgraded from version 2.70 to version 2.76. =back =head1 Configuration and Compilation =over 4 =item * configuration should no longer be confused by ls colorization =back =head1 Platform Support =head2 Platform-Specific Notes =over 4 =item AIX Configure now always adds -qlanglvl=extc99 to the CC flags on AIX when using xlC. This will make it easier to compile a number of XS-based modules that assume C99 [perl #113778]. =back =head1 Selected Bug Fixes =over 4 =item * fix /\h/ equivalence with /[\h]/ see [perl #114220] =back =head1 Known Problems There are no new known problems. =head1 Acknowledgements Perl 5.16.2 represents approximately 2 months of development since Perl 5.16.1 and contains approximately 740 lines of changes across 20 files from 9 authors. Perl continues to flourish into its third decade thanks to a vibrant community of users and developers. The following people are known to have contributed the improvements that became Perl 5.16.2: Andy Dougherty, Craig A. Berry, Darin McBride, Dominic Hargreaves, Karen Etheridge, Karl Williamson, Peter Martini, Ricardo Signes, Tony Cook. The list above is almost certainly incomplete as it is automatically generated from version control history. In particular, it does not include the names of the (very much appreciated) contributors who reported issues to the Perl bug tracker. For a more complete list of all of Perl's historical contributors, please see the F<AUTHORS> file in the Perl source distribution. =head1 Reporting Bugs If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup and the perl bug database at http://rt.perl.org/perlbug/ . There may also be information at http://www.perl.org/ , the Perl Home Page. If you believe you have an unreported bug, please run the L<perlbug> program included with your release. Be sure to trim your bug down to a tiny but sufficient test case. Your bug report, along with the output of C<perl -V>, will be sent off to perlbug@perl.org to be analysed by the Perl porting team. If the bug you are reporting has security implications, which make it inappropriate to send to a publicly archived mailing list, then please send it to perl5-security-report@perl.org. This points to a closed subscription unarchived mailing list, which includes all the core committers, who will be able to help assess the impact of issues, figure out a resolution, and help co-ordinate the release of patches to mitigate or fix the problem across all platforms on which Perl is supported. Please only use this address for security issues in the Perl core, not for modules independently distributed on CPAN. =head1 SEE ALSO The F<Changes> file for an explanation of how to view exhaustive details on what changed. The F<INSTALL> file for how to build Perl. The F<README> file for general stuff. The F<Artistic> and F<Copying> files for copyright information. =cut PK PU�\��h� h� perlfaq7.podnu �[��� =head1 NAME perlfaq7 - General Perl Language Issues =head1 DESCRIPTION This section deals with general Perl language issues that don't clearly fit into any of the other sections. =head2 Can I get a BNF/yacc/RE for the Perl language? There is no BNF, but you can paw your way through the yacc grammar in perly.y in the source distribution if you're particularly brave. The grammar relies on very smart tokenizing code, so be prepared to venture into toke.c as well. In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF. The work of parsing perl is distributed between yacc, the lexer, smoke and mirrors." =head2 What are all these $@%&* punctuation signs, and how do I know when to use them? They are type specifiers, as detailed in L<perldata>: $ for scalar values (number, string or reference) @ for arrays % for hashes (associative arrays) & for subroutines (aka functions, procedures, methods) * for all types of that symbol name. In version 4 you used them like pointers, but in modern perls you can just use references. There are a couple of other symbols that you're likely to encounter that aren't really type specifiers: <> are used for inputting a record from a filehandle. \ takes a reference to something. Note that <FILE> is I<neither> the type specifier for files nor the name of the handle. It is the C<< <> >> operator applied to the handle FILE. It reads one line (well, record--see L<perlvar/$E<sol>>) from the handle FILE in scalar context, or I<all> lines in list context. When performing open, close, or any other operation besides C<< <> >> on files, or even when talking about the handle, do I<not> use the brackets. These are correct: C<eof(FH)>, C<seek(FH, 0, 2)> and "copying from STDIN to FILE". =head2 Do I always/never have to quote my strings or use semicolons and commas? Normally, a bareword doesn't need to be quoted, but in most cases probably should be (and must be under C<use strict>). But a hash key consisting of a simple word and the left-hand operand to the C<< => >> operator both count as though they were quoted: This is like this ------------ --------------- $foo{line} $foo{'line'} bar => stuff 'bar' => stuff The final semicolon in a block is optional, as is the final comma in a list. Good style (see L<perlstyle>) says to put them in except for one-liners: if ($whoops) { exit 1 } my @nums = (1, 2, 3); if ($whoops) { exit 1; } my @lines = ( "There Beren came from mountains cold", "And lost he wandered under leaves", ); =head2 How do I skip some return values? One way is to treat the return values as a list and index into it: $dir = (getpwnam($user))[7]; Another way is to use undef as an element on the left-hand-side: ($dev, $ino, undef, undef, $uid, $gid) = stat($file); You can also use a list slice to select only the elements that you need: ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5]; =head2 How do I temporarily block warnings? If you are running Perl 5.6.0 or better, the C<use warnings> pragma allows fine control of what warnings are produced. See L<perllexwarn> for more details. { no warnings; # temporarily turn off warnings $x = $y + $z; # I know these might be undef } Additionally, you can enable and disable categories of warnings. You turn off the categories you want to ignore and you can still get other categories of warnings. See L<perllexwarn> for the complete details, including the category names and hierarchy. { no warnings 'uninitialized'; $x = $y + $z; } If you have an older version of Perl, the C<$^W> variable (documented in L<perlvar>) controls runtime warnings for a block: { local $^W = 0; # temporarily turn off warnings $x = $y + $z; # I know these might be undef } Note that like all the punctuation variables, you cannot currently use my() on C<$^W>, only local(). =head2 What's an extension? An extension is a way of calling compiled C code from Perl. Reading L<perlxstut> is a good place to learn more about extensions. =head2 Why do Perl operators have different precedence than C operators? Actually, they don't. All C operators that Perl copies have the same precedence in Perl as they do in C. The problem is with operators that C doesn't have, especially functions that give a list context to everything on their right, eg. print, chmod, exec, and so on. Such functions are called "list operators" and appear as such in the precedence table in L<perlop>. A common mistake is to write: unlink $file || die "snafu"; This gets interpreted as: unlink ($file || die "snafu"); To avoid this problem, either put in extra parentheses or use the super low precedence C<or> operator: (unlink $file) || die "snafu"; unlink $file or die "snafu"; The "English" operators (C<and>, C<or>, C<xor>, and C<not>) deliberately have precedence lower than that of list operators for just such situations as the one above. Another operator with surprising precedence is exponentiation. It binds more tightly even than unary minus, making C<-2**2> produce a negative four and not a positive one. It is also right-associating, meaning that C<2**3**2> is two raised to the ninth power, not eight squared. Although it has the same precedence as in C, Perl's C<?:> operator produces an lvalue. This assigns $x to either $if_true or $if_false, depending on the trueness of $maybe: ($maybe ? $if_true : $if_false) = $x; =head2 How do I declare/create a structure? In general, you don't "declare" a structure. Just use a (probably anonymous) hash reference. See L<perlref> and L<perldsc> for details. Here's an example: $person = {}; # new anonymous hash $person->{AGE} = 24; # set field AGE to 24 $person->{NAME} = "Nat"; # set field NAME to "Nat" If you're looking for something a bit more rigorous, try L<perltoot>. =head2 How do I create a module? L<perlnewmod> is a good place to start, ignore the bits about uploading to CPAN if you don't want to make your module publicly available. L<ExtUtils::ModuleMaker> and L<Module::Starter> are also good places to start. Many CPAN authors now use L<Dist::Zilla> to automate as much as possible. Detailed documentation about modules can be found at: L<perlmod>, L<perlmodlib>, L<perlmodstyle>. If you need to include C code or C library interfaces use h2xs. h2xs will create the module distribution structure and the initial interface files. L<perlxs> and L<perlxstut> explain the details. =head2 How do I adopt or take over a module already on CPAN? Ask the current maintainer to make you a co-maintainer or transfer the module to you. If you can not reach the author for some reason contact the PAUSE admins at modules@perl.org who may be able to help, but each case it treated seperatly. =over 4 =item * Get a login for the Perl Authors Upload Server (PAUSE) if you don't already have one: L<http://pause.perl.org> =item * Write to modules@perl.org explaining what you did to contact the current maintainer. The PAUSE admins will also try to reach the maintainer. =item * Post a public message in a heavily trafficked site announcing your intention to take over the module. =item * Wait a bit. The PAUSE admins don't want to act too quickly in case the current maintainer is on holiday. If there's no response to private communication or the public post, a PAUSE admin can transfer it to you. =back =head2 How do I create a class? X<class, creation> X<package> (contributed by brian d foy) In Perl, a class is just a package, and methods are just subroutines. Perl doesn't get more formal than that and lets you set up the package just the way that you like it (that is, it doesn't set up anything for you). The Perl documentation has several tutorials that cover class creation, including L<perlboot> (Barnyard Object Oriented Tutorial), L<perltoot> (Tom's Object Oriented Tutorial), L<perlbot> (Bag o' Object Tricks), and L<perlobj>. =head2 How can I tell if a variable is tainted? You can use the tainted() function of the Scalar::Util module, available from CPAN (or included with Perl since release 5.8.0). See also L<perlsec/"Laundering and Detecting Tainted Data">. =head2 What's a closure? Closures are documented in L<perlref>. I<Closure> is a computer science term with a precise but hard-to-explain meaning. Usually, closures are implemented in Perl as anonymous subroutines with lasting references to lexical variables outside their own scopes. These lexicals magically refer to the variables that were around when the subroutine was defined (deep binding). Closures are most often used in programming languages where you can have the return value of a function be itself a function, as you can in Perl. Note that some languages provide anonymous functions but are not capable of providing proper closures: the Python language, for example. For more information on closures, check out any textbook on functional programming. Scheme is a language that not only supports but encourages closures. Here's a classic non-closure function-generating function: sub add_function_generator { return sub { shift() + shift() }; } my $add_sub = add_function_generator(); my $sum = $add_sub->(4,5); # $sum is 9 now. The anonymous subroutine returned by add_function_generator() isn't technically a closure because it refers to no lexicals outside its own scope. Using a closure gives you a I<function template> with some customization slots left out to be filled later. Contrast this with the following make_adder() function, in which the returned anonymous function contains a reference to a lexical variable outside the scope of that function itself. Such a reference requires that Perl return a proper closure, thus locking in for all time the value that the lexical had when the function was created. sub make_adder { my $addpiece = shift; return sub { shift() + $addpiece }; } my $f1 = make_adder(20); my $f2 = make_adder(555); Now C<< $f1->($n) >> is always 20 plus whatever $n you pass in, whereas C<< $f2->($n) >> is always 555 plus whatever $n you pass in. The $addpiece in the closure sticks around. Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function: my $line; timeout( 30, sub { $line = <STDIN> } ); If the code to execute had been passed in as a string, C<< '$line = <STDIN>' >>, there would have been no way for the hypothetical timeout() function to access the lexical variable $line back in its caller's scope. Another use for a closure is to make a variable I<private> to a named subroutine, e.g. a counter that gets initialized at creation time of the sub and can only be modified from within the sub. This is sometimes used with a BEGIN block in package files to make sure a variable doesn't get meddled with during the lifetime of the package: BEGIN { my $id = 0; sub next_id { ++$id } } This is discussed in more detail in L<perlsub>; see the entry on I<Persistent Private Variables>. =head2 What is variable suicide and how can I prevent it? This problem was fixed in perl 5.004_05, so preventing it means upgrading your version of perl. ;) Variable suicide is when you (temporarily or permanently) lose the value of a variable. It is caused by scoping through my() and local() interacting with either closures or aliased foreach() iterator variables and subroutine arguments. It used to be easy to inadvertently lose a variable's value this way, but now it's much harder. Take this code: my $f = 'foo'; sub T { while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" } } T; print "Finally $f\n"; If you are experiencing variable suicide, that C<my $f> in the subroutine doesn't pick up a fresh copy of the C<$f> whose value is C<'foo'>. The output shows that inside the subroutine the value of C<$f> leaks through when it shouldn't, as in this output: foobar foobarbar foobarbarbar Finally foo The $f that has "bar" added to it three times should be a new C<$f> C<my $f> should create a new lexical variable each time through the loop. The expected output is: foobar foobar foobar Finally foo =head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}? You need to pass references to these objects. See L<perlsub/"Pass by Reference"> for this particular question, and L<perlref> for information on references. =over 4 =item Passing Variables and Functions Regular variables and functions are quite easy to pass: just pass in a reference to an existing or anonymous variable or function: func( \$some_scalar ); func( \@some_array ); func( [ 1 .. 10 ] ); func( \%some_hash ); func( { this => 10, that => 20 } ); func( \&some_func ); func( sub { $_[0] ** $_[1] } ); =item Passing Filehandles As of Perl 5.6, you can represent filehandles with scalar variables which you treat as any other scalar. open my $fh, $filename or die "Cannot open $filename! $!"; func( $fh ); sub func { my $passed_fh = shift; my $line = <$passed_fh>; } Before Perl 5.6, you had to use the C<*FH> or C<\*FH> notations. These are "typeglobs"--see L<perldata/"Typeglobs and Filehandles"> and especially L<perlsub/"Pass by Reference"> for more information. =item Passing Regexes Here's an example of how to pass in a string and a regular expression for it to match against. You construct the pattern with the C<qr//> operator: sub compare($$) { my ($val1, $regex) = @_; my $retval = $val1 =~ /$regex/; return $retval; } $match = compare("old McDonald", qr/d.*D/i); =item Passing Methods To pass an object method into a subroutine, you can do this: call_a_lot(10, $some_obj, "methname") sub call_a_lot { my ($count, $widget, $trick) = @_; for (my $i = 0; $i < $count; $i++) { $widget->$trick(); } } Or, you can use a closure to bundle up the object, its method call, and arguments: my $whatnot = sub { $some_obj->obfuscate(@args) }; func($whatnot); sub func { my $code = shift; &$code(); } You could also investigate the can() method in the UNIVERSAL class (part of the standard perl distribution). =back =head2 How do I create a static variable? (contributed by brian d foy) In Perl 5.10, declare the variable with C<state>. The C<state> declaration creates the lexical variable that persists between calls to the subroutine: sub counter { state $count = 1; $count++ } You can fake a static variable by using a lexical variable which goes out of scope. In this example, you define the subroutine C<counter>, and it uses the lexical variable C<$count>. Since you wrap this in a BEGIN block, C<$count> is defined at compile-time, but also goes out of scope at the end of the BEGIN block. The BEGIN block also ensures that the subroutine and the value it uses is defined at compile-time so the subroutine is ready to use just like any other subroutine, and you can put this code in the same place as other subroutines in the program text (i.e. at the end of the code, typically). The subroutine C<counter> still has a reference to the data, and is the only way you can access the value (and each time you do, you increment the value). The data in chunk of memory defined by C<$count> is private to C<counter>. BEGIN { my $count = 1; sub counter { $count++ } } my $start = counter(); .... # code that calls counter(); my $end = counter(); In the previous example, you created a function-private variable because only one function remembered its reference. You could define multiple functions while the variable is in scope, and each function can share the "private" variable. It's not really "static" because you can access it outside the function while the lexical variable is in scope, and even create references to it. In this example, C<increment_count> and C<return_count> share the variable. One function adds to the value and the other simply returns the value. They can both access C<$count>, and since it has gone out of scope, there is no other way to access it. BEGIN { my $count = 1; sub increment_count { $count++ } sub return_count { $count } } To declare a file-private variable, you still use a lexical variable. A file is also a scope, so a lexical variable defined in the file cannot be seen from any other file. See L<perlsub/"Persistent Private Variables"> for more information. The discussion of closures in L<perlref> may help you even though we did not use anonymous subroutines in this answer. See L<perlsub/"Persistent Private Variables"> for details. =head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()? C<local($x)> saves away the old value of the global variable C<$x> and assigns a new value for the duration of the subroutine I<which is visible in other functions called from that subroutine>. This is done at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables. C<my($x)> creates a new variable that is only visible in the current subroutine. This is done at compile-time, so it is called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables. For instance: sub visible { print "var has value $var\n"; } sub dynamic { local $var = 'local'; # new temporary value for the still-global visible(); # variable called $var } sub lexical { my $var = 'private'; # new private variable, $var visible(); # (invisible outside of sub scope) } $var = 'global'; visible(); # prints global dynamic(); # prints local lexical(); # prints global Notice how at no point does the value "private" get printed. That's because $var only has that value within the block of the lexical() function, and it is hidden from the called subroutine. In summary, local() doesn't make what you think of as private, local variables. It gives a global variable a temporary value. my() is what you're looking for if you want private variables. See L<perlsub/"Private Variables via my()"> and L<perlsub/"Temporary Values via local()"> for excruciating details. =head2 How can I access a dynamic variable while a similarly named lexical is in scope? If you know your package, you can just mention it explicitly, as in $Some_Pack::var. Note that the notation $::var is B<not> the dynamic $var in the current package, but rather the one in the "main" package, as though you had written $main::var. use vars '$var'; local $var = "global"; my $var = "lexical"; print "lexical is $var\n"; print "global is $main::var\n"; Alternatively you can use the compiler directive our() to bring a dynamic variable into the current lexical scope. require 5.006; # our() did not exist before 5.6 use vars '$var'; local $var = "global"; my $var = "lexical"; print "lexical is $var\n"; { our $var; print "global is $var\n"; } =head2 What's the difference between deep and shallow binding? In deep binding, lexical variables mentioned in anonymous subroutines are the same ones that were in scope when the subroutine was created. In shallow binding, they are whichever variables with the same names happen to be in scope when the subroutine is called. Perl always uses deep binding of lexical variables (i.e., those created with my()). However, dynamic variables (aka global, local, or package variables) are effectively shallowly bound. Consider this just one more reason not to use them. See the answer to L<"What's a closure?">. =head2 Why doesn't "my($foo) = E<lt>$fhE<gt>;" work right? C<my()> and C<local()> give list context to the right hand side of C<=>. The <$fh> read operation, like so many of Perl's functions and operators, can tell which context it was called in and behaves appropriately. In general, the scalar() function can help. This function does nothing to the data itself (contrary to popular myth) but rather tells its argument to behave in whatever its scalar fashion is. If that function doesn't have a defined scalar behavior, this of course doesn't help you (such as with sort()). To enforce scalar context in this particular case, however, you need merely omit the parentheses: local($foo) = <$fh>; # WRONG local($foo) = scalar(<$fh>); # ok local $foo = <$fh>; # right You should probably be using lexical variables anyway, although the issue is the same here: my($foo) = <$fh>; # WRONG my $foo = <$fh>; # right =head2 How do I redefine a builtin function, operator, or method? Why do you want to do that? :-) If you want to override a predefined function, such as open(), then you'll have to import the new definition from a different module. See L<perlsub/"Overriding Built-in Functions">. If you want to overload a Perl operator, such as C<+> or C<**>, then you'll want to use the C<use overload> pragma, documented in L<overload>. If you're talking about obscuring method calls in parent classes, see L<perltoot/"Overridden Methods">. =head2 What's the difference between calling a function as &foo and foo()? (contributed by brian d foy) Calling a subroutine as C<&foo> with no trailing parentheses ignores the prototype of C<foo> and passes it the current value of the argument list, C<@_>. Here's an example; the C<bar> subroutine calls C<&foo>, which prints its arguments list: sub bar { &foo } sub foo { print "Args in foo are: @_\n" } bar( qw( a b c ) ); When you call C<bar> with arguments, you see that C<foo> got the same C<@_>: Args in foo are: a b c Calling the subroutine with trailing parentheses, with or without arguments, does not use the current C<@_> and respects the subroutine prototype. Changing the example to put parentheses after the call to C<foo> changes the program: sub bar { &foo() } sub foo { print "Args in foo are: @_\n" } bar( qw( a b c ) ); Now the output shows that C<foo> doesn't get the C<@_> from its caller. Args in foo are: The main use of the C<@_> pass-through feature is to write subroutines whose main job it is to call other subroutines for you. For further details, see L<perlsub>. =head2 How do I create a switch or case statement? In Perl 5.10, use the C<given-when> construct described in L<perlsyn>: use 5.010; given ( $string ) { when( 'Fred' ) { say "I found Fred!" } when( 'Barney' ) { say "I found Barney!" } when( /Bamm-?Bamm/ ) { say "I found Bamm-Bamm!" } default { say "I don't recognize the name!" } }; If one wants to use pure Perl and to be compatible with Perl versions prior to 5.10, the general answer is to use C<if-elsif-else>: for ($variable_to_test) { if (/pat1/) { } # do something elsif (/pat2/) { } # do something else elsif (/pat3/) { } # do something else else { } # default } Here's a simple example of a switch based on pattern matching, lined up in a way to make it look more like a switch statement. We'll do a multiway conditional based on the type of reference stored in $whatchamacallit: SWITCH: for (ref $whatchamacallit) { /^$/ && die "not a reference"; /SCALAR/ && do { print_scalar($$ref); last SWITCH; }; /ARRAY/ && do { print_array(@$ref); last SWITCH; }; /HASH/ && do { print_hash(%$ref); last SWITCH; }; /CODE/ && do { warn "can't print function ref"; last SWITCH; }; # DEFAULT warn "User defined type skipped"; } See L<perlsyn> for other examples in this style. Sometimes you should change the positions of the constant and the variable. For example, let's say you wanted to test which of many answers you were given, but in a case-insensitive way that also allows abbreviations. You can use the following technique if the strings all start with different characters or if you want to arrange the matches so that one takes precedence over another, as C<"SEND"> has precedence over C<"STOP"> here: chomp($answer = <>); if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" } elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" } elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" } elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" } elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" } A totally different approach is to create a hash of function references. my %commands = ( "happy" => \&joy, "sad", => \&sullen, "done" => sub { die "See ya!" }, "mad" => \&angry, ); print "How are you? "; chomp($string = <STDIN>); if ($commands{$string}) { $commands{$string}->(); } else { print "No such command: $string\n"; } Starting from Perl 5.8, a source filter module, C<Switch>, can also be used to get switch and case. Its use is now discouraged, because it's not fully compatible with the native switch of Perl 5.10, and because, as it's implemented as a source filter, it doesn't always work as intended when complex syntax is involved. =head2 How can I catch accesses to undefined variables, functions, or methods? The AUTOLOAD method, discussed in L<perlsub/"Autoloading"> and L<perltoot/"AUTOLOAD: Proxy Methods">, lets you capture calls to undefined functions and methods. When it comes to undefined variables that would trigger a warning under C<use warnings>, you can promote the warning to an error. use warnings FATAL => qw(uninitialized); =head2 Why can't a method included in this same file be found? Some possible reasons: your inheritance is getting confused, you've misspelled the method name, or the object is of the wrong type. Check out L<perltoot> for details about any of the above cases. You may also use C<print ref($object)> to find out the class C<$object> was blessed into. Another possible reason for problems is that you've used the indirect object syntax (eg, C<find Guru "Samy">) on a class name before Perl has seen that such a package exists. It's wisest to make sure your packages are all defined before you start using them, which will be taken care of if you use the C<use> statement instead of C<require>. If not, make sure to use arrow notation (eg., C<< Guru->find("Samy") >>) instead. Object notation is explained in L<perlobj>. Make sure to read about creating modules in L<perlmod> and the perils of indirect objects in L<perlobj/"Method Invocation">. =head2 How can I find out my current or calling package? (contributed by brian d foy) To find the package you are currently in, use the special literal C<__PACKAGE__>, as documented in L<perldata>. You can only use the special literals as separate tokens, so you can't interpolate them into strings like you can with variables: my $current_package = __PACKAGE__; print "I am in package $current_package\n"; If you want to find the package calling your code, perhaps to give better diagnostics as L<Carp> does, use the C<caller> built-in: sub foo { my @args = ...; my( $package, $filename, $line ) = caller; print "I was called from package $package\n"; ); By default, your program starts in package C<main>, so you will always be in some package. This is different from finding out the package an object is blessed into, which might not be the current package. For that, use C<blessed> from L<Scalar::Util>, part of the Standard Library since Perl 5.8: use Scalar::Util qw(blessed); my $object_package = blessed( $object ); Most of the time, you shouldn't care what package an object is blessed into, however, as long as it claims to inherit from that class: my $is_right_class = eval { $object->isa( $package ) }; # true or false And, with Perl 5.10 and later, you don't have to check for an inheritance to see if the object can handle a role. For that, you can use C<DOES>, which comes from C<UNIVERSAL>: my $class_does_it = eval { $object->DOES( $role ) }; # true or false You can safely replace C<isa> with C<DOES> (although the converse is not true). =head2 How can I comment out a large block of Perl code? (contributed by brian d foy) The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the C<#> comments). You end the comment with C<=cut>, ending the Pod section: =pod my $object = NotGonnaHappen->new(); ignored_sub(); $wont_be_assigned = 37; =cut The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, you're multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well. The C<=begin> directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with C<comment>. End the comment using C<=end> with the same label. You still need the C<=cut> to go back to Perl code from the Pod comment: =begin comment my $object = NotGonnaHappen->new(); ignored_sub(); $wont_be_assigned = 37; =end comment =cut For more information on Pod, check out L<perlpod> and L<perlpodspec>. =head2 How do I clear a package? Use this code, provided by Mark-Jason Dominus: sub scrub_package { no strict 'refs'; my $pack = shift; die "Shouldn't delete main package" if $pack eq "" || $pack eq "main"; my $stash = *{$pack . '::'}{HASH}; my $name; foreach $name (keys %$stash) { my $fullname = $pack . '::' . $name; # Get rid of everything with that name. undef $$fullname; undef @$fullname; undef %$fullname; undef &$fullname; undef *$fullname; } } Or, if you're using a recent release of Perl, you can just use the Symbol::delete_package() function instead. =head2 How can I use a variable as a variable name? Beginners often think they want to have a variable contain the name of a variable. $fred = 23; $varname = "fred"; ++$$varname; # $fred now 24 This works I<sometimes>, but it is a very bad idea for two reasons. The first reason is that this technique I<only works on global variables>. That means that if $fred is a lexical variable created with my() in the above example, the code wouldn't work at all: you'd accidentally access the global and skip right over the private lexical altogether. Global variables are bad because they can easily collide accidentally and in general make for non-scalable and confusing code. Symbolic references are forbidden under the C<use strict> pragma. They are not true references and consequently are not reference-counted or garbage-collected. The other reason why using a variable to hold the name of another variable is a bad idea is that the question often stems from a lack of understanding of Perl data structures, particularly hashes. By using symbolic references, you are just using the package's symbol-table hash (like C<%main::>) instead of a user-defined hash. The solution is to use your own hash or a real reference instead. $USER_VARS{"fred"} = 23; my $varname = "fred"; $USER_VARS{$varname}++; # not $$varname++ There we're using the %USER_VARS hash instead of symbolic references. Sometimes this comes up in reading strings from the user with variable references and wanting to expand them to the values of your perl program's variables. This is also a bad idea because it conflates the program-addressable namespace and the user-addressable one. Instead of reading a string and expanding it to the actual contents of your program's own variables: $str = 'this has a $fred and $barney in it'; $str =~ s/(\$\w+)/$1/eeg; # need double eval it would be better to keep a hash around like %USER_VARS and have variable references actually refer to entries in that hash: $str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all That's faster, cleaner, and safer than the previous approach. Of course, you don't need to use a dollar sign. You could use your own scheme to make it less confusing, like bracketed percent symbols, etc. $str = 'this has a %fred% and %barney% in it'; $str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all Another reason that folks sometimes think they want a variable to contain the name of a variable is that they don't know how to build proper data structures using hashes. For example, let's say they wanted two hashes in their program: %fred and %barney, and that they wanted to use another scalar variable to refer to those by name. $name = "fred"; $$name{WIFE} = "wilma"; # set %fred $name = "barney"; $$name{WIFE} = "betty"; # set %barney This is still a symbolic reference, and is still saddled with the problems enumerated above. It would be far better to write: $folks{"fred"}{WIFE} = "wilma"; $folks{"barney"}{WIFE} = "betty"; And just use a multilevel hash to start with. The only times that you absolutely I<must> use symbolic references are when you really must refer to the symbol table. This may be because it's something that one can't take a real reference to, such as a format name. Doing so may also be important for method calls, since these always go through the symbol table for resolution. In those cases, you would turn off C<strict 'refs'> temporarily so you can play around with the symbol table. For example: @colors = qw(red blue green yellow orange purple violet); for my $name (@colors) { no strict 'refs'; # renege for the block *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; } All those functions (red(), blue(), green(), etc.) appear to be separate, but the real code in the closure actually was compiled only once. So, sometimes you might want to use symbolic references to manipulate the symbol table directly. This doesn't matter for formats, handles, and subroutines, because they are always global--you can't use my() on them. For scalars, arrays, and hashes, though--and usually for subroutines-- you probably only want to use hard references. =head2 What does "bad interpreter" mean? (contributed by brian d foy) The "bad interpreter" message comes from the shell, not perl. The actual message may vary depending on your platform, shell, and locale settings. If you see "bad interpreter - no such file or directory", the first line in your perl script (the "shebang" line) does not contain the right path to perl (or any other program capable of running scripts). Sometimes this happens when you move the script from one machine to another and each machine has a different path to perl--/usr/bin/perl versus /usr/local/bin/perl for instance. It may also indicate that the source machine has CRLF line terminators and the destination machine has LF only: the shell tries to find /usr/bin/perl<CR>, but can't. If you see "bad interpreter: Permission denied", you need to make your script executable. In either case, you should still be able to run the scripts with perl explicitly: % perl script.pl If you get a message like "perl: command not found", perl is not in your PATH, which might also mean that the location of perl is not where you expect it so you need to adjust your shebang line. =head1 AUTHOR AND COPYRIGHT Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved. This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. PK PU�\�э�+ �+ perlnewmod.podnu �[��� =head1 NAME perlnewmod - preparing a new module for distribution =head1 DESCRIPTION This document gives you some suggestions about how to go about writing Perl modules, preparing them for distribution, and making them available via CPAN. One of the things that makes Perl really powerful is the fact that Perl hackers tend to want to share the solutions to problems they've faced, so you and I don't have to battle with the same problem again. The main way they do this is by abstracting the solution into a Perl module. If you don't know what one of these is, the rest of this document isn't going to be much use to you. You're also missing out on an awful lot of useful code; consider having a look at L<perlmod>, L<perlmodlib> and L<perlmodinstall> before coming back here. When you've found that there isn't a module available for what you're trying to do, and you've had to write the code yourself, consider packaging up the solution into a module and uploading it to CPAN so that others can benefit. =head2 Warning We're going to primarily concentrate on Perl-only modules here, rather than XS modules. XS modules serve a rather different purpose, and you should consider different things before distributing them - the popularity of the library you are gluing, the portability to other operating systems, and so on. However, the notes on preparing the Perl side of the module and packaging and distributing it will apply equally well to an XS module as a pure-Perl one. =head2 What should I make into a module? You should make a module out of any code that you think is going to be useful to others. Anything that's likely to fill a hole in the communal library and which someone else can slot directly into their program. Any part of your code which you can isolate and extract and plug into something else is a likely candidate. Let's take an example. Suppose you're reading in data from a local format into a hash-of-hashes in Perl, turning that into a tree, walking the tree and then piping each node to an Acme Transmogrifier Server. Now, quite a few people have the Acme Transmogrifier, and you've had to write something to talk the protocol from scratch - you'd almost certainly want to make that into a module. The level at which you pitch it is up to you: you might want protocol-level modules analogous to L<Net::SMTP|Net::SMTP> which then talk to higher level modules analogous to L<Mail::Send|Mail::Send>. The choice is yours, but you do want to get a module out for that server protocol. Nobody else on the planet is going to talk your local data format, so we can ignore that. But what about the thing in the middle? Building tree structures from Perl variables and then traversing them is a nice, general problem, and if nobody's already written a module that does that, you might want to modularise that code too. So hopefully you've now got a few ideas about what's good to modularise. Let's now see how it's done. =head2 Step-by-step: Preparing the ground Before we even start scraping out the code, there are a few things we'll want to do in advance. =over 3 =item Look around Dig into a bunch of modules to see how they're written. I'd suggest starting with L<Text::Tabs|Text::Tabs>, since it's in the standard library and is nice and simple, and then looking at something a little more complex like L<File::Copy|File::Copy>. For object oriented code, C<WWW::Mechanize> or the C<Email::*> modules provide some good examples. These should give you an overall feel for how modules are laid out and written. =item Check it's new There are a lot of modules on CPAN, and it's easy to miss one that's similar to what you're planning on contributing. Have a good plough through the L<http://search.cpan.org> and make sure you're not the one reinventing the wheel! =item Discuss the need You might love it. You might feel that everyone else needs it. But there might not actually be any real demand for it out there. If you're unsure about the demand your module will have, consider sending out feelers on the C<comp.lang.perl.modules> newsgroup, or as a last resort, ask the modules list at C<modules@perl.org>. Remember that this is a closed list with a very long turn-around time - be prepared to wait a good while for a response from them. =item Choose a name Perl modules included on CPAN have a naming hierarchy you should try to fit in with. See L<perlmodlib> for more details on how this works, and browse around CPAN and the modules list to get a feel of it. At the very least, remember this: modules should be title capitalised, (This::Thing) fit in with a category, and explain their purpose succinctly. =item Check again While you're doing that, make really sure you haven't missed a module similar to the one you're about to write. When you've got your name sorted out and you're sure that your module is wanted and not currently available, it's time to start coding. =back =head2 Step-by-step: Making the module =over 3 =item Start with F<module-starter> or F<h2xs> The F<module-starter> utility is distributed as part of the L<Module::Starter|Module::Starter> CPAN package. It creates a directory with stubs of all the necessary files to start a new module, according to recent "best practice" for module development, and is invoked from the command line, thus: module-starter --module=Foo::Bar \ --author="Your Name" --email=yourname@cpan.org If you do not wish to install the L<Module::Starter|Module::Starter> package from CPAN, F<h2xs> is an older tool, originally intended for the development of XS modules, which comes packaged with the Perl distribution. A typical invocation of L<h2xs|h2xs> for a pure Perl module is: h2xs -AX --skip-exporter --use-new-tests -n Foo::Bar The C<-A> omits the Autoloader code, C<-X> omits XS elements, C<--skip-exporter> omits the Exporter code, C<--use-new-tests> sets up a modern testing environment, and C<-n> specifies the name of the module. =item Use L<strict|strict> and L<warnings|warnings> A module's code has to be warning and strict-clean, since you can't guarantee the conditions that it'll be used under. Besides, you wouldn't want to distribute code that wasn't warning or strict-clean anyway, right? =item Use L<Carp|Carp> The L<Carp|Carp> module allows you to present your error messages from the caller's perspective; this gives you a way to signal a problem with the caller and not your module. For instance, if you say this: warn "No hostname given"; the user will see something like this: No hostname given at /usr/local/lib/perl5/site_perl/5.6.0/Net/Acme.pm line 123. which looks like your module is doing something wrong. Instead, you want to put the blame on the user, and say this: No hostname given at bad_code, line 10. You do this by using L<Carp|Carp> and replacing your C<warn>s with C<carp>s. If you need to C<die>, say C<croak> instead. However, keep C<warn> and C<die> in place for your sanity checks - where it really is your module at fault. =item Use L<Exporter|Exporter> - wisely! L<Exporter|Exporter> gives you a standard way of exporting symbols and subroutines from your module into the caller's namespace. For instance, saying C<use Net::Acme qw(&frob)> would import the C<frob> subroutine. The package variable C<@EXPORT> will determine which symbols will get exported when the caller simply says C<use Net::Acme> - you will hardly ever want to put anything in there. C<@EXPORT_OK>, on the other hand, specifies which symbols you're willing to export. If you do want to export a bunch of symbols, use the C<%EXPORT_TAGS> and define a standard export set - look at L<Exporter> for more details. =item Use L<plain old documentation|perlpod> The work isn't over until the paperwork is done, and you're going to need to put in some time writing some documentation for your module. C<module-starter> or C<h2xs> will provide a stub for you to fill in; if you're not sure about the format, look at L<perlpod> for an introduction. Provide a good synopsis of how your module is used in code, a description, and then notes on the syntax and function of the individual subroutines or methods. Use Perl comments for developer notes and POD for end-user notes. =item Write tests You're encouraged to create self-tests for your module to ensure it's working as intended on the myriad platforms Perl supports; if you upload your module to CPAN, a host of testers will build your module and send you the results of the tests. Again, C<module-starter> and C<h2xs> provide a test framework which you can extend - you should do something more than just checking your module will compile. L<Test::Simple|Test::Simple> and L<Test::More|Test::More> are good places to start when writing a test suite. =item Write the README If you're uploading to CPAN, the automated gremlins will extract the README file and place that in your CPAN directory. It'll also appear in the main F<by-module> and F<by-category> directories if you make it onto the modules list. It's a good idea to put here what the module actually does in detail, and the user-visible changes since the last release. =back =head2 Step-by-step: Distributing your module =over 3 =item Get a CPAN user ID Every developer publishing modules on CPAN needs a CPAN ID. Visit C<http://pause.perl.org/>, select "Request PAUSE Account", and wait for your request to be approved by the PAUSE administrators. =item C<perl Makefile.PL; make test; make dist> Once again, C<module-starter> or C<h2xs> has done all the work for you. They produce the standard C<Makefile.PL> you see when you download and install modules, and this produces a Makefile with a C<dist> target. Once you've ensured that your module passes its own tests - always a good thing to make sure - you can C<make dist>, and the Makefile will hopefully produce you a nice tarball of your module, ready for upload. =item Upload the tarball The email you got when you received your CPAN ID will tell you how to log in to PAUSE, the Perl Authors Upload SErver. From the menus there, you can upload your module to CPAN. =item Announce to the modules list Once uploaded, it'll sit unnoticed in your author directory. If you want it connected to the rest of the CPAN, you'll need to go to "Register Namespace" on PAUSE. Once registered, your module will appear in the by-module and by-category listings on CPAN. =item Announce to clpa If you have a burning desire to tell the world about your release, post an announcement to the moderated C<comp.lang.perl.announce> newsgroup. =item Fix bugs! Once you start accumulating users, they'll send you bug reports. If you're lucky, they'll even send you patches. Welcome to the joys of maintaining a software project... =back =head1 AUTHOR Simon Cozens, C<simon@cpan.org> Updated by Kirrily "Skud" Robert, C<skud@cpan.org> =head1 SEE ALSO L<perlmod>, L<perlmodlib>, L<perlmodinstall>, L<h2xs>, L<strict>, L<Carp>, L<Exporter>, L<perlpod>, L<Test::Simple>, L<Test::More> L<ExtUtils::MakeMaker>, L<Module::Build>, L<Module::Starter> http://www.cpan.org/ , Ken Williams's tutorial on building your own module at http://mathforum.org/~ken/perl_modules.html PK PU�\@N���l �l perlcygwin.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see F<pod/perlpod.pod>) which is specially designed to be readable as is. =head1 NAME perlcygwin - Perl for Cygwin =head1 SYNOPSIS This document will help you configure, make, test and install Perl on Cygwin. This document also describes features of Cygwin that will affect how Perl behaves at runtime. B<NOTE:> There are pre-built Perl packages available for Cygwin and a version of Perl is provided in the normal Cygwin install. If you do not need to customize the configuration, consider using one of those packages. =head1 PREREQUISITES FOR COMPILING PERL ON CYGWIN =head2 Cygwin = GNU+Cygnus+Windows (Don't leave UNIX without it) The Cygwin tools are ports of the popular GNU development tools for Win32 platforms. They run thanks to the Cygwin library which provides the UNIX system calls and environment these programs expect. More information about this project can be found at: L<http://www.cygwin.com/> A recent net or commercial release of Cygwin is required. At the time this document was last updated, Cygwin 1.7.10 was current. =head2 Cygwin Configuration While building Perl some changes may be necessary to your Cygwin setup so that Perl builds cleanly. These changes are B<not> required for normal Perl usage. B<NOTE:> The binaries that are built will run on all Win32 versions. They do not depend on your host system (WinXP/Win2K/Win7) or your Cygwin configuration (binary/text mounts, cvgserver). The only dependencies come from hard-coded pathnames like C</usr/local>. However, your host system and Cygwin configuration will affect Perl's runtime behavior (see L</"TEST">). =over 4 =item * C<PATH> Set the C<PATH> environment variable so that Configure finds the Cygwin versions of programs. Any not-needed Windows directories should be removed or moved to the end of your C<PATH>. =item * I<nroff> If you do not have I<nroff> (which is part of the I<groff> package), Configure will B<not> prompt you to install I<man> pages. =back =head1 CONFIGURE PERL ON CYGWIN The default options gathered by Configure with the assistance of F<hints/cygwin.sh> will build a Perl that supports dynamic loading (which requires a shared F<cygperl5_16.dll>). This will run Configure and keep a record: ./Configure 2>&1 | tee log.configure If you are willing to accept all the defaults run Configure with B<-de>. However, several useful customizations are available. =head2 Stripping Perl Binaries on Cygwin It is possible to strip the EXEs and DLLs created by the build process. The resulting binaries will be significantly smaller. If you want the binaries to be stripped, you can either add a B<-s> option when Configure prompts you, Any additional ld flags (NOT including libraries)? [none] -s Any special flags to pass to g++ to create a dynamically loaded library? [none] -s Any special flags to pass to gcc to use dynamic linking? [none] -s or you can edit F<hints/cygwin.sh> and uncomment the relevant variables near the end of the file. =head2 Optional Libraries for Perl on Cygwin Several Perl functions and modules depend on the existence of some optional libraries. Configure will find them if they are installed in one of the directories listed as being used for library searches. Pre-built packages for most of these are available from the Cygwin installer. =over 4 =item * C<-lcrypt> The crypt package distributed with Cygwin is a Linux compatible 56-bit DES crypt port by Corinna Vinschen. Alternatively, the crypt libraries in GNU libc have been ported to Cygwin. =item * C<-lgdbm_compat> (C<use GDBM_File>) GDBM is available for Cygwin. NOTE: The GDBM library only works on NTFS partitions. =item * C<-ldb> (C<use DB_File>) BerkeleyDB is available for Cygwin. NOTE: The BerkeleyDB library only completely works on NTFS partitions. =item * C<cygserver> (C<use IPC::SysV>) A port of SysV IPC is available for Cygwin. NOTE: This has B<not> been extensively tested. In particular, C<d_semctl_semun> is undefined because it fails a Configure test and on Win9x the I<shm*()> functions seem to hang. It also creates a compile time dependency because F<perl.h> includes F<<sys/ipc.h>> and F<<sys/sem.h>> (which will be required in the future when compiling CPAN modules). CURRENTLY NOT SUPPORTED! =item * C<-lutil> Included with the standard Cygwin netrelease is the inetutils package which includes libutil.a. =back =head2 Configure-time Options for Perl on Cygwin The F<INSTALL> document describes several Configure-time options. Some of these will work with Cygwin, others are not yet possible. Also, some of these are experimental. You can either select an option when Configure prompts you or you can define (undefine) symbols on the command line. =over 4 =item * C<-Uusedl> Undefining this symbol forces Perl to be compiled statically. =item * C<-Dusemymalloc> By default Perl does not use the C<malloc()> included with the Perl source, because it was slower and not entirely thread-safe. If you want to force Perl to build with the old -Dusemymalloc define this. =item * C<-Uuseperlio> Undefining this symbol disables the PerlIO abstraction. PerlIO is now the default; it is not recommended to disable PerlIO. =item * C<-Dusemultiplicity> Multiplicity is required when embedding Perl in a C program and using more than one interpreter instance. This is only required when you build a not-threaded perl with C<-Uuseithreads>. =item * C<-Uuse64bitint> By default Perl uses 64 bit integers. If you want to use smaller 32 bit integers, define this symbol. =item * C<-Duselongdouble> I<gcc> supports long doubles (12 bytes). However, several additional long double math functions are necessary to use them within Perl (I<{atan2, cos, exp, floor, fmod, frexp, isnan, log, modf, pow, sin, sqrt}l, strtold>). These are B<not> yet available with newlib, the Cygwin libc. =item * C<-Uuseithreads> Define this symbol if you want not-threaded faster perl. =item * C<-Duselargefiles> Cygwin uses 64-bit integers for internal size and position calculations, this will be correctly detected and defined by Configure. =item * C<-Dmksymlinks> Use this to build perl outside of the source tree. Details can be found in the F<INSTALL> document. This is the recommended way to build perl from sources. =back =head2 Suspicious Warnings on Cygwin You may see some messages during Configure that seem suspicious. =over 4 =item * Win9x and C<d_eofnblk> Win9x does not correctly report C<EOF> with a non-blocking read on a closed pipe. You will see the following messages: But it also returns -1 to signal EOF, so be careful! WARNING: you can't distinguish between EOF and no data! *** WHOA THERE!!! *** The recommended value for $d_eofnblk on this machine was "define"! Keep the recommended value? [y] At least for consistency with WinNT, you should keep the recommended value. =item * Compiler/Preprocessor defines The following error occurs because of the Cygwin C<#define> of C<_LONG_DOUBLE>: Guessing which symbols your C compiler and preprocessor define... try.c:<line#>: missing binary operator This failure does not seem to cause any problems. With older gcc versions, "parse error" is reported instead of "missing binary operator". =back =head1 MAKE ON CYGWIN Simply run I<make> and wait: make 2>&1 | tee log.make =head1 TEST ON CYGWIN There are two steps to running the test suite: make test 2>&1 | tee log.make-test cd t; ./perl harness 2>&1 | tee ../log.harness The same tests are run both times, but more information is provided when running as C<./perl harness>. Test results vary depending on your host system and your Cygwin configuration. If a test can pass in some Cygwin setup, it is always attempted and explainable test failures are documented. It is possible for Perl to pass all the tests, but it is more likely that some tests will fail for one of the reasons listed below. =head2 File Permissions on Cygwin UNIX file permissions are based on sets of mode bits for {read,write,execute} for each {user,group,other}. By default Cygwin only tracks the Win32 read-only attribute represented as the UNIX file user write bit (files are always readable, files are executable if they have a F<.{com,bat,exe}> extension or begin with C<#!>, directories are always readable and executable). On WinNT with the I<ntea> C<CYGWIN> setting, the additional mode bits are stored as extended file attributes. On WinNT with the default I<ntsec> C<CYGWIN> setting, permissions use the standard WinNT security descriptors and access control lists. Without one of these options, these tests will fail (listing not updated yet): Failed Test List of failed ------------------------------------ io/fs.t 5, 7, 9-10 lib/anydbm.t 2 lib/db-btree.t 20 lib/db-hash.t 16 lib/db-recno.t 18 lib/gdbm.t 2 lib/ndbm.t 2 lib/odbm.t 2 lib/sdbm.t 2 op/stat.t 9, 20 (.tmp not an executable extension) =head2 NDBM_File and ODBM_File do not work on FAT filesystems Do not use NDBM_File or ODBM_File on FAT filesystem. They can be built on a FAT filesystem, but many tests will fail: ../ext/NDBM_File/ndbm.t 13 3328 71 59 83.10% 1-2 4 16-71 ../ext/ODBM_File/odbm.t 255 65280 ?? ?? % ?? ../lib/AnyDBM_File.t 2 512 12 2 16.67% 1 4 ../lib/Memoize/t/errors.t 0 139 11 5 45.45% 7-11 ../lib/Memoize/t/tie_ndbm.t 13 3328 4 4 100.00% 1-4 run/fresh_perl.t 97 1 1.03% 91 If you intend to run only on FAT (or if using AnyDBM_File on FAT), run Configure with the -Ui_ndbm and -Ui_dbm options to prevent NDBM_File and ODBM_File being built. With NTFS (and no CYGWIN=nontsec), there should be no problems even if perl was built on FAT. =head2 C<fork()> failures in io_* tests A C<fork()> failure may result in the following tests failing: ext/IO/lib/IO/t/io_multihomed.t ext/IO/lib/IO/t/io_sock.t ext/IO/lib/IO/t/io_unix.t See comment on fork in L</Miscellaneous> below. =head1 Specific features of the Cygwin port =head2 Script Portability on Cygwin Cygwin does an outstanding job of providing UNIX-like semantics on top of Win32 systems. However, in addition to the items noted above, there are some differences that you should know about. This is a very brief guide to portability, more information can be found in the Cygwin documentation. =over 4 =item * Pathnames Cygwin pathnames are separated by forward (F</>) slashes, Universal Naming Codes (F<//UNC>) are also supported Since cygwin-1.7 non-POSIX pathnames are disencouraged. Names may contain all printable characters. File names are case insensitive, but case preserving. A pathname that contains a backslash or drive letter is a Win32 pathname, and not subject to the translations applied to POSIX style pathnames, but cygwin will warn you, so better convert them to POSIX. For conversion we have C<Cygwin::win_to_posix_path()> and C<Cygwin::posix_to_win_path()>. Since cygwin-1.7 pathnames are UTF-8 encoded. =item * Text/Binary Since cywgin-1.7 textmounts are deprecated and stronlgy discouraged. When a file is opened it is in either text or binary mode. In text mode a file is subject to CR/LF/Ctrl-Z translations. With Cygwin, the default mode for an C<open()> is determined by the mode of the mount that underlies the file. See L</Cygwin::is_binmount>(). Perl provides a C<binmode()> function to set binary mode on files that otherwise would be treated as text. C<sysopen()> with the C<O_TEXT> flag sets text mode on files that otherwise would be treated as binary: sysopen(FOO, "bar", O_WRONLY|O_CREAT|O_TEXT) C<lseek()>, C<tell()> and C<sysseek()> only work with files opened in binary mode. The text/binary issue is covered at length in the Cygwin documentation. =item * PerlIO PerlIO overrides the default Cygwin Text/Binary behaviour. A file will always be treated as binary, regardless of the mode of the mount it lives on, just like it is in UNIX. So CR/LF translation needs to be requested in either the C<open()> call like this: open(FH, ">:crlf", "out.txt"); which will do conversion from LF to CR/LF on the output, or in the environment settings (add this to your .bashrc): export PERLIO=crlf which will pull in the crlf PerlIO layer which does LF -> CRLF conversion on every output generated by perl. =item * F<.exe> The Cygwin C<stat()>, C<lstat()> and C<readlink()> functions make the F<.exe> extension transparent by looking for F<foo.exe> when you ask for F<foo> (unless a F<foo> also exists). Cygwin does not require a F<.exe> extension, but I<gcc> adds it automatically when building a program. However, when accessing an executable as a normal file (e.g., I<cp> in a makefile) the F<.exe> is not transparent. The I<install> program included with Cygwin automatically appends a F<.exe> when necessary. =item * Cygwin vs. Windows process ids Cygwin processes have their own pid, which is different from the underlying windows pid. Most posix compliant Proc functions expect the cygwin pid, but several Win32::Process functions expect the winpid. E.g. C<$$> is the cygwin pid of F</usr/bin/perl>, which is not the winpid. Use C<Cygwin::winpid_to_pid()> and C<Cygwin::winpid_to_pid()> to translate between them. =item * Cygwin vs. Windows errors Under Cygwin, $^E is the same as $!. When using L<Win32 API Functions|Win32>, use C<Win32::GetLastError()> to get the last Windows error. =item * rebase errors on fork or system Using C<fork()> or C<system()> out to another perl after loading multiple dlls may result on a DLL baseaddress conflict. The internal cygwin error looks like like the following: 0 [main] perl 8916 child_info_fork::abort: data segment start: parent (0xC1A000) != child(0xA6A000) or: 183 [main] perl 3588 C:\cygwin\bin\perl.exe: *** fatal error - unable to remap C:\cygwin\bin\cygsvn_subr-1-0.dll to same address as parent(0x6FB30000) != 0x6FE60000 46 [main] perl 3488 fork: child 3588 - died waiting for dll loading, errno11 See L<http://cygwin.com/faq/faq-nochunks.html#faq.using.fixing-fork-failures> It helps if not too many DLLs are loaded in memory so the available address space is larger, e.g. stopping the MS Internet Explorer might help. Use the perlrebase or rebase utilities to resolve the conflicting dll addresses. The rebase package is included in the Cygwin setup. Use F<setup.exe> from L<http://www.cygwin.com/setup.exe> to install it. 1. kill all perl processes and run C<perlrebase> or 2. kill all cygwin processes and services, start dash from cmd.exe and run C<rebaseall>. =item * C<chown()> On WinNT C<chown()> can change a file's user and group IDs. On Win9x C<chown()> is a no-op, although this is appropriate since there is no security model. =item * Miscellaneous File locking using the C<F_GETLK> command to C<fcntl()> is a stub that returns C<ENOSYS>. Win9x can not C<rename()> an open file (although WinNT can). The Cygwin C<chroot()> implementation has holes (it can not restrict file access by native Win32 programs). Inplace editing C<perl -i> of files doesn't work without doing a backup of the file being edited C<perl -i.bak> because of windowish restrictions, therefore Perl adds the suffix C<.bak> automatically if you use C<perl -i> without specifying a backup extension. =back =head2 Prebuilt methods: =over 4 =item C<Cwd::cwd> Returns the current working directory. =item C<Cygwin::pid_to_winpid> Translates a cygwin pid to the corresponding Windows pid (which may or may not be the same). =item C<Cygwin::winpid_to_pid> Translates a Windows pid to the corresponding cygwin pid (if any). =item C<Cygwin::win_to_posix_path> Translates a Windows path to the corresponding cygwin path respecting the current mount points. With a second non-null argument returns an absolute path. Double-byte characters will not be translated. =item C<Cygwin::posix_to_win_path> Translates a cygwin path to the corresponding cygwin path respecting the current mount points. With a second non-null argument returns an absolute path. Double-byte characters will not be translated. =item C<Cygwin::mount_table()> Returns an array of [mnt_dir, mnt_fsname, mnt_type, mnt_opts]. perl -e 'for $i (Cygwin::mount_table) {print join(" ",@$i),"\n";}' /bin c:\cygwin\bin system binmode,cygexec /usr/bin c:\cygwin\bin system binmode /usr/lib c:\cygwin\lib system binmode / c:\cygwin system binmode /cygdrive/c c: system binmode,noumount /cygdrive/d d: system binmode,noumount /cygdrive/e e: system binmode,noumount =item C<Cygwin::mount_flags> Returns the mount type and flags for a specified mount point. A comma-separated string of mntent->mnt_type (always "system" or "user"), then the mntent->mnt_opts, where the first is always "binmode" or "textmode". system|user,binmode|textmode,exec,cygexec,cygdrive,mixed, notexec,managed,nosuid,devfs,proc,noumount If the argument is "/cygdrive", then just the volume mount settings, and the cygdrive mount prefix are returned. User mounts override system mounts. $ perl -e 'print Cygwin::mount_flags "/usr/bin"' system,binmode,cygexec $ perl -e 'print Cygwin::mount_flags "/cygdrive"' binmode,cygdrive,/cygdrive =item C<Cygwin::is_binmount> Returns true if the given cygwin path is binary mounted, false if the path is mounted in textmode. =item C<Cygwin::sync_winenv> Cygwin does not initialize all original Win32 environment variables. See the bottom of this page L<http://cygwin.com/cygwin-ug-net/setup-env.html> for "Restricted Win32 environment". Certain Win32 programs called from cygwin programs might need some environment variable, such as e.g. ADODB needs %COMMONPROGRAMFILES%. Call Cygwin::sync_winenv() to copy all Win32 environment variables to your process and note that cygwin will warn on every encounter of non-POSIX paths. =back =head1 INSTALL PERL ON CYGWIN This will install Perl, including I<man> pages. make install 2>&1 | tee log.make-install NOTE: If C<STDERR> is redirected C<make install> will B<not> prompt you to install I<perl> into F</usr/bin>. You may need to be I<Administrator> to run C<make install>. If you are not, you must have write access to the directories in question. Information on installing the Perl documentation in HTML format can be found in the F<INSTALL> document. =head1 MANIFEST ON CYGWIN These are the files in the Perl release that contain references to Cygwin. These very brief notes attempt to explain the reason for all conditional code. Hopefully, keeping this up to date will allow the Cygwin port to be kept as clean as possible. =over 4 =item Documentation INSTALL README.cygwin README.win32 MANIFEST pod/perl.pod pod/perlport.pod pod/perlfaq3.pod pod/perldelta.pod pod/perl5004delta.pod pod/perl56delta.pod pod/perl561delta.pod pod/perl570delta.pod pod/perl572delta.pod pod/perl573delta.pod pod/perl58delta.pod pod/perl581delta.pod pod/perl590delta.pod pod/perlhist.pod pod/perlmodlib.pod pod/perltoc.pod Porting/Glossary pod/perlgit.pod Porting/checkAUTHORS.pl dist/Cwd/Changes ext/Compress-Raw-Zlib/Changes ext/Compress-Raw-Zlib/README ext/Compress-Zlib/Changes ext/DB_File/Changes ext/Encode/Changes ext/Sys-Syslog/Changes ext/Time-HiRes/Changes ext/Win32API-File/Changes lib/CGI/Changes lib/ExtUtils/CBuilder/Changes lib/ExtUtils/Changes lib/ExtUtils/NOTES lib/ExtUtils/PATCHING lib/ExtUtils/README lib/Module/Build/Changes lib/Net/Ping/Changes lib/Test/Harness/Changes lib/Term/ANSIColor/ChangeLog lib/Term/ANSIColor/README README.symbian symbian/TODO =item Build, Configure, Make, Install cygwin/Makefile.SHs ext/IPC/SysV/hints/cygwin.pl ext/NDBM_File/hints/cygwin.pl ext/ODBM_File/hints/cygwin.pl hints/cygwin.sh Configure - help finding hints from uname, shared libperl required for dynamic loading Makefile.SH Cross/Makefile-cross-SH - linklibperl Porting/patchls - cygwin in port list installman - man pages with :: translated to . installperl - install dll, install to 'pods' makedepend.SH - uwinfix regen_lib.pl - file permissions NetWare/Makefile plan9/mkfile symbian/sanity.pl symbian/sisify.pl hints/uwin.sh vms/descrip_mms.template win32/Makefile win32/makefile.mk =item Tests t/io/fs.t - no file mode checks if not ntsec skip rename() check when not check_case:relaxed t/io/tell.t - binmode t/lib/cygwin.t - builtin cygwin function tests t/op/groups.t - basegroup has ID = 0 t/op/magic.t - $^X/symlink WORKAROUND, s/.exe// t/op/stat.t - no /dev, skip Win32 ftCreationTime quirk (cache manager sometimes preserves ctime of file previously created and deleted), no -u (setuid) t/op/taint.t - can't use empty path under Cygwin Perl t/op/time.t - no tzset() =item Compiled Perl Source EXTERN.h - __declspec(dllimport) XSUB.h - __declspec(dllexport) cygwin/cygwin.c - os_extras (getcwd, spawn, and several Cygwin:: functions) perl.c - os_extras, -i.bak perl.h - binmode doio.c - win9x can not rename a file when it is open pp_sys.c - do not define h_errno, init _pwent_struct.pw_comment util.c - use setenv util.h - PERL_FILE_IS_ABSOLUTE macro pp.c - Comment about Posix vs IEEE math under Cygwin perlio.c - CR/LF mode perliol.c - Comment about EXTCONST under Cygwin =item Compiled Module Source ext/Compress-Raw-Zlib/Makefile.PL - Can't install via CPAN shell under Cygwin ext/Compress-Raw-Zlib/zlib-src/zutil.h - Cygwin is Unix-like and has vsnprintf ext/Errno/Errno_pm.PL - Special handling for Win32 Perl under Cygwin ext/POSIX/POSIX.xs - tzname defined externally ext/SDBM_File/sdbm/pair.c - EXTCONST needs to be redefined from EXTERN.h ext/SDBM_File/sdbm/sdbm.c - binary open ext/Sys/Syslog/Syslog.xs - Cygwin has syslog.h ext/Sys/Syslog/win32/compile.pl - Convert paths to Windows paths ext/Time-HiRes/HiRes.xs - Various timers not available ext/Time-HiRes/Makefile.PL - Find w32api/windows.h ext/Win32/Makefile.PL - Use various libraries under Cygwin ext/Win32/Win32.xs - Child dir and child env under Cygwin ext/Win32API-File/File.xs - _open_osfhandle not implemented under Cygwin ext/Win32CORE/Win32CORE.c - __declspec(dllexport) =item Perl Modules/Scripts ext/B/t/OptreeCheck.pm - Comment about stderr/stdout order under Cygwin ext/Digest-SHA/bin/shasum - Use binary mode under Cygwin ext/Sys/Syslog/win32/Win32.pm - Convert paths to Windows paths ext/Time-HiRes/HiRes.pm - Comment about various timers not available ext/Win32API-File/File.pm - _open_osfhandle not implemented under Cygwin ext/Win32CORE/Win32CORE.pm - History of Win32CORE under Cygwin lib/CGI.pm - binmode and path separator lib/CPANPLUS/Dist/MM.pm - Commented out code that fails under Win32/Cygwin lib/CPANPLUS/Internals/Constants/Report.pm - OS classifications lib/CPANPLUS/Internals/Constants.pm - Constants for Cygwin lib/CPANPLUS/Internals/Report.pm - Example of Cygwin report lib/CPANPLUS/Module.pm - Abort if running on old Cygwin version lib/Cwd.pm - hook to internal Cwd::cwd lib/ExtUtils/CBuilder/Platform/cygwin.pm - use gcc for ld, and link to libperl.dll.a lib/ExtUtils/CBuilder.pm - Cygwin is Unix-like lib/ExtUtils/Install.pm - Install and rename issues under Cygwin lib/ExtUtils/MM.pm - OS classifications lib/ExtUtils/MM_Any.pm - Example for Cygwin lib/ExtUtils/MakeMaker.pm - require MM_Cygwin.pm lib/ExtUtils/MM_Cygwin.pm - canonpath, cflags, manifypods, perl_archive lib/File/Fetch.pm - Comment about quotes using a Cygwin example lib/File/Find.pm - on remote drives stat() always sets st_nlink to 1 lib/File/Spec/Cygwin.pm - case_tolerant lib/File/Spec/Unix.pm - preserve //unc lib/File/Spec/Win32.pm - References a message on cygwin.com lib/File/Spec.pm - Pulls in lib/File/Spec/Cygwin.pm lib/File/Temp.pm - no directory sticky bit lib/Module/Build/Compat.pm - Comment references 'make' under Cygwin lib/Module/Build/Platform/cygwin.pm - Use '.' for man page separator lib/Module/Build.pm - Cygwin is Unix-like lib/Module/CoreList.pm - List of all module files and versions lib/Net/Domain.pm - No domainname command under Cygwin lib/Net/Netrc.pm - Bypass using stat() under Cygwin lib/Net/Ping.pm - ECONREFUSED is EAGAIN under Cygwin lib/Pod/Find.pm - Set 'pods' dir lib/Pod/Perldoc/ToMan.pm - '-c' switch for pod2man lib/Pod/Perldoc.pm - Use 'less' pager, and use .exe extension lib/Term/ANSIColor.pm - Cygwin terminal info lib/perl5db.pl - use stdin not /dev/tty utils/perlbug.PL - Add CYGWIN environment variable to report =item Perl Module Tests dist/Cwd/t/cwd.t ext/Compress-Zlib/t/14gzopen.t ext/DB_File/t/db-btree.t ext/DB_File/t/db-hash.t ext/DB_File/t/db-recno.t ext/DynaLoader/t/DynaLoader.t ext/File-Glob/t/basic.t ext/GDBM_File/t/gdbm.t ext/POSIX/t/sysconf.t ext/POSIX/t/time.t ext/SDBM_File/t/sdbm.t ext/Sys/Syslog/t/syslog.t ext/Time-HiRes/t/HiRes.t ext/Win32/t/Unicode.t ext/Win32API-File/t/file.t ext/Win32CORE/t/win32core.t lib/AnyDBM_File.t lib/Archive/Extract/t/01_Archive-Extract.t lib/Archive/Tar/t/02_methods.t lib/CPANPLUS/t/05_CPANPLUS-Internals-Fetch.t lib/CPANPLUS/t/20_CPANPLUS-Dist-MM.t lib/ExtUtils/t/Embed.t lib/ExtUtils/t/eu_command.t lib/ExtUtils/t/MM_Cygwin.t lib/ExtUtils/t/MM_Unix.t lib/File/Compare.t lib/File/Copy.t lib/File/Find/t/find.t lib/File/Path.t lib/File/Spec/t/crossplatform.t lib/File/Spec/t/Spec.t lib/Module/Build/t/destinations.t lib/Net/hostent.t lib/Net/Ping/t/110_icmp_inst.t lib/Net/Ping/t/500_ping_icmp.t lib/Net/t/netrc.t lib/Pod/Simple/t/perlcyg.pod lib/Pod/Simple/t/perlcygo.txt lib/Pod/Simple/t/perlfaq.pod lib/Pod/Simple/t/perlfaqo.txt lib/User/grent.t lib/User/pwent.t =back =head1 BUGS ON CYGWIN Support for swapping real and effective user and group IDs is incomplete. On WinNT Cygwin provides C<setuid()>, C<seteuid()>, C<setgid()> and C<setegid()>. However, additional Cygwin calls for manipulating WinNT access tokens and security contexts are required. =head1 AUTHORS Charles Wilson <cwilson@ece.gatech.edu>, Eric Fifer <egf7@columbia.edu>, alexander smishlajev <als@turnhere.com>, Steven Morlock <newspost@morlock.net>, Sebastien Barre <Sebastien.Barre@utc.fr>, Teun Burgers <burgers@ecn.nl>, Gerrit P. Haase <gp@familiehaase.de>, Reini Urban <rurban@cpan.org>, Jan Dubois <jand@activestate.com>, Jerry D. Hedden <jdhedden@cpan.org>. =head1 HISTORY Last updated: 2012-02-08 PK PU�\���[ [ perlsec.podnu �[��� =head1 NAME perlsec - Perl security =head1 DESCRIPTION Perl is designed to make it easy to program securely even when running with extra privileges, like setuid or setgid programs. Unlike most command line shells, which are based on multiple substitution passes on each line of the script, Perl uses a more conventional evaluation scheme with fewer hidden snags. Additionally, because the language has more builtin functionality, it can rely less upon external (and possibly untrustworthy) programs to accomplish its purposes. =head1 SECURITY VULNERABILITY CONTACT INFORMATION If you believe you have found a security vulnerability in Perl, please email perl5-security-report@perl.org with details. This points to a closed subscription, unarchived mailing list. Please only use this address for security issues in the Perl core, not for modules independently distributed on CPAN. =head1 SECURITY MECHANISMS AND CONCERNS =head2 Taint mode Perl automatically enables a set of special security checks, called I<taint mode>, when it detects its program running with differing real and effective user or group IDs. The setuid bit in Unix permissions is mode 04000, the setgid bit mode 02000; either or both may be set. You can also enable taint mode explicitly by using the B<-T> command line flag. This flag is I<strongly> suggested for server programs and any program run on behalf of someone else, such as a CGI script. Once taint mode is on, it's on for the remainder of your script. While in this mode, Perl takes special precautions called I<taint checks> to prevent both obvious and subtle traps. Some of these checks are reasonably simple, such as verifying that path directories aren't writable by others; careful programmers have always used checks like these. Other checks, however, are best supported by the language itself, and it is these checks especially that contribute to making a set-id Perl program more secure than the corresponding C program. You may not use data derived from outside your program to affect something else outside your program--at least, not by accident. All command line arguments, environment variables, locale information (see L<perllocale>), results of certain system calls (C<readdir()>, C<readlink()>, the variable of C<shmread()>, the messages returned by C<msgrcv()>, the password, gcos and shell fields returned by the C<getpwxxx()> calls), and all file input are marked as "tainted". Tainted data may not be used directly or indirectly in any command that invokes a sub-shell, nor in any command that modifies files, directories, or processes, B<with the following exceptions>: =over 4 =item * Arguments to C<print> and C<syswrite> are B<not> checked for taintedness. =item * Symbolic methods $obj->$method(@args); and symbolic sub references &{$foo}(@args); $foo->(@args); are not checked for taintedness. This requires extra carefulness unless you want external data to affect your control flow. Unless you carefully limit what these symbolic values are, people are able to call functions B<outside> your Perl code, such as POSIX::system, in which case they are able to run arbitrary external code. =item * Hash keys are B<never> tainted. =back For efficiency reasons, Perl takes a conservative view of whether data is tainted. If an expression contains tainted data, any subexpression may be considered tainted, even if the value of the subexpression is not itself affected by the tainted data. Because taintedness is associated with each scalar value, some elements of an array or hash can be tainted and others not. The keys of a hash are B<never> tainted. For example: $arg = shift; # $arg is tainted $hid = $arg, 'bar'; # $hid is also tainted $line = <>; # Tainted $line = <STDIN>; # Also tainted open FOO, "/home/me/bar" or die $!; $line = <FOO>; # Still tainted $path = $ENV{'PATH'}; # Tainted, but see below $data = 'abc'; # Not tainted system "echo $arg"; # Insecure system "/bin/echo", $arg; # Considered insecure # (Perl doesn't know about /bin/echo) system "echo $hid"; # Insecure system "echo $data"; # Insecure until PATH set $path = $ENV{'PATH'}; # $path now tainted $ENV{'PATH'} = '/bin:/usr/bin'; delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'}; $path = $ENV{'PATH'}; # $path now NOT tainted system "echo $data"; # Is secure now! open(FOO, "< $arg"); # OK - read-only file open(FOO, "> $arg"); # Not OK - trying to write open(FOO,"echo $arg|"); # Not OK open(FOO,"-|") or exec 'echo', $arg; # Also not OK $shout = `echo $arg`; # Insecure, $shout now tainted unlink $data, $arg; # Insecure umask $arg; # Insecure exec "echo $arg"; # Insecure exec "echo", $arg; # Insecure exec "sh", '-c', $arg; # Very insecure! @files = <*.c>; # insecure (uses readdir() or similar) @files = glob('*.c'); # insecure (uses readdir() or similar) # In Perl releases older than 5.6.0 the <*.c> and glob('*.c') would # have used an external program to do the filename expansion; but in # either case the result is tainted since the list of filenames comes # from outside of the program. $bad = ($arg, 23); # $bad will be tainted $arg, `true`; # Insecure (although it isn't really) If you try to do something insecure, you will get a fatal error saying something like "Insecure dependency" or "Insecure $ENV{PATH}". The exception to the principle of "one tainted value taints the whole expression" is with the ternary conditional operator C<?:>. Since code with a ternary conditional $result = $tainted_value ? "Untainted" : "Also untainted"; is effectively if ( $tainted_value ) { $result = "Untainted"; } else { $result = "Also untainted"; } it doesn't make sense for C<$result> to be tainted. =head2 Laundering and Detecting Tainted Data To test whether a variable contains tainted data, and whose use would thus trigger an "Insecure dependency" message, you can use the C<tainted()> function of the Scalar::Util module, available in your nearby CPAN mirror, and included in Perl starting from the release 5.8.0. Or you may be able to use the following C<is_tainted()> function. sub is_tainted { local $@; # Don't pollute caller's value. return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 }; } This function makes use of the fact that the presence of tainted data anywhere within an expression renders the entire expression tainted. It would be inefficient for every operator to test every argument for taintedness. Instead, the slightly more efficient and conservative approach is used that if any tainted value has been accessed within the same expression, the whole expression is considered tainted. But testing for taintedness gets you only so far. Sometimes you have just to clear your data's taintedness. Values may be untainted by using them as keys in a hash; otherwise the only way to bypass the tainting mechanism is by referencing subpatterns from a regular expression match. Perl presumes that if you reference a substring using $1, $2, etc., that you knew what you were doing when you wrote the pattern. That means using a bit of thought--don't just blindly untaint anything, or you defeat the entire mechanism. It's better to verify that the variable has only good characters (for certain values of "good") rather than checking whether it has any bad characters. That's because it's far too easy to miss bad characters that you never thought of. Here's a test to make sure that the data contains nothing but "word" characters (alphabetics, numerics, and underscores), a hyphen, an at sign, or a dot. if ($data =~ /^([-\@\w.]+)$/) { $data = $1; # $data now untainted } else { die "Bad data in '$data'"; # log this somewhere } This is fairly secure because C</\w+/> doesn't normally match shell metacharacters, nor are dot, dash, or at going to mean something special to the shell. Use of C</.+/> would have been insecure in theory because it lets everything through, but Perl doesn't check for that. The lesson is that when untainting, you must be exceedingly careful with your patterns. Laundering data using regular expression is the I<only> mechanism for untainting dirty data, unless you use the strategy detailed below to fork a child of lesser privilege. The example does not untaint C<$data> if C<use locale> is in effect, because the characters matched by C<\w> are determined by the locale. Perl considers that locale definitions are untrustworthy because they contain data from outside the program. If you are writing a locale-aware program, and want to launder data with a regular expression containing C<\w>, put C<no locale> ahead of the expression in the same block. See L<perllocale/SECURITY> for further discussion and examples. =head2 Switches On the "#!" Line When you make a script executable, in order to make it usable as a command, the system will pass switches to perl from the script's #! line. Perl checks that any command line switches given to a setuid (or setgid) script actually match the ones set on the #! line. Some Unix and Unix-like environments impose a one-switch limit on the #! line, so you may need to use something like C<-wU> instead of C<-w -U> under such systems. (This issue should arise only in Unix or Unix-like environments that support #! and setuid or setgid scripts.) =head2 Taint mode and @INC When the taint mode (C<-T>) is in effect, the "." directory is removed from C<@INC>, and the environment variables C<PERL5LIB> and C<PERLLIB> are ignored by Perl. You can still adjust C<@INC> from outside the program by using the C<-I> command line option as explained in L<perlrun>. The two environment variables are ignored because they are obscured, and a user running a program could be unaware that they are set, whereas the C<-I> option is clearly visible and therefore permitted. Another way to modify C<@INC> without modifying the program, is to use the C<lib> pragma, e.g.: perl -Mlib=/foo program The benefit of using C<-Mlib=/foo> over C<-I/foo>, is that the former will automagically remove any duplicated directories, while the later will not. Note that if a tainted string is added to C<@INC>, the following problem will be reported: Insecure dependency in require while running with -T switch =head2 Cleaning Up Your Path For "Insecure C<$ENV{PATH}>" messages, you need to set C<$ENV{'PATH'}> to a known value, and each directory in the path must be absolute and non-writable by others than its owner and group. You may be surprised to get this message even if the pathname to your executable is fully qualified. This is I<not> generated because you didn't supply a full path to the program; instead, it's generated because you never set your PATH environment variable, or you didn't set it to something that was safe. Because Perl can't guarantee that the executable in question isn't itself going to turn around and execute some other program that is dependent on your PATH, it makes sure you set the PATH. The PATH isn't the only environment variable which can cause problems. Because some shells may use the variables IFS, CDPATH, ENV, and BASH_ENV, Perl checks that those are either empty or untainted when starting subprocesses. You may wish to add something like this to your setid and taint-checking scripts. delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; # Make %ENV safer It's also possible to get into trouble with other operations that don't care whether they use tainted values. Make judicious use of the file tests in dealing with any user-supplied filenames. When possible, do opens and such B<after> properly dropping any special user (or group!) privileges. Perl doesn't prevent you from opening tainted filenames for reading, so be careful what you print out. The tainting mechanism is intended to prevent stupid mistakes, not to remove the need for thought. Perl does not call the shell to expand wild cards when you pass C<system> and C<exec> explicit parameter lists instead of strings with possible shell wildcards in them. Unfortunately, the C<open>, C<glob>, and backtick functions provide no such alternate calling convention, so more subterfuge will be required. Perl provides a reasonably safe way to open a file or pipe from a setuid or setgid program: just create a child process with reduced privilege who does the dirty work for you. First, fork a child using the special C<open> syntax that connects the parent and child by a pipe. Now the child resets its ID set and any other per-process attributes, like environment variables, umasks, current working directories, back to the originals or known safe values. Then the child process, which no longer has any special permissions, does the C<open> or other system call. Finally, the child passes the data it managed to access back to the parent. Because the file or pipe was opened in the child while running under less privilege than the parent, it's not apt to be tricked into doing something it shouldn't. Here's a way to do backticks reasonably safely. Notice how the C<exec> is not called with a string that the shell could expand. This is by far the best way to call something that might be subjected to shell escapes: just never call the shell at all. use English '-no_match_vars'; die "Can't fork: $!" unless defined($pid = open(KID, "-|")); if ($pid) { # parent while (<KID>) { # do something } close KID; } else { my @temp = ($EUID, $EGID); my $orig_uid = $UID; my $orig_gid = $GID; $EUID = $UID; $EGID = $GID; # Drop privileges $UID = $orig_uid; $GID = $orig_gid; # Make sure privs are really gone ($EUID, $EGID) = @temp; die "Can't drop privileges" unless $UID == $EUID && $GID eq $EGID; $ENV{PATH} = "/bin:/usr/bin"; # Minimal PATH. # Consider sanitizing the environment even more. exec 'myprog', 'arg1', 'arg2' or die "can't exec myprog: $!"; } A similar strategy would work for wildcard expansion via C<glob>, although you can use C<readdir> instead. Taint checking is most useful when although you trust yourself not to have written a program to give away the farm, you don't necessarily trust those who end up using it not to try to trick it into doing something bad. This is the kind of security checking that's useful for set-id programs and programs launched on someone else's behalf, like CGI programs. This is quite different, however, from not even trusting the writer of the code not to try to do something evil. That's the kind of trust needed when someone hands you a program you've never seen before and says, "Here, run this." For that kind of safety, you might want to check out the Safe module, included standard in the Perl distribution. This module allows the programmer to set up special compartments in which all system operations are trapped and namespace access is carefully controlled. Safe should not be considered bullet-proof, though: it will not prevent the foreign code to set up infinite loops, allocate gigabytes of memory, or even abusing perl bugs to make the host interpreter crash or behave in unpredictable ways. In any case it's better avoided completely if you're really concerned about security. =head2 Security Bugs Beyond the obvious problems that stem from giving special privileges to systems as flexible as scripts, on many versions of Unix, set-id scripts are inherently insecure right from the start. The problem is a race condition in the kernel. Between the time the kernel opens the file to see which interpreter to run and when the (now-set-id) interpreter turns around and reopens the file to interpret it, the file in question may have changed, especially if you have symbolic links on your system. Fortunately, sometimes this kernel "feature" can be disabled. Unfortunately, there are two ways to disable it. The system can simply outlaw scripts with any set-id bit set, which doesn't help much. Alternately, it can simply ignore the set-id bits on scripts. However, if the kernel set-id script feature isn't disabled, Perl will complain loudly that your set-id script is insecure. You'll need to either disable the kernel set-id script feature, or put a C wrapper around the script. A C wrapper is just a compiled program that does nothing except call your Perl program. Compiled programs are not subject to the kernel bug that plagues set-id scripts. Here's a simple wrapper, written in C: #define REAL_PATH "/path/to/script" main(ac, av) char **av; { execv(REAL_PATH, av); } Compile this wrapper into a binary executable and then make I<it> rather than your script setuid or setgid. In recent years, vendors have begun to supply systems free of this inherent security bug. On such systems, when the kernel passes the name of the set-id script to open to the interpreter, rather than using a pathname subject to meddling, it instead passes I</dev/fd/3>. This is a special file already opened on the script, so that there can be no race condition for evil scripts to exploit. On these systems, Perl should be compiled with C<-DSETUID_SCRIPTS_ARE_SECURE_NOW>. The F<Configure> program that builds Perl tries to figure this out for itself, so you should never have to specify this yourself. Most modern releases of SysVr4 and BSD 4.4 use this approach to avoid the kernel race condition. =head2 Protecting Your Programs There are a number of ways to hide the source to your Perl programs, with varying levels of "security". First of all, however, you I<can't> take away read permission, because the source code has to be readable in order to be compiled and interpreted. (That doesn't mean that a CGI script's source is readable by people on the web, though.) So you have to leave the permissions at the socially friendly 0755 level. This lets people on your local system only see your source. Some people mistakenly regard this as a security problem. If your program does insecure things, and relies on people not knowing how to exploit those insecurities, it is not secure. It is often possible for someone to determine the insecure things and exploit them without viewing the source. Security through obscurity, the name for hiding your bugs instead of fixing them, is little security indeed. You can try using encryption via source filters (Filter::* from CPAN, or Filter::Util::Call and Filter::Simple since Perl 5.8). But crackers might be able to decrypt it. You can try using the byte code compiler and interpreter described below, but crackers might be able to de-compile it. You can try using the native-code compiler described below, but crackers might be able to disassemble it. These pose varying degrees of difficulty to people wanting to get at your code, but none can definitively conceal it (this is true of every language, not just Perl). If you're concerned about people profiting from your code, then the bottom line is that nothing but a restrictive license will give you legal security. License your software and pepper it with threatening statements like "This is unpublished proprietary software of XYZ Corp. Your access to it does not give you permission to use it blah blah blah." You should see a lawyer to be sure your license's wording will stand up in court. =head2 Unicode Unicode is a new and complex technology and one may easily overlook certain security pitfalls. See L<perluniintro> for an overview and L<perlunicode> for details, and L<perlunicode/"Security Implications of Unicode"> for security implications in particular. =head2 Algorithmic Complexity Attacks Certain internal algorithms used in the implementation of Perl can be attacked by choosing the input carefully to consume large amounts of either time or space or both. This can lead into the so-called I<Denial of Service> (DoS) attacks. =over 4 =item * Hash Function - the algorithm used to "order" hash elements has been changed several times during the development of Perl, mainly to be reasonably fast. In Perl 5.8.1 also the security aspect was taken into account. In Perls before 5.8.1 one could rather easily generate data that as hash keys would cause Perl to consume large amounts of time because internal structure of hashes would badly degenerate. In Perl 5.8.1 the hash function is randomly perturbed by a pseudorandom seed which makes generating such naughty hash keys harder. See L<perlrun/PERL_HASH_SEED> for more information. In Perl 5.8.1 the random perturbation was done by default, but as of 5.8.2 it is only used on individual hashes if the internals detect the insertion of pathological data. If one wants for some reason emulate the old behaviour (and expose oneself to DoS attacks) one can set the environment variable PERL_HASH_SEED to zero to disable the protection (or any other integer to force a known perturbation, rather than random). One possible reason for wanting to emulate the old behaviour is that in the new behaviour consecutive runs of Perl will order hash keys differently, which may confuse some applications (like Data::Dumper: the outputs of two different runs are no longer identical). B<Perl has never guaranteed any ordering of the hash keys>, and the ordering has already changed several times during the lifetime of Perl 5. Also, the ordering of hash keys has always been, and continues to be, affected by the insertion order. Also note that while the order of the hash elements might be randomised, this "pseudoordering" should B<not> be used for applications like shuffling a list randomly (use List::Util::shuffle() for that, see L<List::Util>, a standard core module since Perl 5.8.0; or the CPAN module Algorithm::Numerical::Shuffle), or for generating permutations (use e.g. the CPAN modules Algorithm::Permute or Algorithm::FastPermute), or for any cryptographic applications. =item * Regular expressions - Perl's regular expression engine is so called NFA (Non-deterministic Finite Automaton), which among other things means that it can rather easily consume large amounts of both time and space if the regular expression may match in several ways. Careful crafting of the regular expressions can help but quite often there really isn't much one can do (the book "Mastering Regular Expressions" is required reading, see L<perlfaq2>). Running out of space manifests itself by Perl running out of memory. =item * Sorting - the quicksort algorithm used in Perls before 5.8.0 to implement the sort() function is very easy to trick into misbehaving so that it consumes a lot of time. Starting from Perl 5.8.0 a different sorting algorithm, mergesort, is used by default. Mergesort cannot misbehave on any input. =back See L<http://www.cs.rice.edu/~scrosby/hash/> for more information, and any computer science textbook on algorithmic complexity. =head1 SEE ALSO L<perlrun> for its description of cleaning up environment variables. PK PU�\�T��� �� perlhacktips.podnu �[��� =encoding utf8 =for comment Consistent formatting of this file is achieved with: perl ./Porting/podtidy pod/perlhacktips.pod =head1 NAME perlhacktips - Tips for Perl core C code hacking =head1 DESCRIPTION This document will help you learn the best way to go about hacking on the Perl core C code. It covers common problems, debugging, profiling, and more. If you haven't read L<perlhack> and L<perlhacktut> yet, you might want to do that first. =head1 COMMON PROBLEMS Perl source plays by ANSI C89 rules: no C99 (or C++) extensions. In some cases we have to take pre-ANSI requirements into consideration. You don't care about some particular platform having broken Perl? I hear there is still a strong demand for J2EE programmers. =head2 Perl environment problems =over 4 =item * Not compiling with threading Compiling with threading (-Duseithreads) completely rewrites the function prototypes of Perl. You better try your changes with that. Related to this is the difference between "Perl_-less" and "Perl_-ly" APIs, for example: Perl_sv_setiv(aTHX_ ...); sv_setiv(...); The first one explicitly passes in the context, which is needed for e.g. threaded builds. The second one does that implicitly; do not get them mixed. If you are not passing in a aTHX_, you will need to do a dTHX (or a dVAR) as the first thing in the function. See L<perlguts/"How multiple interpreters and concurrency are supported"> for further discussion about context. =item * Not compiling with -DDEBUGGING The DEBUGGING define exposes more code to the compiler, therefore more ways for things to go wrong. You should try it. =item * Introducing (non-read-only) globals Do not introduce any modifiable globals, truly global or file static. They are bad form and complicate multithreading and other forms of concurrency. The right way is to introduce them as new interpreter variables, see F<intrpvar.h> (at the very end for binary compatibility). Introducing read-only (const) globals is okay, as long as you verify with e.g. C<nm libperl.a|egrep -v ' [TURtr] '> (if your C<nm> has BSD-style output) that the data you added really is read-only. (If it is, it shouldn't show up in the output of that command.) If you want to have static strings, make them constant: static const char etc[] = "..."; If you want to have arrays of constant strings, note carefully the right combination of C<const>s: static const char * const yippee[] = {"hi", "ho", "silver"}; There is a way to completely hide any modifiable globals (they are all moved to heap), the compilation setting C<-DPERL_GLOBAL_STRUCT_PRIVATE>. It is not normally used, but can be used for testing, read more about it in L<perlguts/"Background and PERL_IMPLICIT_CONTEXT">. =item * Not exporting your new function Some platforms (Win32, AIX, VMS, OS/2, to name a few) require any function that is part of the public API (the shared Perl library) to be explicitly marked as exported. See the discussion about F<embed.pl> in L<perlguts>. =item * Exporting your new function The new shiny result of either genuine new functionality or your arduous refactoring is now ready and correctly exported. So what could possibly go wrong? Maybe simply that your function did not need to be exported in the first place. Perl has a long and not so glorious history of exporting functions that it should not have. If the function is used only inside one source code file, make it static. See the discussion about F<embed.pl> in L<perlguts>. If the function is used across several files, but intended only for Perl's internal use (and this should be the common case), do not export it to the public API. See the discussion about F<embed.pl> in L<perlguts>. =back =head2 Portability problems The following are common causes of compilation and/or execution failures, not common to Perl as such. The C FAQ is good bedtime reading. Please test your changes with as many C compilers and platforms as possible; we will, anyway, and it's nice to save oneself from public embarrassment. If using gcc, you can add the C<-std=c89> option which will hopefully catch most of these unportabilities. (However it might also catch incompatibilities in your system's header files.) Use the Configure C<-Dgccansipedantic> flag to enable the gcc C<-ansi -pedantic> flags which enforce stricter ANSI rules. If using the C<gcc -Wall> note that not all the possible warnings (like C<-Wunitialized>) are given unless you also compile with C<-O>. Note that if using gcc, starting from Perl 5.9.5 the Perl core source code files (the ones at the top level of the source code distribution, but not e.g. the extensions under ext/) are automatically compiled with as many as possible of the C<-std=c89>, C<-ansi>, C<-pedantic>, and a selection of C<-W> flags (see cflags.SH). Also study L<perlport> carefully to avoid any bad assumptions about the operating system, filesystems, and so forth. You may once in a while try a "make microperl" to see whether we can still compile Perl with just the bare minimum of interfaces. (See README.micro.) Do not assume an operating system indicates a certain compiler. =over 4 =item * Casting pointers to integers or casting integers to pointers void castaway(U8* p) { IV i = p; or void castaway(U8* p) { IV i = (IV)p; Both are bad, and broken, and unportable. Use the PTR2IV() macro that does it right. (Likewise, there are PTR2UV(), PTR2NV(), INT2PTR(), and NUM2PTR().) =item * Casting between data function pointers and data pointers Technically speaking casting between function pointers and data pointers is unportable and undefined, but practically speaking it seems to work, but you should use the FPTR2DPTR() and DPTR2FPTR() macros. Sometimes you can also play games with unions. =item * Assuming sizeof(int) == sizeof(long) There are platforms where longs are 64 bits, and platforms where ints are 64 bits, and while we are out to shock you, even platforms where shorts are 64 bits. This is all legal according to the C standard. (In other words, "long long" is not a portable way to specify 64 bits, and "long long" is not even guaranteed to be any wider than "long".) Instead, use the definitions IV, UV, IVSIZE, I32SIZE, and so forth. Avoid things like I32 because they are B<not> guaranteed to be I<exactly> 32 bits, they are I<at least> 32 bits, nor are they guaranteed to be B<int> or B<long>. If you really explicitly need 64-bit variables, use I64 and U64, but only if guarded by HAS_QUAD. =item * Assuming one can dereference any type of pointer for any type of data char *p = ...; long pony = *p; /* BAD */ Many platforms, quite rightly so, will give you a core dump instead of a pony if the p happens not to be correctly aligned. =item * Lvalue casts (int)*p = ...; /* BAD */ Simply not portable. Get your lvalue to be of the right type, or maybe use temporary variables, or dirty tricks with unions. =item * Assume B<anything> about structs (especially the ones you don't control, like the ones coming from the system headers) =over 8 =item * That a certain field exists in a struct =item * That no other fields exist besides the ones you know of =item * That a field is of certain signedness, sizeof, or type =item * That the fields are in a certain order =over 8 =item * While C guarantees the ordering specified in the struct definition, between different platforms the definitions might differ =back =item * That the sizeof(struct) or the alignments are the same everywhere =over 8 =item * There might be padding bytes between the fields to align the fields - the bytes can be anything =item * Structs are required to be aligned to the maximum alignment required by the fields - which for native types is for usually equivalent to sizeof() of the field =back =back =item * Assuming the character set is ASCIIish Perl can compile and run under EBCDIC platforms. See L<perlebcdic>. This is transparent for the most part, but because the character sets differ, you shouldn't use numeric (decimal, octal, nor hex) constants to refer to characters. You can safely say 'A', but not 0x41. You can safely say '\n', but not \012. If a character doesn't have a trivial input form, you can create a #define for it in both C<utfebcdic.h> and C<utf8.h>, so that it resolves to different values depending on the character set being used. (There are three different EBCDIC character sets defined in C<utfebcdic.h>, so it might be best to insert the #define three times in that file.) Also, the range 'A' - 'Z' in ASCII is an unbroken sequence of 26 upper case alphabetic characters. That is not true in EBCDIC. Nor for 'a' to 'z'. But '0' - '9' is an unbroken range in both systems. Don't assume anything about other ranges. Many of the comments in the existing code ignore the possibility of EBCDIC, and may be wrong therefore, even if the code works. This is actually a tribute to the successful transparent insertion of being able to handle EBCDIC without having to change pre-existing code. UTF-8 and UTF-EBCDIC are two different encodings used to represent Unicode code points as sequences of bytes. Macros with the same names (but different definitions) in C<utf8.h> and C<utfebcdic.h> are used to allow the calling code to think that there is only one such encoding. This is almost always referred to as C<utf8>, but it means the EBCDIC version as well. Again, comments in the code may well be wrong even if the code itself is right. For example, the concept of C<invariant characters> differs between ASCII and EBCDIC. On ASCII platforms, only characters that do not have the high-order bit set (i.e. whose ordinals are strict ASCII, 0 - 127) are invariant, and the documentation and comments in the code may assume that, often referring to something like, say, C<hibit>. The situation differs and is not so simple on EBCDIC machines, but as long as the code itself uses the C<NATIVE_IS_INVARIANT()> macro appropriately, it works, even if the comments are wrong. =item * Assuming the character set is just ASCII ASCII is a 7 bit encoding, but bytes have 8 bits in them. The 128 extra characters have different meanings depending on the locale. Absent a locale, currently these extra characters are generally considered to be unassigned, and this has presented some problems. This is being changed starting in 5.12 so that these characters will be considered to be Latin-1 (ISO-8859-1). =item * Mixing #define and #ifdef #define BURGLE(x) ... \ #ifdef BURGLE_OLD_STYLE /* BAD */ ... do it the old way ... \ #else ... do it the new way ... \ #endif You cannot portably "stack" cpp directives. For example in the above you need two separate BURGLE() #defines, one for each #ifdef branch. =item * Adding non-comment stuff after #endif or #else #ifdef SNOSH ... #else !SNOSH /* BAD */ ... #endif SNOSH /* BAD */ The #endif and #else cannot portably have anything non-comment after them. If you want to document what is going (which is a good idea especially if the branches are long), use (C) comments: #ifdef SNOSH ... #else /* !SNOSH */ ... #endif /* SNOSH */ The gcc option C<-Wendif-labels> warns about the bad variant (by default on starting from Perl 5.9.4). =item * Having a comma after the last element of an enum list enum color { CERULEAN, CHARTREUSE, CINNABAR, /* BAD */ }; is not portable. Leave out the last comma. Also note that whether enums are implicitly morphable to ints varies between compilers, you might need to (int). =item * Using //-comments // This function bamfoodles the zorklator. /* BAD */ That is C99 or C++. Perl is C89. Using the //-comments is silently allowed by many C compilers but cranking up the ANSI C89 strictness (which we like to do) causes the compilation to fail. =item * Mixing declarations and code void zorklator() { int n = 3; set_zorkmids(n); /* BAD */ int q = 4; That is C99 or C++. Some C compilers allow that, but you shouldn't. The gcc option C<-Wdeclaration-after-statements> scans for such problems (by default on starting from Perl 5.9.4). =item * Introducing variables inside for() for(int i = ...; ...; ...) { /* BAD */ That is C99 or C++. While it would indeed be awfully nice to have that also in C89, to limit the scope of the loop variable, alas, we cannot. =item * Mixing signed char pointers with unsigned char pointers int foo(char *s) { ... } ... unsigned char *t = ...; /* Or U8* t = ... */ foo(t); /* BAD */ While this is legal practice, it is certainly dubious, and downright fatal in at least one platform: for example VMS cc considers this a fatal error. One cause for people often making this mistake is that a "naked char" and therefore dereferencing a "naked char pointer" have an undefined signedness: it depends on the compiler and the flags of the compiler and the underlying platform whether the result is signed or unsigned. For this very same reason using a 'char' as an array index is bad. =item * Macros that have string constants and their arguments as substrings of the string constants #define FOO(n) printf("number = %d\n", n) /* BAD */ FOO(10); Pre-ANSI semantics for that was equivalent to printf("10umber = %d\10"); which is probably not what you were expecting. Unfortunately at least one reasonably common and modern C compiler does "real backward compatibility" here, in AIX that is what still happens even though the rest of the AIX compiler is very happily C89. =item * Using printf formats for non-basic C types IV i = ...; printf("i = %d\n", i); /* BAD */ While this might by accident work in some platform (where IV happens to be an C<int>), in general it cannot. IV might be something larger. Even worse the situation is with more specific types (defined by Perl's configuration step in F<config.h>): Uid_t who = ...; printf("who = %d\n", who); /* BAD */ The problem here is that Uid_t might be not only not C<int>-wide but it might also be unsigned, in which case large uids would be printed as negative values. There is no simple solution to this because of printf()'s limited intelligence, but for many types the right format is available as with either 'f' or '_f' suffix, for example: IVdf /* IV in decimal */ UVxf /* UV is hexadecimal */ printf("i = %"IVdf"\n", i); /* The IVdf is a string constant. */ Uid_t_f /* Uid_t in decimal */ printf("who = %"Uid_t_f"\n", who); Or you can try casting to a "wide enough" type: printf("i = %"IVdf"\n", (IV)something_very_small_and_signed); Also remember that the C<%p> format really does require a void pointer: U8* p = ...; printf("p = %p\n", (void*)p); The gcc option C<-Wformat> scans for such problems. =item * Blindly using variadic macros gcc has had them for a while with its own syntax, and C99 brought them with a standardized syntax. Don't use the former, and use the latter only if the HAS_C99_VARIADIC_MACROS is defined. =item * Blindly passing va_list Not all platforms support passing va_list to further varargs (stdarg) functions. The right thing to do is to copy the va_list using the Perl_va_copy() if the NEED_VA_COPY is defined. =item * Using gcc statement expressions val = ({...;...;...}); /* BAD */ While a nice extension, it's not portable. The Perl code does admittedly use them if available to gain some extra speed (essentially as a funky form of inlining), but you shouldn't. =item * Binding together several statements in a macro Use the macros STMT_START and STMT_END. STMT_START { ... } STMT_END =item * Testing for operating systems or versions when should be testing for features #ifdef __FOONIX__ /* BAD */ foo = quux(); #endif Unless you know with 100% certainty that quux() is only ever available for the "Foonix" operating system B<and> that is available B<and> correctly working for B<all> past, present, B<and> future versions of "Foonix", the above is very wrong. This is more correct (though still not perfect, because the below is a compile-time check): #ifdef HAS_QUUX foo = quux(); #endif How does the HAS_QUUX become defined where it needs to be? Well, if Foonix happens to be Unixy enough to be able to run the Configure script, and Configure has been taught about detecting and testing quux(), the HAS_QUUX will be correctly defined. In other platforms, the corresponding configuration step will hopefully do the same. In a pinch, if you cannot wait for Configure to be educated, or if you have a good hunch of where quux() might be available, you can temporarily try the following: #if (defined(__FOONIX__) || defined(__BARNIX__)) # define HAS_QUUX #endif ... #ifdef HAS_QUUX foo = quux(); #endif But in any case, try to keep the features and operating systems separate. =back =head2 Problematic System Interfaces =over 4 =item * malloc(0), realloc(0), calloc(0, 0) are non-portable. To be portable allocate at least one byte. (In general you should rarely need to work at this low level, but instead use the various malloc wrappers.) =item * snprintf() - the return type is unportable. Use my_snprintf() instead. =back =head2 Security problems Last but not least, here are various tips for safer coding. =over 4 =item * Do not use gets() Or we will publicly ridicule you. Seriously. =item * Do not use strcpy() or strcat() or strncpy() or strncat() Use my_strlcpy() and my_strlcat() instead: they either use the native implementation, or Perl's own implementation (borrowed from the public domain implementation of INN). =item * Do not use sprintf() or vsprintf() If you really want just plain byte strings, use my_snprintf() and my_vsnprintf() instead, which will try to use snprintf() and vsnprintf() if those safer APIs are available. If you want something fancier than a plain byte string, use SVs and Perl_sv_catpvf(). =back =head1 DEBUGGING You can compile a special debugging version of Perl, which allows you to use the C<-D> option of Perl to tell more about what Perl is doing. But sometimes there is no alternative than to dive in with a debugger, either to see the stack trace of a core dump (very useful in a bug report), or trying to figure out what went wrong before the core dump happened, or how did we end up having wrong or unexpected results. =head2 Poking at Perl To really poke around with Perl, you'll probably want to build Perl for debugging, like this: ./Configure -d -D optimize=-g make C<-g> is a flag to the C compiler to have it produce debugging information which will allow us to step through a running program, and to see in which C function we are at (without the debugging information we might see only the numerical addresses of the functions, which is not very helpful). F<Configure> will also turn on the C<DEBUGGING> compilation symbol which enables all the internal debugging code in Perl. There are a whole bunch of things you can debug with this: L<perlrun> lists them all, and the best way to find out about them is to play about with them. The most useful options are probably l Context (loop) stack processing t Trace execution o Method and overloading resolution c String/numeric conversions Some of the functionality of the debugging code can be achieved using XS modules. -Dr => use re 'debug' -Dx => use O 'Debug' =head2 Using a source-level debugger If the debugging output of C<-D> doesn't help you, it's time to step through perl's execution with a source-level debugger. =over 3 =item * We'll use C<gdb> for our examples here; the principles will apply to any debugger (many vendors call their debugger C<dbx>), but check the manual of the one you're using. =back To fire up the debugger, type gdb ./perl Or if you have a core dump: gdb ./perl core You'll want to do that in your Perl source tree so the debugger can read the source code. You should see the copyright message, followed by the prompt. (gdb) C<help> will get you into the documentation, but here are the most useful commands: =over 3 =item * run [args] Run the program with the given arguments. =item * break function_name =item * break source.c:xxx Tells the debugger that we'll want to pause execution when we reach either the named function (but see L<perlguts/Internal Functions>!) or the given line in the named source file. =item * step Steps through the program a line at a time. =item * next Steps through the program a line at a time, without descending into functions. =item * continue Run until the next breakpoint. =item * finish Run until the end of the current function, then stop again. =item * 'enter' Just pressing Enter will do the most recent operation again - it's a blessing when stepping through miles of source code. =item * print Execute the given C code and print its results. B<WARNING>: Perl makes heavy use of macros, and F<gdb> does not necessarily support macros (see later L</"gdb macro support">). You'll have to substitute them yourself, or to invoke cpp on the source code files (see L</"The .i Targets">) So, for instance, you can't say print SvPV_nolen(sv) but you have to say print Perl_sv_2pv_nolen(sv) =back You may find it helpful to have a "macro dictionary", which you can produce by saying C<cpp -dM perl.c | sort>. Even then, F<cpp> won't recursively apply those macros for you. =head2 gdb macro support Recent versions of F<gdb> have fairly good macro support, but in order to use it you'll need to compile perl with macro definitions included in the debugging information. Using F<gcc> version 3.1, this means configuring with C<-Doptimize=-g3>. Other compilers might use a different switch (if they support debugging macros at all). =head2 Dumping Perl Data Structures One way to get around this macro hell is to use the dumping functions in F<dump.c>; these work a little like an internal L<Devel::Peek|Devel::Peek>, but they also cover OPs and other structures that you can't get at from Perl. Let's take an example. We'll use the C<$a = $b + $c> we used before, but give it a bit of context: C<$b = "6XXXX"; $c = 2.3;>. Where's a good place to stop and poke around? What about C<pp_add>, the function we examined earlier to implement the C<+> operator: (gdb) break Perl_pp_add Breakpoint 1 at 0x46249f: file pp_hot.c, line 309. Notice we use C<Perl_pp_add> and not C<pp_add> - see L<perlguts/Internal Functions>. With the breakpoint in place, we can run our program: (gdb) run -e '$b = "6XXXX"; $c = 2.3; $a = $b + $c' Lots of junk will go past as gdb reads in the relevant source files and libraries, and then: Breakpoint 1, Perl_pp_add () at pp_hot.c:309 309 dSP; dATARGET; tryAMAGICbin(add,opASSIGN); (gdb) step 311 dPOPTOPnnrl_ul; (gdb) We looked at this bit of code before, and we said that C<dPOPTOPnnrl_ul> arranges for two C<NV>s to be placed into C<left> and C<right> - let's slightly expand it: #define dPOPTOPnnrl_ul NV right = POPn; \ SV *leftsv = TOPs; \ NV left = USE_LEFT(leftsv) ? SvNV(leftsv) : 0.0 C<POPn> takes the SV from the top of the stack and obtains its NV either directly (if C<SvNOK> is set) or by calling the C<sv_2nv> function. C<TOPs> takes the next SV from the top of the stack - yes, C<POPn> uses C<TOPs> - but doesn't remove it. We then use C<SvNV> to get the NV from C<leftsv> in the same way as before - yes, C<POPn> uses C<SvNV>. Since we don't have an NV for C<$b>, we'll have to use C<sv_2nv> to convert it. If we step again, we'll find ourselves there: Perl_sv_2nv (sv=0xa0675d0) at sv.c:1669 1669 if (!sv) (gdb) We can now use C<Perl_sv_dump> to investigate the SV: SV = PV(0xa057cc0) at 0xa0675d0 REFCNT = 1 FLAGS = (POK,pPOK) PV = 0xa06a510 "6XXXX"\0 CUR = 5 LEN = 6 $1 = void We know we're going to get C<6> from this, so let's finish the subroutine: (gdb) finish Run till exit from #0 Perl_sv_2nv (sv=0xa0675d0) at sv.c:1671 0x462669 in Perl_pp_add () at pp_hot.c:311 311 dPOPTOPnnrl_ul; We can also dump out this op: the current op is always stored in C<PL_op>, and we can dump it with C<Perl_op_dump>. This'll give us similar output to L<B::Debug|B::Debug>. { 13 TYPE = add ===> 14 TARG = 1 FLAGS = (SCALAR,KIDS) { TYPE = null ===> (12) (was rv2sv) FLAGS = (SCALAR,KIDS) { 11 TYPE = gvsv ===> 12 FLAGS = (SCALAR) GV = main::b } } # finish this later # =head1 SOURCE CODE STATIC ANALYSIS Various tools exist for analysing C source code B<statically>, as opposed to B<dynamically>, that is, without executing the code. It is possible to detect resource leaks, undefined behaviour, type mismatches, portability problems, code paths that would cause illegal memory accesses, and other similar problems by just parsing the C code and looking at the resulting graph, what does it tell about the execution and data flows. As a matter of fact, this is exactly how C compilers know to give warnings about dubious code. =head2 lint, splint The good old C code quality inspector, C<lint>, is available in several platforms, but please be aware that there are several different implementations of it by different vendors, which means that the flags are not identical across different platforms. There is a lint variant called C<splint> (Secure Programming Lint) available from http://www.splint.org/ that should compile on any Unix-like platform. There are C<lint> and <splint> targets in Makefile, but you may have to diddle with the flags (see above). =head2 Coverity Coverity (http://www.coverity.com/) is a product similar to lint and as a testbed for their product they periodically check several open source projects, and they give out accounts to open source developers to the defect databases. =head2 cpd (cut-and-paste detector) The cpd tool detects cut-and-paste coding. If one instance of the cut-and-pasted code changes, all the other spots should probably be changed, too. Therefore such code should probably be turned into a subroutine or a macro. cpd (http://pmd.sourceforge.net/cpd.html) is part of the pmd project (http://pmd.sourceforge.net/). pmd was originally written for static analysis of Java code, but later the cpd part of it was extended to parse also C and C++. Download the pmd-bin-X.Y.zip () from the SourceForge site, extract the pmd-X.Y.jar from it, and then run that on source code thusly: java -cp pmd-X.Y.jar net.sourceforge.pmd.cpd.CPD --minimum-tokens 100 --files /some/where/src --language c > cpd.txt You may run into memory limits, in which case you should use the -Xmx option: java -Xmx512M ... =head2 gcc warnings Though much can be written about the inconsistency and coverage problems of gcc warnings (like C<-Wall> not meaning "all the warnings", or some common portability problems not being covered by C<-Wall>, or C<-ansi> and C<-pedantic> both being a poorly defined collection of warnings, and so forth), gcc is still a useful tool in keeping our coding nose clean. The C<-Wall> is by default on. The C<-ansi> (and its sidekick, C<-pedantic>) would be nice to be on always, but unfortunately they are not safe on all platforms, they can for example cause fatal conflicts with the system headers (Solaris being a prime example). If Configure C<-Dgccansipedantic> is used, the C<cflags> frontend selects C<-ansi -pedantic> for the platforms where they are known to be safe. Starting from Perl 5.9.4 the following extra flags are added: =over 4 =item * C<-Wendif-labels> =item * C<-Wextra> =item * C<-Wdeclaration-after-statement> =back The following flags would be nice to have but they would first need their own Augean stablemaster: =over 4 =item * C<-Wpointer-arith> =item * C<-Wshadow> =item * C<-Wstrict-prototypes> =back The C<-Wtraditional> is another example of the annoying tendency of gcc to bundle a lot of warnings under one switch (it would be impossible to deploy in practice because it would complain a lot) but it does contain some warnings that would be beneficial to have available on their own, such as the warning about string constants inside macros containing the macro arguments: this behaved differently pre-ANSI than it does in ANSI, and some C compilers are still in transition, AIX being an example. =head2 Warnings of other C compilers Other C compilers (yes, there B<are> other C compilers than gcc) often have their "strict ANSI" or "strict ANSI with some portability extensions" modes on, like for example the Sun Workshop has its C<-Xa> mode on (though implicitly), or the DEC (these days, HP...) has its C<-std1> mode on. =head1 MEMORY DEBUGGERS B<NOTE 1>: Running under memory debuggers such as Purify, valgrind, or Third Degree greatly slows down the execution: seconds become minutes, minutes become hours. For example as of Perl 5.8.1, the ext/Encode/t/Unicode.t takes extraordinarily long to complete under e.g. Purify, Third Degree, and valgrind. Under valgrind it takes more than six hours, even on a snappy computer. The said test must be doing something that is quite unfriendly for memory debuggers. If you don't feel like waiting, that you can simply kill away the perl process. B<NOTE 2>: To minimize the number of memory leak false alarms (see L</PERL_DESTRUCT_LEVEL> for more information), you have to set the environment variable PERL_DESTRUCT_LEVEL to 2. For csh-like shells: setenv PERL_DESTRUCT_LEVEL 2 For Bourne-type shells: PERL_DESTRUCT_LEVEL=2 export PERL_DESTRUCT_LEVEL In Unixy environments you can also use the C<env> command: env PERL_DESTRUCT_LEVEL=2 valgrind ./perl -Ilib ... B<NOTE 3>: There are known memory leaks when there are compile-time errors within eval or require, seeing C<S_doeval> in the call stack is a good sign of these. Fixing these leaks is non-trivial, unfortunately, but they must be fixed eventually. B<NOTE 4>: L<DynaLoader> will not clean up after itself completely unless Perl is built with the Configure option C<-Accflags=-DDL_UNLOAD_ALL_AT_EXIT>. =head2 Rational Software's Purify Purify is a commercial tool that is helpful in identifying memory overruns, wild pointers, memory leaks and other such badness. Perl must be compiled in a specific way for optimal testing with Purify. Purify is available under Windows NT, Solaris, HP-UX, SGI, and Siemens Unix. =head3 Purify on Unix On Unix, Purify creates a new Perl binary. To get the most benefit out of Purify, you should create the perl to Purify using: sh Configure -Accflags=-DPURIFY -Doptimize='-g' \ -Uusemymalloc -Dusemultiplicity where these arguments mean: =over 4 =item * -Accflags=-DPURIFY Disables Perl's arena memory allocation functions, as well as forcing use of memory allocation functions derived from the system malloc. =item * -Doptimize='-g' Adds debugging information so that you see the exact source statements where the problem occurs. Without this flag, all you will see is the source filename of where the error occurred. =item * -Uusemymalloc Disable Perl's malloc so that Purify can more closely monitor allocations and leaks. Using Perl's malloc will make Purify report most leaks in the "potential" leaks category. =item * -Dusemultiplicity Enabling the multiplicity option allows perl to clean up thoroughly when the interpreter shuts down, which reduces the number of bogus leak reports from Purify. =back Once you've compiled a perl suitable for Purify'ing, then you can just: make pureperl which creates a binary named 'pureperl' that has been Purify'ed. This binary is used in place of the standard 'perl' binary when you want to debug Perl memory problems. As an example, to show any memory leaks produced during the standard Perl testset you would create and run the Purify'ed perl as: make pureperl cd t ../pureperl -I../lib harness which would run Perl on test.pl and report any memory problems. Purify outputs messages in "Viewer" windows by default. If you don't have a windowing environment or if you simply want the Purify output to unobtrusively go to a log file instead of to the interactive window, use these following options to output to the log file "perl.log": setenv PURIFYOPTIONS "-chain-length=25 -windows=no \ -log-file=perl.log -append-logfile=yes" If you plan to use the "Viewer" windows, then you only need this option: setenv PURIFYOPTIONS "-chain-length=25" In Bourne-type shells: PURIFYOPTIONS="..." export PURIFYOPTIONS or if you have the "env" utility: env PURIFYOPTIONS="..." ../pureperl ... =head3 Purify on NT Purify on Windows NT instruments the Perl binary 'perl.exe' on the fly. There are several options in the makefile you should change to get the most use out of Purify: =over 4 =item * DEFINES You should add -DPURIFY to the DEFINES line so the DEFINES line looks something like: DEFINES = -DWIN32 -D_CONSOLE -DNO_STRICT $(CRYPT_FLAG) -DPURIFY=1 to disable Perl's arena memory allocation functions, as well as to force use of memory allocation functions derived from the system malloc. =item * USE_MULTI = define Enabling the multiplicity option allows perl to clean up thoroughly when the interpreter shuts down, which reduces the number of bogus leak reports from Purify. =item * #PERL_MALLOC = define Disable Perl's malloc so that Purify can more closely monitor allocations and leaks. Using Perl's malloc will make Purify report most leaks in the "potential" leaks category. =item * CFG = Debug Adds debugging information so that you see the exact source statements where the problem occurs. Without this flag, all you will see is the source filename of where the error occurred. =back As an example, to show any memory leaks produced during the standard Perl testset you would create and run Purify as: cd win32 make cd ../t purify ../perl -I../lib harness which would instrument Perl in memory, run Perl on test.pl, then finally report any memory problems. =head2 valgrind The excellent valgrind tool can be used to find out both memory leaks and illegal memory accesses. As of version 3.3.0, Valgrind only supports Linux on x86, x86-64 and PowerPC and Darwin (OS X) on x86 and x86-64). The special "test.valgrind" target can be used to run the tests under valgrind. Found errors and memory leaks are logged in files named F<testfile.valgrind>. Valgrind also provides a cachegrind tool, invoked on perl as: VG_OPTS=--tool=cachegrind make test.valgrind As system libraries (most notably glibc) are also triggering errors, valgrind allows to suppress such errors using suppression files. The default suppression file that comes with valgrind already catches a lot of them. Some additional suppressions are defined in F<t/perl.supp>. To get valgrind and for more information see http://valgrind.org/ =head1 PROFILING Depending on your platform there are various ways of profiling Perl. There are two commonly used techniques of profiling executables: I<statistical time-sampling> and I<basic-block counting>. The first method takes periodically samples of the CPU program counter, and since the program counter can be correlated with the code generated for functions, we get a statistical view of in which functions the program is spending its time. The caveats are that very small/fast functions have lower probability of showing up in the profile, and that periodically interrupting the program (this is usually done rather frequently, in the scale of milliseconds) imposes an additional overhead that may skew the results. The first problem can be alleviated by running the code for longer (in general this is a good idea for profiling), the second problem is usually kept in guard by the profiling tools themselves. The second method divides up the generated code into I<basic blocks>. Basic blocks are sections of code that are entered only in the beginning and exited only at the end. For example, a conditional jump starts a basic block. Basic block profiling usually works by I<instrumenting> the code by adding I<enter basic block #nnnn> book-keeping code to the generated code. During the execution of the code the basic block counters are then updated appropriately. The caveat is that the added extra code can skew the results: again, the profiling tools usually try to factor their own effects out of the results. =head2 Gprof Profiling gprof is a profiling tool available in many Unix platforms, it uses F<statistical time-sampling>. You can build a profiled version of perl called "perl.gprof" by invoking the make target "perl.gprof" (What is required is that Perl must be compiled using the C<-pg> flag, you may need to re-Configure). Running the profiled version of Perl will create an output file called F<gmon.out> is created which contains the profiling data collected during the execution. The gprof tool can then display the collected data in various ways. Usually gprof understands the following options: =over 4 =item * -a Suppress statically defined functions from the profile. =item * -b Suppress the verbose descriptions in the profile. =item * -e routine Exclude the given routine and its descendants from the profile. =item * -f routine Display only the given routine and its descendants in the profile. =item * -s Generate a summary file called F<gmon.sum> which then may be given to subsequent gprof runs to accumulate data over several runs. =item * -z Display routines that have zero usage. =back For more detailed explanation of the available commands and output formats, see your own local documentation of gprof. quick hint: $ sh Configure -des -Dusedevel -Doptimize='-pg' && make perl.gprof $ ./perl.gprof someprog # creates gmon.out in current directory $ gprof ./perl.gprof > out $ view out =head2 GCC gcov Profiling Starting from GCC 3.0 I<basic block profiling> is officially available for the GNU CC. You can build a profiled version of perl called F<perl.gcov> by invoking the make target "perl.gcov" (what is required that Perl must be compiled using gcc with the flags C<-fprofile-arcs -ftest-coverage>, you may need to re-Configure). Running the profiled version of Perl will cause profile output to be generated. For each source file an accompanying ".da" file will be created. To display the results you use the "gcov" utility (which should be installed if you have gcc 3.0 or newer installed). F<gcov> is run on source code files, like this gcov sv.c which will cause F<sv.c.gcov> to be created. The F<.gcov> files contain the source code annotated with relative frequencies of execution indicated by "#" markers. Useful options of F<gcov> include C<-b> which will summarise the basic block, branch, and function call coverage, and C<-c> which instead of relative frequencies will use the actual counts. For more information on the use of F<gcov> and basic block profiling with gcc, see the latest GNU CC manual, as of GCC 3.0 see http://gcc.gnu.org/onlinedocs/gcc-3.0/gcc.html and its section titled "8. gcov: a Test Coverage Program" http://gcc.gnu.org/onlinedocs/gcc-3.0/gcc_8.html#SEC132 quick hint: $ sh Configure -des -Dusedevel -Doptimize='-g' \ -Accflags='-fprofile-arcs -ftest-coverage' \ -Aldflags='-fprofile-arcs -ftest-coverage' && make perl.gcov $ rm -f regexec.c.gcov regexec.gcda $ ./perl.gcov $ gcov regexec.c $ view regexec.c.gcov =head1 MISCELLANEOUS TRICKS =head2 PERL_DESTRUCT_LEVEL If you want to run any of the tests yourself manually using e.g. valgrind, or the pureperl or perl.third executables, please note that by default perl B<does not> explicitly cleanup all the memory it has allocated (such as global memory arenas) but instead lets the exit() of the whole program "take care" of such allocations, also known as "global destruction of objects". There is a way to tell perl to do complete cleanup: set the environment variable PERL_DESTRUCT_LEVEL to a non-zero value. The t/TEST wrapper does set this to 2, and this is what you need to do too, if you don't want to see the "global leaks": For example, for "third-degreed" Perl: env PERL_DESTRUCT_LEVEL=2 ./perl.third -Ilib t/foo/bar.t (Note: the mod_perl apache module uses also this environment variable for its own purposes and extended its semantics. Refer to the mod_perl documentation for more information. Also, spawned threads do the equivalent of setting this variable to the value 1.) If, at the end of a run you get the message I<N scalars leaked>, you can recompile with C<-DDEBUG_LEAKING_SCALARS>, which will cause the addresses of all those leaked SVs to be dumped along with details as to where each SV was originally allocated. This information is also displayed by Devel::Peek. Note that the extra details recorded with each SV increases memory usage, so it shouldn't be used in production environments. It also converts C<new_SV()> from a macro into a real function, so you can use your favourite debugger to discover where those pesky SVs were allocated. If you see that you're leaking memory at runtime, but neither valgrind nor C<-DDEBUG_LEAKING_SCALARS> will find anything, you're probably leaking SVs that are still reachable and will be properly cleaned up during destruction of the interpreter. In such cases, using the C<-Dm> switch can point you to the source of the leak. If the executable was built with C<-DDEBUG_LEAKING_SCALARS>, C<-Dm> will output SV allocations in addition to memory allocations. Each SV allocation has a distinct serial number that will be written on creation and destruction of the SV. So if you're executing the leaking code in a loop, you need to look for SVs that are created, but never destroyed between each cycle. If such an SV is found, set a conditional breakpoint within C<new_SV()> and make it break only when C<PL_sv_serial> is equal to the serial number of the leaking SV. Then you will catch the interpreter in exactly the state where the leaking SV is allocated, which is sufficient in many cases to find the source of the leak. As C<-Dm> is using the PerlIO layer for output, it will by itself allocate quite a bunch of SVs, which are hidden to avoid recursion. You can bypass the PerlIO layer if you use the SV logging provided by C<-DPERL_MEM_LOG> instead. =head2 PERL_MEM_LOG If compiled with C<-DPERL_MEM_LOG>, both memory and SV allocations go through logging functions, which is handy for breakpoint setting. Unless C<-DPERL_MEM_LOG_NOIMPL> is also compiled, the logging functions read $ENV{PERL_MEM_LOG} to determine whether to log the event, and if so how: $ENV{PERL_MEM_LOG} =~ /m/ Log all memory ops $ENV{PERL_MEM_LOG} =~ /s/ Log all SV ops $ENV{PERL_MEM_LOG} =~ /t/ include timestamp in Log $ENV{PERL_MEM_LOG} =~ /^(\d+)/ write to FD given (default is 2) Memory logging is somewhat similar to C<-Dm> but is independent of C<-DDEBUGGING>, and at a higher level; all uses of Newx(), Renew(), and Safefree() are logged with the caller's source code file and line number (and C function name, if supported by the C compiler). In contrast, C<-Dm> is directly at the point of C<malloc()>. SV logging is similar. Since the logging doesn't use PerlIO, all SV allocations are logged and no extra SV allocations are introduced by enabling the logging. If compiled with C<-DDEBUG_LEAKING_SCALARS>, the serial number for each SV allocation is also logged. =head2 DDD over gdb Those debugging perl with the DDD frontend over gdb may find the following useful: You can extend the data conversion shortcuts menu, so for example you can display an SV's IV value with one click, without doing any typing. To do that simply edit ~/.ddd/init file and add after: ! Display shortcuts. Ddd*gdbDisplayShortcuts: \ /t () // Convert to Bin\n\ /d () // Convert to Dec\n\ /x () // Convert to Hex\n\ /o () // Convert to Oct(\n\ the following two lines: ((XPV*) (())->sv_any )->xpv_pv // 2pvx\n\ ((XPVIV*) (())->sv_any )->xiv_iv // 2ivx so now you can do ivx and pvx lookups or you can plug there the sv_peek "conversion": Perl_sv_peek(my_perl, (SV*)()) // sv_peek (The my_perl is for threaded builds.) Just remember that every line, but the last one, should end with \n\ Alternatively edit the init file interactively via: 3rd mouse button -> New Display -> Edit Menu Note: you can define up to 20 conversion shortcuts in the gdb section. =head2 Poison If you see in a debugger a memory area mysteriously full of 0xABABABAB or 0xEFEFEFEF, you may be seeing the effect of the Poison() macros, see L<perlclib>. =head2 Read-only optrees Under ithreads the optree is read only. If you want to enforce this, to check for write accesses from buggy code, compile with C<-DPL_OP_SLAB_ALLOC> to enable the OP slab allocator and C<-DPERL_DEBUG_READONLY_OPS> to enable code that allocates op memory via C<mmap>, and sets it read-only at run time. Any write access to an op results in a C<SIGBUS> and abort. This code is intended for development only, and may not be portable even to all Unix variants. Also, it is an 80% solution, in that it isn't able to make all ops read only. Specifically it =over =item * 1 Only sets read-only on all slabs of ops at C<CHECK> time, hence ops allocated later via C<require> or C<eval> will be re-write =item * 2 Turns an entire slab of ops read-write if the refcount of any op in the slab needs to be decreased. =item * 3 Turns an entire slab of ops read-write if any op from the slab is freed. =back It's not possible to turn the slabs to read-only after an action requiring read-write access, as either can happen during op tree building time, so there may still be legitimate write access. However, as an 80% solution it is still effective, as currently it catches a write access during the generation of F<Config.pm>, which means that we can't yet build F<perl> with this enabled. =head2 The .i Targets You can expand the macros in a F<foo.c> file by saying make foo.i which will expand the macros using cpp. Don't be scared by the results. =head1 AUTHOR This document was originally written by Nathan Torkington, and is maintained by the perl5-porters mailing list. PK PU�\��-A� � perliol.podnu �[��� =head1 NAME perliol - C API for Perl's implementation of IO in Layers. =head1 SYNOPSIS /* Defining a layer ... */ #include <perliol.h> =head1 DESCRIPTION This document describes the behavior and implementation of the PerlIO abstraction described in L<perlapio> when C<USE_PERLIO> is defined (and C<USE_SFIO> is not). =head2 History and Background The PerlIO abstraction was introduced in perl5.003_02 but languished as just an abstraction until perl5.7.0. However during that time a number of perl extensions switched to using it, so the API is mostly fixed to maintain (source) compatibility. The aim of the implementation is to provide the PerlIO API in a flexible and platform neutral manner. It is also a trial of an "Object Oriented C, with vtables" approach which may be applied to Perl 6. =head2 Basic Structure PerlIO is a stack of layers. The low levels of the stack work with the low-level operating system calls (file descriptors in C) getting bytes in and out, the higher layers of the stack buffer, filter, and otherwise manipulate the I/O, and return characters (or bytes) to Perl. Terms I<above> and I<below> are used to refer to the relative positioning of the stack layers. A layer contains a "vtable", the table of I/O operations (at C level a table of function pointers), and status flags. The functions in the vtable implement operations like "open", "read", and "write". When I/O, for example "read", is requested, the request goes from Perl first down the stack using "read" functions of each layer, then at the bottom the input is requested from the operating system services, then the result is returned up the stack, finally being interpreted as Perl data. The requests do not necessarily go always all the way down to the operating system: that's where PerlIO buffering comes into play. When you do an open() and specify extra PerlIO layers to be deployed, the layers you specify are "pushed" on top of the already existing default stack. One way to see it is that "operating system is on the left" and "Perl is on the right". What exact layers are in this default stack depends on a lot of things: your operating system, Perl version, Perl compile time configuration, and Perl runtime configuration. See L<PerlIO>, L<perlrun/PERLIO>, and L<open> for more information. binmode() operates similarly to open(): by default the specified layers are pushed on top of the existing stack. However, note that even as the specified layers are "pushed on top" for open() and binmode(), this doesn't mean that the effects are limited to the "top": PerlIO layers can be very 'active' and inspect and affect layers also deeper in the stack. As an example there is a layer called "raw" which repeatedly "pops" layers until it reaches the first layer that has declared itself capable of handling binary data. The "pushed" layers are processed in left-to-right order. sysopen() operates (unsurprisingly) at a lower level in the stack than open(). For example in Unix or Unix-like systems sysopen() operates directly at the level of file descriptors: in the terms of PerlIO layers, it uses only the "unix" layer, which is a rather thin wrapper on top of the Unix file descriptors. =head2 Layers vs Disciplines Initial discussion of the ability to modify IO streams behaviour used the term "discipline" for the entities which were added. This came (I believe) from the use of the term in "sfio", which in turn borrowed it from "line disciplines" on Unix terminals. However, this document (and the C code) uses the term "layer". This is, I hope, a natural term given the implementation, and should avoid connotations that are inherent in earlier uses of "discipline" for things which are rather different. =head2 Data Structures The basic data structure is a PerlIOl: typedef struct _PerlIO PerlIOl; typedef struct _PerlIO_funcs PerlIO_funcs; typedef PerlIOl *PerlIO; struct _PerlIO { PerlIOl * next; /* Lower layer */ PerlIO_funcs * tab; /* Functions for this layer */ IV flags; /* Various flags for state */ }; A C<PerlIOl *> is a pointer to the struct, and the I<application> level C<PerlIO *> is a pointer to a C<PerlIOl *> - i.e. a pointer to a pointer to the struct. This allows the application level C<PerlIO *> to remain constant while the actual C<PerlIOl *> underneath changes. (Compare perl's C<SV *> which remains constant while its C<sv_any> field changes as the scalar's type changes.) An IO stream is then in general represented as a pointer to this linked-list of "layers". It should be noted that because of the double indirection in a C<PerlIO *>, a C<< &(perlio->next) >> "is" a C<PerlIO *>, and so to some degree at least one layer can use the "standard" API on the next layer down. A "layer" is composed of two parts: =over 4 =item 1. The functions and attributes of the "layer class". =item 2. The per-instance data for a particular handle. =back =head2 Functions and Attributes The functions and attributes are accessed via the "tab" (for table) member of C<PerlIOl>. The functions (methods of the layer "class") are fixed, and are defined by the C<PerlIO_funcs> type. They are broadly the same as the public C<PerlIO_xxxxx> functions: struct _PerlIO_funcs { Size_t fsize; char * name; Size_t size; IV kind; IV (*Pushed)(pTHX_ PerlIO *f,const char *mode,SV *arg, PerlIO_funcs *tab); IV (*Popped)(pTHX_ PerlIO *f); PerlIO * (*Open)(pTHX_ PerlIO_funcs *tab, PerlIO_list_t *layers, IV n, const char *mode, int fd, int imode, int perm, PerlIO *old, int narg, SV **args); IV (*Binmode)(pTHX_ PerlIO *f); SV * (*Getarg)(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags) IV (*Fileno)(pTHX_ PerlIO *f); PerlIO * (*Dup)(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags) /* Unix-like functions - cf sfio line disciplines */ SSize_t (*Read)(pTHX_ PerlIO *f, void *vbuf, Size_t count); SSize_t (*Unread)(pTHX_ PerlIO *f, const void *vbuf, Size_t count); SSize_t (*Write)(pTHX_ PerlIO *f, const void *vbuf, Size_t count); IV (*Seek)(pTHX_ PerlIO *f, Off_t offset, int whence); Off_t (*Tell)(pTHX_ PerlIO *f); IV (*Close)(pTHX_ PerlIO *f); /* Stdio-like buffered IO functions */ IV (*Flush)(pTHX_ PerlIO *f); IV (*Fill)(pTHX_ PerlIO *f); IV (*Eof)(pTHX_ PerlIO *f); IV (*Error)(pTHX_ PerlIO *f); void (*Clearerr)(pTHX_ PerlIO *f); void (*Setlinebuf)(pTHX_ PerlIO *f); /* Perl's snooping functions */ STDCHAR * (*Get_base)(pTHX_ PerlIO *f); Size_t (*Get_bufsiz)(pTHX_ PerlIO *f); STDCHAR * (*Get_ptr)(pTHX_ PerlIO *f); SSize_t (*Get_cnt)(pTHX_ PerlIO *f); void (*Set_ptrcnt)(pTHX_ PerlIO *f,STDCHAR *ptr,SSize_t cnt); }; The first few members of the struct give a function table size for compatibility check "name" for the layer, the size to C<malloc> for the per-instance data, and some flags which are attributes of the class as whole (such as whether it is a buffering layer), then follow the functions which fall into four basic groups: =over 4 =item 1. Opening and setup functions =item 2. Basic IO operations =item 3. Stdio class buffering options. =item 4. Functions to support Perl's traditional "fast" access to the buffer. =back A layer does not have to implement all the functions, but the whole table has to be present. Unimplemented slots can be NULL (which will result in an error when called) or can be filled in with stubs to "inherit" behaviour from a "base class". This "inheritance" is fixed for all instances of the layer, but as the layer chooses which stubs to populate the table, limited "multiple inheritance" is possible. =head2 Per-instance Data The per-instance data are held in memory beyond the basic PerlIOl struct, by making a PerlIOl the first member of the layer's struct thus: typedef struct { struct _PerlIO base; /* Base "class" info */ STDCHAR * buf; /* Start of buffer */ STDCHAR * end; /* End of valid part of buffer */ STDCHAR * ptr; /* Current position in buffer */ Off_t posn; /* Offset of buf into the file */ Size_t bufsiz; /* Real size of buffer */ IV oneword; /* Emergency buffer */ } PerlIOBuf; In this way (as for perl's scalars) a pointer to a PerlIOBuf can be treated as a pointer to a PerlIOl. =head2 Layers in action. table perlio unix | | +-----------+ +----------+ +--------+ PerlIO ->| |--->| next |--->| NULL | +-----------+ +----------+ +--------+ | | | buffer | | fd | +-----------+ | | +--------+ | | +----------+ The above attempts to show how the layer scheme works in a simple case. The application's C<PerlIO *> points to an entry in the table(s) representing open (allocated) handles. For example the first three slots in the table correspond to C<stdin>,C<stdout> and C<stderr>. The table in turn points to the current "top" layer for the handle - in this case an instance of the generic buffering layer "perlio". That layer in turn points to the next layer down - in this case the low-level "unix" layer. The above is roughly equivalent to a "stdio" buffered stream, but with much more flexibility: =over 4 =item * If Unix level C<read>/C<write>/C<lseek> is not appropriate for (say) sockets then the "unix" layer can be replaced (at open time or even dynamically) with a "socket" layer. =item * Different handles can have different buffering schemes. The "top" layer could be the "mmap" layer if reading disk files was quicker using C<mmap> than C<read>. An "unbuffered" stream can be implemented simply by not having a buffer layer. =item * Extra layers can be inserted to process the data as it flows through. This was the driving need for including the scheme in perl 5.7.0+ - we needed a mechanism to allow data to be translated between perl's internal encoding (conceptually at least Unicode as UTF-8), and the "native" format used by the system. This is provided by the ":encoding(xxxx)" layer which typically sits above the buffering layer. =item * A layer can be added that does "\n" to CRLF translation. This layer can be used on any platform, not just those that normally do such things. =back =head2 Per-instance flag bits The generic flag bits are a hybrid of C<O_XXXXX> style flags deduced from the mode string passed to C<PerlIO_open()>, and state bits for typical buffer layers. =over 4 =item PERLIO_F_EOF End of file. =item PERLIO_F_CANWRITE Writes are permitted, i.e. opened as "w" or "r+" or "a", etc. =item PERLIO_F_CANREAD Reads are permitted i.e. opened "r" or "w+" (or even "a+" - ick). =item PERLIO_F_ERROR An error has occurred (for C<PerlIO_error()>). =item PERLIO_F_TRUNCATE Truncate file suggested by open mode. =item PERLIO_F_APPEND All writes should be appends. =item PERLIO_F_CRLF Layer is performing Win32-like "\n" mapped to CR,LF for output and CR,LF mapped to "\n" for input. Normally the provided "crlf" layer is the only layer that need bother about this. C<PerlIO_binmode()> will mess with this flag rather than add/remove layers if the C<PERLIO_K_CANCRLF> bit is set for the layers class. =item PERLIO_F_UTF8 Data written to this layer should be UTF-8 encoded; data provided by this layer should be considered UTF-8 encoded. Can be set on any layer by ":utf8" dummy layer. Also set on ":encoding" layer. =item PERLIO_F_UNBUF Layer is unbuffered - i.e. write to next layer down should occur for each write to this layer. =item PERLIO_F_WRBUF The buffer for this layer currently holds data written to it but not sent to next layer. =item PERLIO_F_RDBUF The buffer for this layer currently holds unconsumed data read from layer below. =item PERLIO_F_LINEBUF Layer is line buffered. Write data should be passed to next layer down whenever a "\n" is seen. Any data beyond the "\n" should then be processed. =item PERLIO_F_TEMP File has been C<unlink()>ed, or should be deleted on C<close()>. =item PERLIO_F_OPEN Handle is open. =item PERLIO_F_FASTGETS This instance of this layer supports the "fast C<gets>" interface. Normally set based on C<PERLIO_K_FASTGETS> for the class and by the existence of the function(s) in the table. However a class that normally provides that interface may need to avoid it on a particular instance. The "pending" layer needs to do this when it is pushed above a layer which does not support the interface. (Perl's C<sv_gets()> does not expect the streams fast C<gets> behaviour to change during one "get".) =back =head2 Methods in Detail =over 4 =item fsize Size_t fsize; Size of the function table. This is compared against the value PerlIO code "knows" as a compatibility check. Future versions I<may> be able to tolerate layers compiled against an old version of the headers. =item name char * name; The name of the layer whose open() method Perl should invoke on open(). For example if the layer is called APR, you will call: open $fh, ">:APR", ... and Perl knows that it has to invoke the PerlIOAPR_open() method implemented by the APR layer. =item size Size_t size; The size of the per-instance data structure, e.g.: sizeof(PerlIOAPR) If this field is zero then C<PerlIO_pushed> does not malloc anything and assumes layer's Pushed function will do any required layer stack manipulation - used to avoid malloc/free overhead for dummy layers. If the field is non-zero it must be at least the size of C<PerlIOl>, C<PerlIO_pushed> will allocate memory for the layer's data structures and link new layer onto the stream's stack. (If the layer's Pushed method returns an error indication the layer is popped again.) =item kind IV kind; =over 4 =item * PERLIO_K_BUFFERED The layer is buffered. =item * PERLIO_K_RAW The layer is acceptable to have in a binmode(FH) stack - i.e. it does not (or will configure itself not to) transform bytes passing through it. =item * PERLIO_K_CANCRLF Layer can translate between "\n" and CRLF line ends. =item * PERLIO_K_FASTGETS Layer allows buffer snooping. =item * PERLIO_K_MULTIARG Used when the layer's open() accepts more arguments than usual. The extra arguments should come not before the C<MODE> argument. When this flag is used it's up to the layer to validate the args. =back =item Pushed IV (*Pushed)(pTHX_ PerlIO *f,const char *mode, SV *arg); The only absolutely mandatory method. Called when the layer is pushed onto the stack. The C<mode> argument may be NULL if this occurs post-open. The C<arg> will be non-C<NULL> if an argument string was passed. In most cases this should call C<PerlIOBase_pushed()> to convert C<mode> into the appropriate C<PERLIO_F_XXXXX> flags in addition to any actions the layer itself takes. If a layer is not expecting an argument it need neither save the one passed to it, nor provide C<Getarg()> (it could perhaps C<Perl_warn> that the argument was un-expected). Returns 0 on success. On failure returns -1 and should set errno. =item Popped IV (*Popped)(pTHX_ PerlIO *f); Called when the layer is popped from the stack. A layer will normally be popped after C<Close()> is called. But a layer can be popped without being closed if the program is dynamically managing layers on the stream. In such cases C<Popped()> should free any resources (buffers, translation tables, ...) not held directly in the layer's struct. It should also C<Unread()> any unconsumed data that has been read and buffered from the layer below back to that layer, so that it can be re-provided to what ever is now above. Returns 0 on success and failure. If C<Popped()> returns I<true> then I<perlio.c> assumes that either the layer has popped itself, or the layer is super special and needs to be retained for other reasons. In most cases it should return I<false>. =item Open PerlIO * (*Open)(...); The C<Open()> method has lots of arguments because it combines the functions of perl's C<open>, C<PerlIO_open>, perl's C<sysopen>, C<PerlIO_fdopen> and C<PerlIO_reopen>. The full prototype is as follows: PerlIO * (*Open)(pTHX_ PerlIO_funcs *tab, PerlIO_list_t *layers, IV n, const char *mode, int fd, int imode, int perm, PerlIO *old, int narg, SV **args); Open should (perhaps indirectly) call C<PerlIO_allocate()> to allocate a slot in the table and associate it with the layers information for the opened file, by calling C<PerlIO_push>. The I<layers> is an array of all the layers destined for the C<PerlIO *>, and any arguments passed to them, I<n> is the index into that array of the layer being called. The macro C<PerlIOArg> will return a (possibly C<NULL>) SV * for the argument passed to the layer. The I<mode> string is an "C<fopen()>-like" string which would match the regular expression C</^[I#]?[rwa]\+?[bt]?$/>. The C<'I'> prefix is used during creation of C<stdin>..C<stderr> via special C<PerlIO_fdopen> calls; the C<'#'> prefix means that this is C<sysopen> and that I<imode> and I<perm> should be passed to C<PerlLIO_open3>; C<'r'> means B<r>ead, C<'w'> means B<w>rite and C<'a'> means B<a>ppend. The C<'+'> suffix means that both reading and writing/appending are permitted. The C<'b'> suffix means file should be binary, and C<'t'> means it is text. (Almost all layers should do the IO in binary mode, and ignore the b/t bits. The C<:crlf> layer should be pushed to handle the distinction.) If I<old> is not C<NULL> then this is a C<PerlIO_reopen>. Perl itself does not use this (yet?) and semantics are a little vague. If I<fd> not negative then it is the numeric file descriptor I<fd>, which will be open in a manner compatible with the supplied mode string, the call is thus equivalent to C<PerlIO_fdopen>. In this case I<nargs> will be zero. If I<nargs> is greater than zero then it gives the number of arguments passed to C<open>, otherwise it will be 1 if for example C<PerlIO_open> was called. In simple cases SvPV_nolen(*args) is the pathname to open. If a layer provides C<Open()> it should normally call the C<Open()> method of next layer down (if any) and then push itself on top if that succeeds. C<PerlIOBase_open> is provided to do exactly that, so in most cases you don't have to write your own C<Open()> method. If this method is not defined, other layers may have difficulty pushing themselves on top of it during open. If C<PerlIO_push> was performed and open has failed, it must C<PerlIO_pop> itself, since if it's not, the layer won't be removed and may cause bad problems. Returns C<NULL> on failure. =item Binmode IV (*Binmode)(pTHX_ PerlIO *f); Optional. Used when C<:raw> layer is pushed (explicitly or as a result of binmode(FH)). If not present layer will be popped. If present should configure layer as binary (or pop itself) and return 0. If it returns -1 for error C<binmode> will fail with layer still on the stack. =item Getarg SV * (*Getarg)(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags); Optional. If present should return an SV * representing the string argument passed to the layer when it was pushed. e.g. ":encoding(ascii)" would return an SvPV with value "ascii". (I<param> and I<flags> arguments can be ignored in most cases) C<Dup> uses C<Getarg> to retrieve the argument originally passed to C<Pushed>, so you must implement this function if your layer has an extra argument to C<Pushed> and will ever be C<Dup>ed. =item Fileno IV (*Fileno)(pTHX_ PerlIO *f); Returns the Unix/Posix numeric file descriptor for the handle. Normally C<PerlIOBase_fileno()> (which just asks next layer down) will suffice for this. Returns -1 on error, which is considered to include the case where the layer cannot provide such a file descriptor. =item Dup PerlIO * (*Dup)(pTHX_ PerlIO *f, PerlIO *o, CLONE_PARAMS *param, int flags); XXX: Needs more docs. Used as part of the "clone" process when a thread is spawned (in which case param will be non-NULL) and when a stream is being duplicated via '&' in the C<open>. Similar to C<Open>, returns PerlIO* on success, C<NULL> on failure. =item Read SSize_t (*Read)(pTHX_ PerlIO *f, void *vbuf, Size_t count); Basic read operation. Typically will call C<Fill> and manipulate pointers (possibly via the API). C<PerlIOBuf_read()> may be suitable for derived classes which provide "fast gets" methods. Returns actual bytes read, or -1 on an error. =item Unread SSize_t (*Unread)(pTHX_ PerlIO *f, const void *vbuf, Size_t count); A superset of stdio's C<ungetc()>. Should arrange for future reads to see the bytes in C<vbuf>. If there is no obviously better implementation then C<PerlIOBase_unread()> provides the function by pushing a "fake" "pending" layer above the calling layer. Returns the number of unread chars. =item Write SSize_t (*Write)(PerlIO *f, const void *vbuf, Size_t count); Basic write operation. Returns bytes written or -1 on an error. =item Seek IV (*Seek)(pTHX_ PerlIO *f, Off_t offset, int whence); Position the file pointer. Should normally call its own C<Flush> method and then the C<Seek> method of next layer down. Returns 0 on success, -1 on failure. =item Tell Off_t (*Tell)(pTHX_ PerlIO *f); Return the file pointer. May be based on layers cached concept of position to avoid overhead. Returns -1 on failure to get the file pointer. =item Close IV (*Close)(pTHX_ PerlIO *f); Close the stream. Should normally call C<PerlIOBase_close()> to flush itself and close layers below, and then deallocate any data structures (buffers, translation tables, ...) not held directly in the data structure. Returns 0 on success, -1 on failure. =item Flush IV (*Flush)(pTHX_ PerlIO *f); Should make stream's state consistent with layers below. That is, any buffered write data should be written, and file position of lower layers adjusted for data read from below but not actually consumed. (Should perhaps C<Unread()> such data to the lower layer.) Returns 0 on success, -1 on failure. =item Fill IV (*Fill)(pTHX_ PerlIO *f); The buffer for this layer should be filled (for read) from layer below. When you "subclass" PerlIOBuf layer, you want to use its I<_read> method and to supply your own fill method, which fills the PerlIOBuf's buffer. Returns 0 on success, -1 on failure. =item Eof IV (*Eof)(pTHX_ PerlIO *f); Return end-of-file indicator. C<PerlIOBase_eof()> is normally sufficient. Returns 0 on end-of-file, 1 if not end-of-file, -1 on error. =item Error IV (*Error)(pTHX_ PerlIO *f); Return error indicator. C<PerlIOBase_error()> is normally sufficient. Returns 1 if there is an error (usually when C<PERLIO_F_ERROR> is set, 0 otherwise. =item Clearerr void (*Clearerr)(pTHX_ PerlIO *f); Clear end-of-file and error indicators. Should call C<PerlIOBase_clearerr()> to set the C<PERLIO_F_XXXXX> flags, which may suffice. =item Setlinebuf void (*Setlinebuf)(pTHX_ PerlIO *f); Mark the stream as line buffered. C<PerlIOBase_setlinebuf()> sets the PERLIO_F_LINEBUF flag and is normally sufficient. =item Get_base STDCHAR * (*Get_base)(pTHX_ PerlIO *f); Allocate (if not already done so) the read buffer for this layer and return pointer to it. Return NULL on failure. =item Get_bufsiz Size_t (*Get_bufsiz)(pTHX_ PerlIO *f); Return the number of bytes that last C<Fill()> put in the buffer. =item Get_ptr STDCHAR * (*Get_ptr)(pTHX_ PerlIO *f); Return the current read pointer relative to this layer's buffer. =item Get_cnt SSize_t (*Get_cnt)(pTHX_ PerlIO *f); Return the number of bytes left to be read in the current buffer. =item Set_ptrcnt void (*Set_ptrcnt)(pTHX_ PerlIO *f, STDCHAR *ptr, SSize_t cnt); Adjust the read pointer and count of bytes to match C<ptr> and/or C<cnt>. The application (or layer above) must ensure they are consistent. (Checking is allowed by the paranoid.) =back =head2 Utilities To ask for the next layer down use PerlIONext(PerlIO *f). To check that a PerlIO* is valid use PerlIOValid(PerlIO *f). (All this does is really just to check that the pointer is non-NULL and that the pointer behind that is non-NULL.) PerlIOBase(PerlIO *f) returns the "Base" pointer, or in other words, the C<PerlIOl*> pointer. PerlIOSelf(PerlIO* f, type) return the PerlIOBase cast to a type. Perl_PerlIO_or_Base(PerlIO* f, callback, base, failure, args) either calls the I<callback> from the functions of the layer I<f> (just by the name of the IO function, like "Read") with the I<args>, or if there is no such callback, calls the I<base> version of the callback with the same args, or if the f is invalid, set errno to EBADF and return I<failure>. Perl_PerlIO_or_fail(PerlIO* f, callback, failure, args) either calls the I<callback> of the functions of the layer I<f> with the I<args>, or if there is no such callback, set errno to EINVAL. Or if the f is invalid, set errno to EBADF and return I<failure>. Perl_PerlIO_or_Base_void(PerlIO* f, callback, base, args) either calls the I<callback> of the functions of the layer I<f> with the I<args>, or if there is no such callback, calls the I<base> version of the callback with the same args, or if the f is invalid, set errno to EBADF. Perl_PerlIO_or_fail_void(PerlIO* f, callback, args) either calls the I<callback> of the functions of the layer I<f> with the I<args>, or if there is no such callback, set errno to EINVAL. Or if the f is invalid, set errno to EBADF. =head2 Implementing PerlIO Layers If you find the implementation document unclear or not sufficient, look at the existing PerlIO layer implementations, which include: =over =item * C implementations The F<perlio.c> and F<perliol.h> in the Perl core implement the "unix", "perlio", "stdio", "crlf", "utf8", "byte", "raw", "pending" layers, and also the "mmap" and "win32" layers if applicable. (The "win32" is currently unfinished and unused, to see what is used instead in Win32, see L<PerlIO/"Querying the layers of filehandles"> .) PerlIO::encoding, PerlIO::scalar, PerlIO::via in the Perl core. PerlIO::gzip and APR::PerlIO (mod_perl 2.0) on CPAN. =item * Perl implementations PerlIO::via::QuotedPrint in the Perl core and PerlIO::via::* on CPAN. =back If you are creating a PerlIO layer, you may want to be lazy, in other words, implement only the methods that interest you. The other methods you can either replace with the "blank" methods PerlIOBase_noop_ok PerlIOBase_noop_fail (which do nothing, and return zero and -1, respectively) or for certain methods you may assume a default behaviour by using a NULL method. The Open method looks for help in the 'parent' layer. The following table summarizes the behaviour: method behaviour with NULL Clearerr PerlIOBase_clearerr Close PerlIOBase_close Dup PerlIOBase_dup Eof PerlIOBase_eof Error PerlIOBase_error Fileno PerlIOBase_fileno Fill FAILURE Flush SUCCESS Getarg SUCCESS Get_base FAILURE Get_bufsiz FAILURE Get_cnt FAILURE Get_ptr FAILURE Open INHERITED Popped SUCCESS Pushed SUCCESS Read PerlIOBase_read Seek FAILURE Set_cnt FAILURE Set_ptrcnt FAILURE Setlinebuf PerlIOBase_setlinebuf Tell FAILURE Unread PerlIOBase_unread Write FAILURE FAILURE Set errno (to EINVAL in Unixish, to LIB$_INVARG in VMS) and return -1 (for numeric return values) or NULL (for pointers) INHERITED Inherited from the layer below SUCCESS Return 0 (for numeric return values) or a pointer =head2 Core Layers The file C<perlio.c> provides the following layers: =over 4 =item "unix" A basic non-buffered layer which calls Unix/POSIX C<read()>, C<write()>, C<lseek()>, C<close()>. No buffering. Even on platforms that distinguish between O_TEXT and O_BINARY this layer is always O_BINARY. =item "perlio" A very complete generic buffering layer which provides the whole of PerlIO API. It is also intended to be used as a "base class" for other layers. (For example its C<Read()> method is implemented in terms of the C<Get_cnt()>/C<Get_ptr()>/C<Set_ptrcnt()> methods). "perlio" over "unix" provides a complete replacement for stdio as seen via PerlIO API. This is the default for USE_PERLIO when system's stdio does not permit perl's "fast gets" access, and which do not distinguish between C<O_TEXT> and C<O_BINARY>. =item "stdio" A layer which provides the PerlIO API via the layer scheme, but implements it by calling system's stdio. This is (currently) the default if system's stdio provides sufficient access to allow perl's "fast gets" access and which do not distinguish between C<O_TEXT> and C<O_BINARY>. =item "crlf" A layer derived using "perlio" as a base class. It provides Win32-like "\n" to CR,LF translation. Can either be applied above "perlio" or serve as the buffer layer itself. "crlf" over "unix" is the default if system distinguishes between C<O_TEXT> and C<O_BINARY> opens. (At some point "unix" will be replaced by a "native" Win32 IO layer on that platform, as Win32's read/write layer has various drawbacks.) The "crlf" layer is a reasonable model for a layer which transforms data in some way. =item "mmap" If Configure detects C<mmap()> functions this layer is provided (with "perlio" as a "base") which does "read" operations by mmap()ing the file. Performance improvement is marginal on modern systems, so it is mainly there as a proof of concept. It is likely to be unbundled from the core at some point. The "mmap" layer is a reasonable model for a minimalist "derived" layer. =item "pending" An "internal" derivative of "perlio" which can be used to provide Unread() function for layers which have no buffer or cannot be bothered. (Basically this layer's C<Fill()> pops itself off the stack and so resumes reading from layer below.) =item "raw" A dummy layer which never exists on the layer stack. Instead when "pushed" it actually pops the stack removing itself, it then calls Binmode function table entry on all the layers in the stack - normally this (via PerlIOBase_binmode) removes any layers which do not have C<PERLIO_K_RAW> bit set. Layers can modify that behaviour by defining their own Binmode entry. =item "utf8" Another dummy layer. When pushed it pops itself and sets the C<PERLIO_F_UTF8> flag on the layer which was (and now is once more) the top of the stack. =back In addition F<perlio.c> also provides a number of C<PerlIOBase_xxxx()> functions which are intended to be used in the table slots of classes which do not need to do anything special for a particular method. =head2 Extension Layers Layers can be made available by extension modules. When an unknown layer is encountered the PerlIO code will perform the equivalent of : use PerlIO 'layer'; Where I<layer> is the unknown layer. F<PerlIO.pm> will then attempt to: require PerlIO::layer; If after that process the layer is still not defined then the C<open> will fail. The following extension layers are bundled with perl: =over 4 =item ":encoding" use Encoding; makes this layer available, although F<PerlIO.pm> "knows" where to find it. It is an example of a layer which takes an argument as it is called thus: open( $fh, "<:encoding(iso-8859-7)", $pathname ); =item ":scalar" Provides support for reading data from and writing data to a scalar. open( $fh, "+<:scalar", \$scalar ); When a handle is so opened, then reads get bytes from the string value of I<$scalar>, and writes change the value. In both cases the position in I<$scalar> starts as zero but can be altered via C<seek>, and determined via C<tell>. Please note that this layer is implied when calling open() thus: open( $fh, "+<", \$scalar ); =item ":via" Provided to allow layers to be implemented as Perl code. For instance: use PerlIO::via::StripHTML; open( my $fh, "<:via(StripHTML)", "index.html" ); See L<PerlIO::via> for details. =back =head1 TODO Things that need to be done to improve this document. =over =item * Explain how to make a valid fh without going through open()(i.e. apply a layer). For example if the file is not opened through perl, but we want to get back a fh, like it was opened by Perl. How PerlIO_apply_layera fits in, where its docs, was it made public? Currently the example could be something like this: PerlIO *foo_to_PerlIO(pTHX_ char *mode, ...) { char *mode; /* "w", "r", etc */ const char *layers = ":APR"; /* the layer name */ PerlIO *f = PerlIO_allocate(aTHX); if (!f) { return NULL; } PerlIO_apply_layers(aTHX_ f, mode, layers); if (f) { PerlIOAPR *st = PerlIOSelf(f, PerlIOAPR); /* fill in the st struct, as in _open() */ st->file = file; PerlIOBase(f)->flags |= PERLIO_F_OPEN; return f; } return NULL; } =item * fix/add the documentation in places marked as XXX. =item * The handling of errors by the layer is not specified. e.g. when $! should be set explicitly, when the error handling should be just delegated to the top layer. Probably give some hints on using SETERRNO() or pointers to where they can be found. =item * I think it would help to give some concrete examples to make it easier to understand the API. Of course I agree that the API has to be concise, but since there is no second document that is more of a guide, I think that it'd make it easier to start with the doc which is an API, but has examples in it in places where things are unclear, to a person who is not a PerlIO guru (yet). =back =cut PK PU�\�q] perlplan9.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see pod/perlpod.pod) which is specially designed to be readable as is. =head1 NAME perlplan9 - Plan 9-specific documentation for Perl =head1 DESCRIPTION These are a few notes describing features peculiar to Plan 9 Perl. As such, it is not intended to be a replacement for the rest of the Perl 5 documentation (which is both copious and excellent). If you have any questions to which you can't find answers in these man pages, contact Luther Huffman at lutherh@stratcom.com and we'll try to answer them. =head2 Invoking Perl Perl is invoked from the command line as described in L<perl>. Most perl scripts, however, do have a first line such as "#!/usr/local/bin/perl". This is known as a shebang (shell-bang) statement and tells the OS shell where to find the perl interpreter. In Plan 9 Perl this statement should be "#!/bin/perl" if you wish to be able to directly invoke the script by its name. Alternatively, you may invoke perl with the command "Perl" instead of "perl". This will produce Acme-friendly error messages of the form "filename:18". Some scripts, usually identified with a *.PL extension, are self-configuring and are able to correctly create their own shebang path from config information located in Plan 9 Perl. These you won't need to be worried about. =head2 What's in Plan 9 Perl Although Plan 9 Perl currently only provides static loading, it is built with a number of useful extensions. These include Opcode, FileHandle, Fcntl, and POSIX. Expect to see others (and DynaLoading!) in the future. =head2 What's not in Plan 9 Perl As mentioned previously, dynamic loading isn't currently available nor is MakeMaker. Both are high-priority items. =head2 Perl5 Functions not currently supported in Plan 9 Perl Some, such as C<chown> and C<umask> aren't provided because the concept does not exist within Plan 9. Others, such as some of the socket-related functions, simply haven't been written yet. Many in the latter category may be supported in the future. The functions not currently implemented include: chown, chroot, dbmclose, dbmopen, getsockopt, setsockopt, recvmsg, sendmsg, getnetbyname, getnetbyaddr, getnetent, getprotoent, getservent, sethostent, setnetent, setprotoent, setservent, endservent, endnetent, endprotoent, umask There may be several other functions that have undefined behavior so this list shouldn't be considered complete. =head2 Signals in Plan 9 Perl For compatibility with perl scripts written for the Unix environment, Plan 9 Perl uses the POSIX signal emulation provided in Plan 9's ANSI POSIX Environment (APE). Signal stacking isn't supported. The signals provided are: SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGKILL, SIGSEGV, SIGPIPE, SIGPIPE, SIGALRM, SIGTERM, SIGUSR1, SIGUSR2, SIGCHLD, SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU =head1 COMPILING AND INSTALLING PERL ON PLAN 9 WELCOME to Plan 9 Perl, brave soul! This is a preliminary alpha version of Plan 9 Perl. Still to be implemented are MakeMaker and DynaLoader. Many perl commands are missing or currently behave in an inscrutable manner. These gaps will, with perseverance and a modicum of luck, be remedied in the near future.To install this software: 1. Create the source directories and libraries for perl by running the plan9/setup.rc command (i.e., located in the plan9 subdirectory). Note: the setup routine assumes that you haven't dearchived these files into /sys/src/cmd/perl. After running setup.rc you may delete the copy of the source you originally detarred, as source code has now been installed in /sys/src/cmd/perl. If you plan on installing perl binaries for all architectures, run "setup.rc -a". 2. After making sure that you have adequate privileges to build system software, from /sys/src/cmd/perl/5.00301 (adjust version appropriately) run: mk install If you wish to install perl versions for all architectures (68020, mips, sparc and 386) run: mk installall 3. Wait. The build process will take a *long* time because perl bootstraps itself. A 75MHz Pentium, 16MB RAM machine takes roughly 30 minutes to build the distribution from scratch. =head2 Installing Perl Documentation on Plan 9 This perl distribution comes with a tremendous amount of documentation. To add these to the built-in manuals that come with Plan 9, from /sys/src/cmd/perl/5.00301 (adjust version appropriately) run: mk man To begin your reading, start with: man perl This is a good introduction and will direct you towards other man pages that may interest you. (Note: "mk man" may produce some extraneous noise. Fear not.) =head1 BUGS "As many as there are grains of sand on all the beaches of the world . . ." - Carl Sagan =head1 Revision date This document was revised 09-October-1996 for Perl 5.003_7. =head1 AUTHOR Direct questions, comments, and the unlikely bug report (ahem) direct comments toward: Luther Huffman, lutherh@stratcom.com, Strategic Computer Solutions, Inc. PK PU�\`p��I �I perlfunc.podnu �[��� =head1 NAME X<function> perlfunc - Perl builtin functions =head1 DESCRIPTION The functions in this section can serve as terms in an expression. They fall into two major categories: list operators and named unary operators. These differ in their precedence relationship with a following comma. (See the precedence table in L<perlop>.) List operators take more than one argument, while unary operators can never take more than one argument. Thus, a comma terminates the argument of a unary operator, but merely separates the arguments of a list operator. A unary operator generally provides scalar context to its argument, while a list operator may provide either scalar or list contexts for its arguments. If it does both, scalar arguments come first and list argument follow, and there can only ever be one such list argument. For instance, splice() has three scalar arguments followed by a list, whereas gethostbyname() has four scalar arguments. In the syntax descriptions that follow, list operators that expect a list (and provide list context for elements of the list) are shown with LIST as an argument. Such a list may consist of any combination of scalar arguments or list values; the list values will be included in the list as if each individual element were interpolated at that point in the list, forming a longer single-dimensional list value. Commas should separate literal elements of the LIST. Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use parentheses, the simple but occasionally surprising rule is this: It I<looks> like a function, therefore it I<is> a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. Whitespace between the function and left parenthesis doesn't count, so sometimes you need to be careful: print 1+2+4; # Prints 7. print(1+2) + 4; # Prints 3. print (1+2)+4; # Also prints 3! print +(1+2)+4; # Prints 7. print ((1+2)+4); # Prints 7. If you run Perl with the B<-w> switch it can warn you about this. For example, the third line above produces: print (...) interpreted as function at - line 1. Useless use of integer addition in void context at - line 1. A few functions take no arguments at all, and therefore work as neither unary nor list operators. These include such functions as C<time> and C<endpwent>. For example, C<time+86_400> always means C<time() + 86_400>. For functions that can be used in either a scalar or list context, nonabortive failure is generally indicated in scalar context by returning the undefined value, and in list context by returning the empty list. Remember the following important rule: There is B<no rule> that relates the behavior of an expression in list context to its behavior in scalar context, or vice versa. It might do two totally different things. Each operator and function decides which sort of value would be most appropriate to return in scalar context. Some operators return the length of the list that would have been returned in list context. Some operators return the first value in the list. Some operators return the last value in the list. Some operators return a count of successful operations. In general, they do what you want, unless you want consistency. X<context> A named array in scalar context is quite different from what would at first glance appear to be a list in scalar context. You can't get a list like C<(1,2,3)> into being in scalar context, because the compiler knows the context at compile time. It would generate the scalar comma operator there, not the list construction version of the comma. That means it was never a list to start with. In general, functions in Perl that serve as wrappers for system calls ("syscalls") of the same name (like chown(2), fork(2), closedir(2), etc.) return true when they succeed and C<undef> otherwise, as is usually mentioned in the descriptions below. This is different from the C interfaces, which return C<-1> on failure. Exceptions to this rule include C<wait>, C<waitpid>, and C<syscall>. System calls also set the special C<$!> variable on failure. Other functions do not, except accidentally. Extension modules can also hook into the Perl parser to define new kinds of keyword-headed expression. These may look like functions, but may also look completely different. The syntax following the keyword is defined entirely by the extension. If you are an implementor, see L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such a module, see the module's documentation for details of the syntax that it defines. =head2 Perl Functions by Category X<function> Here are Perl's functions (including things that look like functions, like some keywords and named operators) arranged by category. Some functions appear in more than one place. =over 4 =item Functions for SCALARs or strings X<scalar> X<string> X<character> =for Pod::Functions =String C<chomp>, C<chop>, C<chr>, C<crypt>, C<fc>, C<hex>, C<index>, C<lc>, C<lcfirst>, C<length>, C<oct>, C<ord>, C<pack>, C<q//>, C<qq//>, C<reverse>, C<rindex>, C<sprintf>, C<substr>, C<tr///>, C<uc>, C<ucfirst>, C<y///> C<fc> is available only if the C<"fc"> feature is enabled or if it is prefixed with C<CORE::>. The C<"fc"> feature is enabled automatically with a C<use v5.16> (or higher) declaration in the current scope. =item Regular expressions and pattern matching X<regular expression> X<regex> X<regexp> =for Pod::Functions =Regexp C<m//>, C<pos>, C<qr//>, C<quotemeta>, C<s///>, C<split>, C<study> =item Numeric functions X<numeric> X<number> X<trigonometric> X<trigonometry> =for Pod::Functions =Math C<abs>, C<atan2>, C<cos>, C<exp>, C<hex>, C<int>, C<log>, C<oct>, C<rand>, C<sin>, C<sqrt>, C<srand> =item Functions for real @ARRAYs X<array> =for Pod::Functions =ARRAY C<each>, C<keys>, C<pop>, C<push>, C<shift>, C<splice>, C<unshift>, C<values> =item Functions for list data X<list> =for Pod::Functions =LIST C<grep>, C<join>, C<map>, C<qw//>, C<reverse>, C<sort>, C<unpack> =item Functions for real %HASHes X<hash> =for Pod::Functions =HASH C<delete>, C<each>, C<exists>, C<keys>, C<values> =item Input and output functions X<I/O> X<input> X<output> X<dbm> =for Pod::Functions =I/O C<binmode>, C<close>, C<closedir>, C<dbmclose>, C<dbmopen>, C<die>, C<eof>, C<fileno>, C<flock>, C<format>, C<getc>, C<print>, C<printf>, C<read>, C<readdir>, C<readline> C<rewinddir>, C<say>, C<seek>, C<seekdir>, C<select>, C<syscall>, C<sysread>, C<sysseek>, C<syswrite>, C<tell>, C<telldir>, C<truncate>, C<warn>, C<write> C<say> is available only if the C<"say"> feature is enabled or if it is prefixed with C<CORE::>. The C<"say"> feature is enabled automatically with a C<use v5.10> (or higher) declaration in the current scope. =item Functions for fixed-length data or records =for Pod::Functions =Binary C<pack>, C<read>, C<syscall>, C<sysread>, C<sysseek>, C<syswrite>, C<unpack>, C<vec> =item Functions for filehandles, files, or directories X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink> =for Pod::Functions =File C<-I<X>>, C<chdir>, C<chmod>, C<chown>, C<chroot>, C<fcntl>, C<glob>, C<ioctl>, C<link>, C<lstat>, C<mkdir>, C<open>, C<opendir>, C<readlink>, C<rename>, C<rmdir>, C<stat>, C<symlink>, C<sysopen>, C<umask>, C<unlink>, C<utime> =item Keywords related to the control flow of your Perl program X<control flow> =for Pod::Functions =Flow C<break>, C<caller>, C<continue>, C<die>, C<do>, C<dump>, C<eval>, C<evalbytes> C<exit>, C<__FILE__>, C<goto>, C<last>, C<__LINE__>, C<next>, C<__PACKAGE__>, C<redo>, C<return>, C<sub>, C<__SUB__>, C<wantarray> C<break> is available only if you enable the experimental C<"switch"> feature or use the C<CORE::> prefix. The C<"switch"> feature also enables the C<default>, C<given> and C<when> statements, which are documented in L<perlsyn/"Switch Statements">. The C<"switch"> feature is enabled automatically with a C<use v5.10> (or higher) declaration in the current scope. In Perl v5.14 and earlier, C<continue> required the C<"switch"> feature, like the other keywords. C<evalbytes> is only available with with the C<"evalbytes"> feature (see L<feature>) or if prefixed with C<CORE::>. C<__SUB__> is only available with with the C<"current_sub"> feature or if prefixed with C<CORE::>. Both the C<"evalbytes"> and C<"current_sub"> features are enabled automatically with a C<use v5.16> (or higher) declaration in the current scope. =item Keywords related to scoping =for Pod::Functions =Namespace C<caller>, C<import>, C<local>, C<my>, C<our>, C<package>, C<state>, C<use> C<state> is available only if the C<"state"> feature is enabled or if it is prefixed with C<CORE::>. The C<"state"> feature is enabled automatically with a C<use v5.10> (or higher) declaration in the current scope. =item Miscellaneous functions =for Pod::Functions =Misc C<defined>, C<formline>, C<lock>, C<prototype>, C<reset>, C<scalar>, C<undef> =item Functions for processes and process groups X<process> X<pid> X<process id> =for Pod::Functions =Process C<alarm>, C<exec>, C<fork>, C<getpgrp>, C<getppid>, C<getpriority>, C<kill>, C<pipe>, C<qx//>, C<readpipe>, C<setpgrp>, C<setpriority>, C<sleep>, C<system>, C<times>, C<wait>, C<waitpid> =item Keywords related to Perl modules X<module> =for Pod::Functions =Modules C<do>, C<import>, C<no>, C<package>, C<require>, C<use> =item Keywords related to classes and object-orientation X<object> X<class> X<package> =for Pod::Functions =Objects C<bless>, C<dbmclose>, C<dbmopen>, C<package>, C<ref>, C<tie>, C<tied>, C<untie>, C<use> =item Low-level socket functions X<socket> X<sock> =for Pod::Functions =Socket C<accept>, C<bind>, C<connect>, C<getpeername>, C<getsockname>, C<getsockopt>, C<listen>, C<recv>, C<send>, C<setsockopt>, C<shutdown>, C<socket>, C<socketpair> =item System V interprocess communication functions X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message> =for Pod::Functions =SysV C<msgctl>, C<msgget>, C<msgrcv>, C<msgsnd>, C<semctl>, C<semget>, C<semop>, C<shmctl>, C<shmget>, C<shmread>, C<shmwrite> =item Fetching user and group info X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd> =for Pod::Functions =User C<endgrent>, C<endhostent>, C<endnetent>, C<endpwent>, C<getgrent>, C<getgrgid>, C<getgrnam>, C<getlogin>, C<getpwent>, C<getpwnam>, C<getpwuid>, C<setgrent>, C<setpwent> =item Fetching network info X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service> =for Pod::Functions =Network C<endprotoent>, C<endservent>, C<gethostbyaddr>, C<gethostbyname>, C<gethostent>, C<getnetbyaddr>, C<getnetbyname>, C<getnetent>, C<getprotobyname>, C<getprotobynumber>, C<getprotoent>, C<getservbyname>, C<getservbyport>, C<getservent>, C<sethostent>, C<setnetent>, C<setprotoent>, C<setservent> =item Time-related functions X<time> X<date> =for Pod::Functions =Time C<gmtime>, C<localtime>, C<time>, C<times> =item Non-function keywords =for Pod::Functions =!Non-functions C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>, C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>, C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>, C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>, C<while>, C<x>, C<xor> =back =head2 Portability X<portability> X<Unix> X<portable> Perl was born in Unix and can therefore access all common Unix system calls. In non-Unix environments, the functionality of some Unix system calls may not be available or details of the available functionality may differ slightly. The Perl functions affected by this are: C<-X>, C<binmode>, C<chmod>, C<chown>, C<chroot>, C<crypt>, C<dbmclose>, C<dbmopen>, C<dump>, C<endgrent>, C<endhostent>, C<endnetent>, C<endprotoent>, C<endpwent>, C<endservent>, C<exec>, C<fcntl>, C<flock>, C<fork>, C<getgrent>, C<getgrgid>, C<gethostbyname>, C<gethostent>, C<getlogin>, C<getnetbyaddr>, C<getnetbyname>, C<getnetent>, C<getppid>, C<getpgrp>, C<getpriority>, C<getprotobynumber>, C<getprotoent>, C<getpwent>, C<getpwnam>, C<getpwuid>, C<getservbyport>, C<getservent>, C<getsockopt>, C<glob>, C<ioctl>, C<kill>, C<link>, C<lstat>, C<msgctl>, C<msgget>, C<msgrcv>, C<msgsnd>, C<open>, C<pipe>, C<readlink>, C<rename>, C<select>, C<semctl>, C<semget>, C<semop>, C<setgrent>, C<sethostent>, C<setnetent>, C<setpgrp>, C<setpriority>, C<setprotoent>, C<setpwent>, C<setservent>, C<setsockopt>, C<shmctl>, C<shmget>, C<shmread>, C<shmwrite>, C<socket>, C<socketpair>, C<stat>, C<symlink>, C<syscall>, C<sysopen>, C<system>, C<times>, C<truncate>, C<umask>, C<unlink>, C<utime>, C<wait>, C<waitpid> For more information about the portability of these functions, see L<perlport> and other available platform-specific documentation. =head2 Alphabetical Listing of Perl Functions =over =item -X FILEHANDLE X<-r>X<-w>X<-x>X<-o>X<-R>X<-W>X<-X>X<-O>X<-e>X<-z>X<-s>X<-f>X<-d>X<-l>X<-p> X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C> =item -X EXPR =item -X DIRHANDLE =item -X =for Pod::Functions a file test (-r, -x, etc) A file test, where X is one of the letters listed below. This unary operator takes one argument, either a filename, a filehandle, or a dirhandle, and tests the associated file to see if something is true about it. If the argument is omitted, tests C<$_>, except for C<-t>, which tests STDIN. Unless otherwise documented, it returns C<1> for true and C<''> for false, or the undefined value if the file doesn't exist. Despite the funny names, precedence is the same as any other named unary operator. The operator may be any of: -r File is readable by effective uid/gid. -w File is writable by effective uid/gid. -x File is executable by effective uid/gid. -o File is owned by effective uid. -R File is readable by real uid/gid. -W File is writable by real uid/gid. -X File is executable by real uid/gid. -O File is owned by real uid. -e File exists. -z File has zero size (is empty). -s File has nonzero size (returns size in bytes). -f File is a plain file. -d File is a directory. -l File is a symbolic link. -p File is a named pipe (FIFO), or Filehandle is a pipe. -S File is a socket. -b File is a block special file. -c File is a character special file. -t Filehandle is opened to a tty. -u File has setuid bit set. -g File has setgid bit set. -k File has sticky bit set. -T File is an ASCII text file (heuristic guess). -B File is a "binary" file (opposite of -T). -M Script start time minus file modification time, in days. -A Same for access time. -C Same for inode change time (Unix, may differ for other platforms) Example: while (<>) { chomp; next unless -f $_; # ignore specials #... } Note that C<-s/a/b/> does not do a negated substitution. Saying C<-exp($foo)> still works as expected, however: only single letters following a minus are interpreted as file tests. These operators are exempt from the "looks like a function rule" described above. That is, an opening parenthesis after the operator does not affect how much of the following code constitutes the argument. Put the opening parentheses before the operator to separate it from code that follows (this applies only to operators with higher precedence than unary operators, of course): -s($file) + 1024 # probably wrong; same as -s($file + 1024) (-s $file) + 1024 # correct The interpretation of the file permission operators C<-r>, C<-R>, C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode of the file and the uids and gids of the user. There may be other reasons you can't actually read, write, or execute the file: for example network filesystem access controls, ACLs (access control lists), read-only filesystems, and unrecognized executable formats. Note that the use of these six specific operators to verify if some operation is possible is usually a mistake, because it may be open to race conditions. Also note that, for the superuser on the local filesystems, the C<-r>, C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1 if any execute bit is set in the mode. Scripts run by the superuser may thus need to do a stat() to determine the actual mode of the file, or temporarily set their effective uid to something else. If you are using ACLs, there is a pragma called C<filetest> that may produce more accurate results than the bare stat() mode bits. When under C<use filetest 'access'> the above-mentioned filetests test whether the permission can(not) be granted using the access(2) family of system calls. Also note that the C<-x> and C<-X> may under this pragma return true even if there are no execute permission bits set (nor any extra execute permission ACLs). This strangeness is due to the underlying system calls' definitions. Note also that, due to the implementation of C<use filetest 'access'>, the C<_> special filehandle won't cache the results of the file tests when this pragma is in effect. Read the documentation for the C<filetest> pragma for more information. The C<-T> and C<-B> switches work as follows. The first block or so of the file is examined for odd characters such as strange control codes or characters with the high bit set. If too many strange characters (>30%) are found, it's a C<-B> file; otherwise it's a C<-T> file. Also, any file containing a zero byte in the first block is considered a binary file. If C<-T> or C<-B> is used on a filehandle, the current IO buffer is examined rather than the first block. Both C<-T> and C<-B> return true on an empty file, or a file at EOF when testing a filehandle. Because you have to read a file to do the C<-T> test, on most occasions you want to use a C<-f> against the file first, as in C<next unless -f $file && -T $file>. If any of the file tests (or either the C<stat> or C<lstat> operator) is given the special filehandle consisting of a solitary underline, then the stat structure of the previous file test (or stat operator) is used, saving a system call. (This doesn't work with C<-t>, and you need to remember that lstat() and C<-l> leave values in the stat structure for the symbolic link, not the real file.) (Also, if the stat buffer was filled by an C<lstat> call, C<-T> and C<-B> will reset it with the results of C<stat _>). Example: print "Can do.\n" if -r $a || -w _ || -x _; stat($filename); print "Readable\n" if -r _; print "Writable\n" if -w _; print "Executable\n" if -x _; print "Setuid\n" if -u _; print "Setgid\n" if -g _; print "Sticky\n" if -k _; print "Text\n" if -T _; print "Binary\n" if -B _; As of Perl 5.9.1, as a form of purely syntactic sugar, you can stack file test operators, in a way that C<-f -w -x $file> is equivalent to C<-x $file && -w _ && -f _>. (This is only fancy fancy: if you use the return value of C<-f $file> as an argument to another filetest operator, no special magic will happen.) Portability issues: L<perlport/-X>. To avoid confusing would-be users of your code with mysterious syntax errors, put something like this at the top of your script: use 5.010; # so filetest ops can stack =item abs VALUE X<abs> X<absolute> =item abs =for Pod::Functions absolute value function Returns the absolute value of its argument. If VALUE is omitted, uses C<$_>. =item accept NEWSOCKET,GENERICSOCKET X<accept> =for Pod::Functions accept an incoming socket connect Accepts an incoming socket connect, just as accept(2) does. Returns the packed address if it succeeded, false otherwise. See the example in L<perlipc/"Sockets: Client/Server Communication">. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See L<perlvar/$^F>. =item alarm SECONDS X<alarm> X<SIGALRM> X<timer> =item alarm =for Pod::Functions schedule a SIGALRM Arranges to have a SIGALRM delivered to this process after the specified number of wallclock seconds has elapsed. If SECONDS is not specified, the value stored in C<$_> is used. (On some machines, unfortunately, the elapsed time may be up to one second less or more than you specified because of how seconds are counted, and process scheduling may delay the delivery of the signal even further.) Only one timer may be counting at once. Each call disables the previous timer, and an argument of C<0> may be supplied to cancel the previous timer without starting a new one. The returned value is the amount of time remaining on the previous timer. For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides ualarm(). You may also use Perl's four-argument version of select() leaving the first three arguments undefined, or you might be able to use the C<syscall> interface to access setitimer(2) if your system supports it. See L<perlfaq8> for details. It is usually a mistake to intermix C<alarm> and C<sleep> calls, because C<sleep> may be internally implemented on your system with C<alarm>. If you want to use C<alarm> to time out a system call you need to use an C<eval>/C<die> pair. You can't rely on the alarm causing the system call to fail with C<$!> set to C<EINTR> because Perl sets up signal handlers to restart system calls on some systems. Using C<eval>/C<die> always works, modulo the caveats given in L<perlipc/"Signals">. eval { local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required alarm $timeout; $nread = sysread SOCKET, $buffer, $size; alarm 0; }; if ($@) { die unless $@ eq "alarm\n"; # propagate unexpected errors # timed out } else { # didn't } For more information see L<perlipc>. Portability issues: L<perlport/alarm>. =item atan2 Y,X X<atan2> X<arctangent> X<tan> X<tangent> =for Pod::Functions arctangent of Y/X in the range -PI to PI Returns the arctangent of Y/X in the range -PI to PI. For the tangent operation, you may use the C<Math::Trig::tan> function, or use the familiar relation: sub tan { sin($_[0]) / cos($_[0]) } The return value for C<atan2(0,0)> is implementation-defined; consult your atan2(3) manpage for more information. Portability issues: L<perlport/atan2>. =item bind SOCKET,NAME X<bind> =for Pod::Functions binds an address to a socket Binds a network address to a socket, just as bind(2) does. Returns true if it succeeded, false otherwise. NAME should be a packed address of the appropriate type for the socket. See the examples in L<perlipc/"Sockets: Client/Server Communication">. =item binmode FILEHANDLE, LAYER X<binmode> X<binary> X<text> X<DOS> X<Windows> =item binmode FILEHANDLE =for Pod::Functions prepare binary files for I/O Arranges for FILEHANDLE to be read or written in "binary" or "text" mode on systems where the run-time libraries distinguish between binary and text files. If FILEHANDLE is an expression, the value is taken as the name of the filehandle. Returns true on success, otherwise it returns C<undef> and sets C<$!> (errno). On some systems (in general, DOS- and Windows-based systems) binmode() is necessary when you're not working with a text file. For the sake of portability it is a good idea always to use it when appropriate, and never to use it when it isn't appropriate. Also, people can set their I/O to be by default UTF8-encoded Unicode, not bytes. In other words: regardless of platform, use binmode() on binary data, like images, for example. If LAYER is present it is a single string, but may contain multiple directives. The directives alter the behaviour of the filehandle. When LAYER is present, using binmode on a text file makes sense. If LAYER is omitted or specified as C<:raw> the filehandle is made suitable for passing binary data. This includes turning off possible CRLF translation and marking it as bytes (as opposed to Unicode characters). Note that, despite what may be implied in I<"Programming Perl"> (the Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>. Other layers that would affect the binary nature of the stream are I<also> disabled. See L<PerlIO>, L<perlrun>, and the discussion about the PERLIO environment variable. The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the form C<:...>, are called I/O I<layers>. The C<open> pragma can be used to establish default I/O layers. See L<open>. I<The LAYER parameter of the binmode() function is described as "DISCIPLINE" in "Programming Perl, 3rd Edition". However, since the publishing of this book, by many known as "Camel III", the consensus of the naming of this functionality has moved from "discipline" to "layer". All documentation of this version of Perl therefore refers to "layers" rather than to "disciplines". Now back to the regularly scheduled documentation...> To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>. C<:utf8> just marks the data as UTF-8 without further checking, while C<:encoding(UTF-8)> checks the data for actually being valid UTF-8. More details can be found in L<PerlIO::encoding>. In general, binmode() should be called after open() but before any I/O is done on the filehandle. Calling binmode() normally flushes any pending buffered output data (and perhaps pending input data) on the handle. An exception to this is the C<:encoding> layer that changes the default character encoding of the handle; see L</open>. The C<:encoding> layer sometimes needs to be called in mid-stream, and it doesn't flush the stream. The C<:encoding> also implicitly pushes on top of itself the C<:utf8> layer because internally Perl operates on UTF8-encoded Unicode characters. The operating system, device drivers, C libraries, and Perl run-time system all conspire to let the programmer treat a single character (C<\n>) as the line terminator, irrespective of external representation. On many operating systems, the native text file representation matches the internal representation, but on some platforms the external representation of C<\n> is made up of more than one character. All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use a single character to end each line in the external representation of text (even though that single character is CARRIAGE RETURN on old, pre-Darwin flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other systems like OS/2, DOS, and the various flavors of MS-Windows, your program sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the two characters C<\cM\cJ>. That means that if you don't use binmode() on these systems, C<\cM\cJ> sequences on disk will be converted to C<\n> on input, and any C<\n> in your program will be converted back to C<\cM\cJ> on output. This is what you want for text files, but it can be disastrous for binary files. Another consequence of using binmode() (on some systems) is that special end-of-file markers will be seen as part of the data stream. For systems from the Microsoft family this means that, if your binary data contain C<\cZ>, the I/O subsystem will regard it as the end of the file, unless you use binmode(). binmode() is important not only for readline() and print() operations, but also when using read(), seek(), sysread(), syswrite() and tell() (see L<perlport> for more details). See the C<$/> and C<$\> variables in L<perlvar> for how to manually set your input and output line-termination sequences. Portability issues: L<perlport/binmode>. =item bless REF,CLASSNAME X<bless> =item bless REF =for Pod::Functions create an object This function tells the thingy referenced by REF that it is now an object in the CLASSNAME package. If CLASSNAME is omitted, the current package is used. Because a C<bless> is often the last thing in a constructor, it returns the reference for convenience. Always use the two-argument version if a derived class might inherit the function doing the blessing. SeeL<perlobj> for more about the blessing (and blessings) of objects. Consider always blessing objects in CLASSNAMEs that are mixed case. Namespaces with all lowercase names are considered reserved for Perl pragmata. Builtin types have all uppercase names. To prevent confusion, you may wish to avoid such package names as well. Make sure that CLASSNAME is a true value. See L<perlmod/"Perl Modules">. =item break =for Pod::Functions +switch break out of a C<given> block Break out of a C<given()> block. This keyword is enabled by the C<"switch"> feature: see L<feature> for more information. You can also access it by prefixing it with C<CORE::>. Alternately, include a C<use v5.10> or later to the current scope. =item caller EXPR X<caller> X<call stack> X<stack> X<stack trace> =item caller =for Pod::Functions get context of the current subroutine call Returns the context of the current subroutine call. In scalar context, returns the caller's package name if there I<is> a caller (that is, if we're in a subroutine or C<eval> or C<require>) and the undefined value otherwise. In list context, returns # 0 1 2 ($package, $filename, $line) = caller; With EXPR, it returns some extra information that the debugger uses to print a stack trace. The value of EXPR indicates how many call frames to go back before the current one. # 0 1 2 3 4 ($package, $filename, $line, $subroutine, $hasargs, # 5 6 7 8 9 10 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) = caller($i); Here $subroutine may be C<(eval)> if the frame is not a subroutine call, but an C<eval>. In such a case additional elements $evaltext and C<$is_require> are set: C<$is_require> is true if the frame is created by a C<require> or C<use> statement, $evaltext contains the text of the C<eval EXPR> statement. In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>, but $evaltext is undefined. (Note also that each C<use> statement creates a C<require> frame inside an C<eval EXPR> frame.) $subroutine may also be C<(unknown)> if this particular subroutine happens to have been deleted from the symbol table. C<$hasargs> is true if a new instance of C<@_> was set up for the frame. C<$hints> and C<$bitmask> contain pragmatic hints that the caller was compiled with. The C<$hints> and C<$bitmask> values are subject to change between versions of Perl, and are not meant for external use. C<$hinthash> is a reference to a hash containing the value of C<%^H> when the caller was compiled, or C<undef> if C<%^H> was empty. Do not modify the values of this hash, as they are the actual values stored in the optree. Furthermore, when called from within the DB package in list context, and with an argument, caller returns more detailed information: it sets the list variable C<@DB::args> to be the arguments with which the subroutine was invoked. Be aware that the optimizer might have optimized call frames away before C<caller> had a chance to get the information. That means that C<caller(N)> might not return information about the call frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> might have information from the previous time C<caller> was called. Be aware that setting C<@DB::args> is I<best effort>, intended for debugging or generating backtraces, and should not be relied upon. In particular, as C<@_> contains aliases to the caller's arguments, Perl does not take a copy of C<@_>, so C<@DB::args> will contain modifications the subroutine makes to C<@_> or its contents, not the original values at call time. C<@DB::args>, like C<@_>, does not hold explicit references to its elements, so under certain cases its elements may have become freed and reallocated for other variables or temporary values. Finally, a side effect of the current implementation is that the effects of C<shift @_> can I<normally> be undone (but not C<pop @_> or other splicing, I<and> not if a reference to C<@_> has been taken, I<and> subject to the caveat about reallocated elements), so C<@DB::args> is actually a hybrid of the current state and initial state of C<@_>. Buyer beware. =item chdir EXPR X<chdir> X<cd> X<directory, change> =item chdir FILEHANDLE =item chdir DIRHANDLE =item chdir =for Pod::Functions change your current working directory Changes the working directory to EXPR, if possible. If EXPR is omitted, changes to the directory specified by C<$ENV{HOME}>, if set; if not, changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the variable C<$ENV{SYS$LOGIN}> is also checked, and used if it is set.) If neither is set, C<chdir> does nothing. It returns true on success, false otherwise. See the example under C<die>. On systems that support fchdir(2), you may pass a filehandle or directory handle as the argument. On systems that don't support fchdir(2), passing handles raises an exception. =item chmod LIST X<chmod> X<permission> X<mode> =for Pod::Functions changes the permissions on a list of files Changes the permissions of a list of files. The first element of the list must be the numeric mode, which should probably be an octal number, and which definitely should I<not> be a string of octal digits: C<0644> is okay, but C<"0644"> is not. Returns the number of files successfully changed. See also L</oct> if all you have is a string. $cnt = chmod 0755, "foo", "bar"; chmod 0755, @executables; $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to # --w----r-T $mode = "0644"; chmod oct($mode), "foo"; # this is better $mode = 0644; chmod $mode, "foo"; # this is best On systems that support fchmod(2), you may pass filehandles among the files. On systems that don't support fchmod(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames. open(my $fh, "<", "foo"); my $perm = (stat $fh)[2] & 07777; chmod($perm | 0600, $fh); You can also import the symbolic C<S_I*> constants from the C<Fcntl> module: use Fcntl qw( :mode ); chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; # Identical to the chmod 0755 of the example above. Portability issues: L<perlport/chmod>. =item chomp VARIABLE X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> =item chomp( LIST ) =item chomp =for Pod::Functions remove a trailing record separator from a string This safer version of L</chop> removes any trailing string that corresponds to the current value of C<$/> (also known as $INPUT_RECORD_SEPARATOR in the C<English> module). It returns the total number of characters removed from all its arguments. It's often used to remove the newline from the end of an input record when you're worried that the final record may be missing its newline. When in paragraph mode (C<$/ = "">), it removes all trailing newlines from the string. When in slurp mode (C<$/ = undef>) or fixed-length record mode (C<$/> is a reference to an integer or the like; see L<perlvar>) chomp() won't remove anything. If VARIABLE is omitted, it chomps C<$_>. Example: while (<>) { chomp; # avoid \n on last field @array = split(/:/); # ... } If VARIABLE is a hash, it chomps the hash's values, but not its keys. You can actually chomp anything that's an lvalue, including an assignment: chomp($cwd = `pwd`); chomp($answer = <STDIN>); If you chomp a list, each element is chomped, and the total number of characters removed is returned. Note that parentheses are necessary when you're chomping anything that is not a simple variable. This is because C<chomp $cwd = `pwd`;> is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as C<chomp( $cwd = `pwd` )> which you might expect. Similarly, C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than as C<chomp($a, $b)>. =item chop VARIABLE X<chop> =item chop( LIST ) =item chop =for Pod::Functions remove the last character from a string Chops off the last character of a string and returns the character chopped. It is much more efficient than C<s/.$//s> because it neither scans nor copies the string. If VARIABLE is omitted, chops C<$_>. If VARIABLE is a hash, it chops the hash's values, but not its keys. You can actually chop anything that's an lvalue, including an assignment. If you chop a list, each element is chopped. Only the value of the last C<chop> is returned. Note that C<chop> returns the last character. To return all but the last character, use C<substr($string, 0, -1)>. See also L</chomp>. =item chown LIST X<chown> X<owner> X<user> X<group> =for Pod::Functions change the ownership on a list of files Changes the owner (and group) of a list of files. The first two elements of the list must be the I<numeric> uid and gid, in that order. A value of -1 in either position is interpreted by most systems to leave that value unchanged. Returns the number of files successfully changed. $cnt = chown $uid, $gid, 'foo', 'bar'; chown $uid, $gid, @filenames; On systems that support fchown(2), you may pass filehandles among the files. On systems that don't support fchown(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames. Here's an example that looks up nonnumeric uids in the passwd file: print "User: "; chomp($user = <STDIN>); print "Files: "; chomp($pattern = <STDIN>); ($login,$pass,$uid,$gid) = getpwnam($user) or die "$user not in passwd file"; @ary = glob($pattern); # expand filenames chown $uid, $gid, @ary; 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. On POSIX systems, you can detect this condition this way: use POSIX qw(sysconf _PC_CHOWN_RESTRICTED); $can_chown_giveaway = not sysconf(_PC_CHOWN_RESTRICTED); Portability issues: L<perlport/chmod>. =item chr NUMBER X<chr> X<character> X<ASCII> X<Unicode> =item chr =for Pod::Functions get character this number represents Returns the character represented by that NUMBER in the character set. For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and chr(0x263a) is a Unicode smiley face. Negative values give the Unicode replacement character (chr(0xfffd)), except under the L<bytes> pragma, where the low eight bits of the value (truncated to an integer) are used. If NUMBER is omitted, uses C<$_>. For the reverse, use L</ord>. Note that characters from 128 to 255 (inclusive) are by default internally not encoded as UTF-8 for backward compatibility reasons. See L<perlunicode> for more about Unicode. =item chroot FILENAME X<chroot> X<root> =item chroot =for Pod::Functions make directory new root for path lookups This function works like the system call by the same name: it makes the named directory the new root directory for all further pathnames that begin with a C</> by your process and all its children. (It doesn't change your current working directory, which is unaffected.) For security reasons, this call is restricted to the superuser. If FILENAME is omitted, does a C<chroot> to C<$_>. Portability issues: L<perlport/chroot>. =item close FILEHANDLE X<close> =item close =for Pod::Functions close file (or pipe or socket) handle Closes the file or pipe associated with the filehandle, flushes the IO buffers, and closes the system file descriptor. Returns true if those operations succeed and if no error was reported by any PerlIO layer. Closes the currently selected filehandle if the argument is omitted. You don't have to close FILEHANDLE if you are immediately going to do another C<open> on it, because C<open> closes it for you. (See L<open|/open FILEHANDLE>.) However, an explicit C<close> on an input file resets the line counter (C<$.>), while the implicit close done by C<open> does not. If the filehandle came from a piped open, C<close> returns false if one of the other syscalls involved fails or if its program exits with non-zero status. If the only problem was that the program exited non-zero, C<$!> will be set to C<0>. Closing a pipe also waits for the process executing on the pipe to exit--in case you wish to look at the output of the pipe afterwards--and implicitly puts the exit status value of that command into C<$?> and C<${^CHILD_ERROR_NATIVE}>. If there are multiple threads running, C<close> on a filehandle from a piped open returns true without waiting for the child process to terminate, if the filehandle is still open in another thread. Closing the read end of a pipe before the process writing to it at the other end is done writing results in the writer receiving a SIGPIPE. If the other end can't handle that, be sure to read all the data before closing the pipe. Example: open(OUTPUT, '|sort >foo') # pipe to sort or die "Can't start sort: $!"; #... # print stuff to output close OUTPUT # wait for sort to finish or warn $! ? "Error closing sort pipe: $!" : "Exit status $? from sort"; open(INPUT, 'foo') # get sort's results or die "Can't open 'foo' for input: $!"; FILEHANDLE may be an expression whose value can be used as an indirect filehandle, usually the real filehandle name or an autovivified handle. =item closedir DIRHANDLE X<closedir> =for Pod::Functions close directory handle Closes a directory opened by C<opendir> and returns the success of that system call. =item connect SOCKET,NAME X<connect> =for Pod::Functions connect to a remote socket Attempts to connect to a remote socket, just like connect(2). Returns true if it succeeded, false otherwise. NAME should be a packed address of the appropriate type for the socket. See the examples in L<perlipc/"Sockets: Client/Server Communication">. =item continue BLOCK X<continue> =item continue =for Pod::Functions optional trailing block in a while or foreach When followed by a BLOCK, C<continue> is actually a flow control statement rather than a function. If there is a C<continue> BLOCK attached to a BLOCK (typically in a C<while> or C<foreach>), it is always executed just before the conditional is about to be evaluated again, just like the third part of a C<for> loop in C. Thus it can be used to increment a loop variable, even when the loop has been continued via the C<next> statement (which is similar to the C C<continue> statement). C<last>, C<next>, or C<redo> may appear within a C<continue> block; C<last> and C<redo> behave as if they had been executed within the main block. So will C<next>, but since it will execute a C<continue> block, it may be more entertaining. while (EXPR) { ### redo always comes here do_something; } continue { ### next always comes here do_something_else; # then back the top to re-check EXPR } ### last always comes here Omitting the C<continue> section is equivalent to using an empty one, logically enough, so C<next> goes directly back to check the condition at the top of the loop. When there is no BLOCK, C<continue> is a function that falls through the current C<when> or C<default> block instead of iterating a dynamically enclosing C<foreach> or exiting a lexically enclosing C<given>. In Perl 5.14 and earlier, this form of C<continue> was only available when the C<"switch"> feature was enabled. See L<feature> and L<perlsyn/"Switch Statements"> for more information. =item cos EXPR X<cos> X<cosine> X<acos> X<arccosine> =item cos =for Pod::Functions cosine function Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, takes the cosine of C<$_>. For the inverse cosine operation, you may use the C<Math::Trig::acos()> function, or use this relation: sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } =item crypt PLAINTEXT,SALT X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> X<decrypt> X<cryptography> X<passwd> X<encrypt> =for Pod::Functions one-way passwd-style encryption Creates a digest string exactly like the crypt(3) function in the C library (assuming that you actually have a version there that has not been extirpated as a potential munition). crypt() is a one-way hash function. The PLAINTEXT and SALT are turned into a short string, called a digest, which is returned. The same PLAINTEXT and SALT will always return the same string, but there is no (known) way to get the original PLAINTEXT from the hash. Small changes in the PLAINTEXT or SALT will result in large changes in the digest. There is no decrypt function. This function isn't all that useful for cryptography (for that, look for F<Crypt> modules on your nearby CPAN mirror) and the name "crypt" is a bit of a misnomer. Instead it is primarily used to check if two pieces of text are the same without having to transmit or store the text itself. An example is checking if a correct password is given. The digest of the password is stored, not the password itself. The user types in a password that is crypt()'d with the same salt as the stored digest. If the two digests match, the password is correct. When verifying an existing digest string you should use the digest as the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used to create the digest is visible as part of the digest. This ensures crypt() will hash the new string with the same salt as the digest. This allows your code to work with the standard L<crypt|/crypt> and with more exotic implementations. In other words, assume nothing about the returned string itself nor about how many bytes of SALT may matter. Traditionally the result is a string of 13 bytes: two first bytes of the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only the first eight bytes of PLAINTEXT mattered. But alternative hashing schemes (like MD5), higher level security schemes (like C2), and implementations on non-Unix platforms may produce different strings. When choosing a new salt create a random two character string whose characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of characters is just a recommendation; the characters allowed in the salt depend solely on your system's crypt library, and Perl can't restrict what salts C<crypt()> accepts. Here's an example that makes sure that whoever runs this program knows their password: $pwd = (getpwuid($<))[1]; system "stty -echo"; print "Password: "; chomp($word = <STDIN>); print "\n"; system "stty echo"; if (crypt($word, $pwd) ne $pwd) { die "Sorry...\n"; } else { print "ok\n"; } Of course, typing in your own password to whoever asks you for it is unwise. The L<crypt|/crypt> function is unsuitable for hashing large quantities of data, not least of all because you can't get the information back. Look at the L<Digest> module for more robust algorithms. If using crypt() on a Unicode string (which I<potentially> has characters with codepoints above 255), Perl tries to make sense of the situation by trying to downgrade (a copy of) the string back to an eight-bit byte string before calling crypt() (on that copy). If that works, good. If not, crypt() dies with C<Wide character in crypt>. Portability issues: L<perlport/crypt>. =item dbmclose HASH X<dbmclose> =for Pod::Functions breaks binding on a tied dbm file [This function has been largely superseded by the C<untie> function.] Breaks the binding between a DBM file and a hash. Portability issues: L<perlport/dbmclose>. =item dbmopen HASH,DBNAME,MASK X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> =for Pod::Functions create binding on a tied dbm file [This function has been largely superseded by the L<tie|/tie VARIABLE,CLASSNAME,LIST> function.] This binds a dbm(3), ndbm(3), sdbm(3), gdbm(3), or Berkeley DB file to a hash. HASH is the name of the hash. (Unlike normal C<open>, the first argument is I<not> a filehandle, even though it looks like one). DBNAME is the name of the database (without the F<.dir> or F<.pag> extension if any). If the database does not exist, it is created with protection specified by MASK (as modified by the C<umask>). To prevent creation of the database if it doesn't exist, you may specify a MODE of 0, 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 make only one C<dbmopen> call in your program. In older versions of Perl, if your system had neither DBM nor ndbm, calling C<dbmopen> produced a fatal error; it now falls back to sdbm(3). If you don't have write access to the DBM file, you can only read hash variables, not set them. If you want to test whether you can write, either use file tests or try setting a dummy hash entry inside an C<eval> to trap the error. Note that functions such as C<keys> and C<values> may return huge lists when used on large DBM files. You may prefer to use the C<each> function to iterate over large DBM files. Example: # print out history file offsets dbmopen(%HIST,'/usr/lib/news/history',0666); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } dbmclose(%HIST); See also L<AnyDBM_File> for a more general description of the pros and cons of the various dbm approaches, as well as L<DB_File> for a particularly rich implementation. You can control which DBM library you use by loading that library before you call dbmopen(): use DB_File; dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") or die "Can't open netscape history file: $!"; Portability issues: L<perlport/dbmopen>. =item defined EXPR X<defined> X<undef> X<undefined> =item defined =for Pod::Functions test whether a value, variable, or function is defined Returns a Boolean value telling whether EXPR has a value other than the undefined value C<undef>. If EXPR is not present, C<$_> is checked. Many operations return C<undef> to indicate failure, end of file, system error, uninitialized variable, and other exceptional conditions. This function allows you to distinguish C<undef> from other values. (A simple Boolean test will not distinguish among C<undef>, zero, the empty string, and C<"0">, which are all equally false.) Note that since C<undef> is a valid scalar, its presence doesn't I<necessarily> indicate an exceptional condition: C<pop> returns C<undef> when its argument is an empty array, I<or> when the element to return happens to be C<undef>. You may also use C<defined(&func)> to check whether subroutine C<&func> has ever been defined. The return value is unaffected by any forward declarations of C<&func>. A subroutine that is not defined may still be callable: its package may have an C<AUTOLOAD> method that makes it spring into existence the first time that it is called; see L<perlsub>. Use of C<defined> on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate had ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size: if (@an_array) { print "has array elements\n" } if (%a_hash) { print "has hash members\n" } When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use L</exists> for the latter purpose. Examples: print if defined $switch{D}; print "$val\n" while defined($val = pop(@ary)); die "Can't readlink $sym: $!" unless defined($value = readlink $sym); sub foo { defined &$bar ? &$bar(@_) : die "No bar"; } $debugging = 0 unless defined $debugging; Note: Many folks tend to overuse C<defined> and are then surprised to discover that the number C<0> and C<""> (the zero-length string) are, in fact, defined values. For example, if you say "ab" =~ /a(.*)b/; The pattern match succeeds and C<$1> is defined, although it matched "nothing". It didn't really fail to match anything. Rather, it matched something that happened to be zero characters long. This is all very above-board and honest. When a function returns an undefined value, it's an admission that it couldn't give you an honest answer. So you should use C<defined> only when questioning the integrity of what you're trying to do. At other times, a simple comparison to C<0> or C<""> is what you want. See also L</undef>, L</exists>, L</ref>. =item delete EXPR X<delete> =for Pod::Functions deletes a value from a hash Given an expression that specifies an element or slice of a hash, C<delete> deletes the specified elements from that hash so that exists() on that element no longer returns true. Setting a hash element to the undefined value does not remove its key, but deleting it does; see L</exists>. In list context, returns the value or values deleted, or the last such element in scalar context. The return list's length always matches that of the argument list: deleting non-existent elements returns the undefined value in their corresponding positions. delete() may also be used on arrays and array slices, but its behavior is less straightforward. Although exists() will return false for deleted entries, deleting array elements never changes indices of existing values; use shift() or splice() for that. However, if all deleted elements fall at the end of an array, the array's size shrinks to the position of the highest element that still tests true for exists(), or to 0 if none do. B<WARNING:> Calling delete on array values is deprecated and likely to be removed in a future version of Perl. Deleting from C<%ENV> modifies the environment. Deleting from a hash tied to a DBM file deletes the entry from the DBM file. Deleting from a C<tied> hash or array may not necessarily return anything; it depends on the implementation of the C<tied> package's DELETE method, which may do whatever it pleases. The C<delete local EXPR> construct localizes the deletion to the current block at run time. Until the block exits, elements locally deleted temporarily no longer exist. See L<perlsub/"Localized deletion of elements of composite types">. %hash = (foo => 11, bar => 22, baz => 33); $scalar = delete $hash{foo}; # $scalar is 11 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 @array = delete @hash{qw(foo bar baz)}; # @array is (undef,undef,33) The following (inefficiently) deletes all the values of %HASH and @ARRAY: foreach $key (keys %HASH) { delete $HASH{$key}; } foreach $index (0 .. $#ARRAY) { delete $ARRAY[$index]; } And so do these: delete @HASH{keys %HASH}; delete @ARRAY[0 .. $#ARRAY]; But both are slower than assigning the empty list or undefining %HASH or @ARRAY, which is the customary way to empty out an aggregate: %HASH = (); # completely empty %HASH undef %HASH; # forget %HASH ever existed @ARRAY = (); # completely empty @ARRAY undef @ARRAY; # forget @ARRAY ever existed The EXPR can be arbitrarily complicated provided its final operation is an element or slice of an aggregate: delete $ref->[$x][$y]{$key}; delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys}; delete $ref->[$x][$y][$index]; delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices]; =item die LIST X<die> X<throw> X<exception> X<raise> X<$@> X<abort> =for Pod::Functions raise an exception or bail out C<die> raises an exception. Inside an C<eval> the error message is stuffed into C<$@> and the C<eval> is terminated with the undefined value. If the exception is outside of all enclosing C<eval>s, then the uncaught exception prints LIST to C<STDERR> and exits with a non-zero value. If you need to exit the process with a specific exit code, see L</exit>. Equivalent examples: die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" If the last element of LIST does not end in a newline, the current script line number and input line number (if any) are also printed, and a newline is supplied. Note that the "input line number" (also known as "chunk") is subject to whatever notion of "line" happens to be currently in effect, and is also available as the special variable C<$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. Hint: sometimes appending C<", stopped"> to your message will cause it to make better sense when the string C<"at foo line 123"> is appended. Suppose you are running script "canasta". die "/etc/games is no good"; die "/etc/games is no good, stopped"; produce, respectively /etc/games is no good at canasta line 123. /etc/games is no good, stopped at canasta line 123. If the output is empty and C<$@> already contains a value (typically from a previous eval) that value is reused after appending C<"\t...propagated">. This is useful for propagating exceptions: eval { ... }; die unless $@ =~ /Expected exception/; If the output is empty and C<$@> contains an object reference that has a C<PROPAGATE> method, that method will be called with additional file and line number parameters. The return value replaces the value in C<$@>; i.e., as if C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. If C<$@> is empty then the string C<"Died"> is used. If an uncaught exception results in interpreter exit, the exit code is determined from the values of C<$!> and C<$?> with this pseudocode: exit $! if $!; # errno exit $? >> 8 if $? >> 8; # child exit status exit 255; # last resort The intent is to squeeze as much possible information about the likely cause into the limited space of the system exit code. However, as C<$!> is the value of C's C<errno>, which can be set by any system call, this means that the value of the exit code used by C<die> can be non-predictable, so should not be relied upon, other than to be non-zero. You can also call C<die> with a reference argument, and if this is trapped within an C<eval>, C<$@> contains that reference. This permits more elaborate exception handling using objects that maintain arbitrary state about the exception. Such a scheme is sometimes preferable to matching particular string values of C<$@> with regular expressions. Because C<$@> is a global variable and C<eval> may be used within object implementations, be careful that analyzing the error object doesn't replace the reference in the global variable. It's easiest to make a local copy of the reference before any manipulations. Here's an example: use Scalar::Util "blessed"; eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) }; if (my $ev_err = $@) { if (blessed($ev_err) && $ev_err->isa("Some::Module::Exception")) { # handle Some::Module::Exception } else { # handle all other possible exceptions } } Because Perl stringifies uncaught exception messages before display, you'll probably want to overload stringification operations on exception objects. See L<overload> for details about that. You can arrange for a callback to be run just before the C<die> does its deed, by setting the C<$SIG{__DIE__}> hook. The associated handler is called with the error text and can change the error message, if it sees fit, by calling C<die> again. See L<perlvar/%SIG> for details on setting C<%SIG> entries, and L<"eval BLOCK"> for some examples. Although this feature was to be run only right before your program was to exit, this is not currently so: the C<$SIG{__DIE__}> hook is currently called even inside eval()ed blocks/strings! If one wants the hook to do nothing in such situations, put die @_ if $^S; as the first line of the handler (see L<perlvar/$^S>). Because this promotes strange action at a distance, this counterintuitive behavior may be fixed in a future release. See also exit(), warn(), and the Carp module. =item do BLOCK X<do> X<block> =for Pod::Functions turn a BLOCK into a TERM Not really a function. Returns the value of the last command in the sequence of commands indicated by BLOCK. When modified by the C<while> or C<until> loop modifier, executes the BLOCK once before testing the loop condition. (On other statements the loop modifiers test the conditional first.) C<do BLOCK> does I<not> count as a loop, so the loop control statements C<next>, C<last>, or C<redo> cannot be used to leave or restart the block. See L<perlsyn> for alternative strategies. =item do SUBROUTINE(LIST) X<do> This form of subroutine call is deprecated. SUBROUTINE can be a bareword, a scalar variable or a subroutine beginning with C<&>. =item do EXPR X<do> Uses the value of EXPR as a filename and executes the contents of the file as a Perl script. do 'stat.pl'; is just like eval `cat stat.pl`; except that it's more efficient and concise, keeps track of the current filename for error messages, searches the C<@INC> directories, and updates C<%INC> if the file is found. See L<perlvar/@INC> and L<perlvar/%INC> for these variables. It also differs in that code evaluated with C<do FILENAME> cannot see lexicals in the enclosing scope; C<eval STRING> does. It's the same, however, in that it does reparse the file every time you call it, so you probably don't want to do this inside a loop. If C<do> can read the file but cannot compile it, it returns C<undef> and sets an error message in C<$@>. If C<do> cannot read the file, it returns undef and sets C<$!> to the error. Always check C<$@> first, as compilation could fail in a way that also sets C<$!>. If the file is successfully compiled, C<do> returns the value of the last expression evaluated. Inclusion of library modules is better done with the C<use> and C<require> operators, which also do automatic error checking and raise an exception if there's a problem. You might like to use C<do> to read in a program configuration file. Manual error checking can be done this way: # read in config files: system first, then user for $file ("/share/prog/defaults.rc", "$ENV{HOME}/.someprogrc") { unless ($return = do $file) { warn "couldn't parse $file: $@" if $@; warn "couldn't do $file: $!" unless defined $return; warn "couldn't run $file" unless $return; } } =item dump LABEL X<dump> X<core> X<undump> =item dump =for Pod::Functions create an immediate core dump This function causes an immediate core dump. See also the B<-u> command-line switch in L<perlrun>, which does the same thing. Primarily this is so that you can use the B<undump> program (not supplied) to turn your core dump into an executable binary after having initialized all your variables at the beginning of the program. When the new binary is executed it will begin by executing a C<goto LABEL> (with all the restrictions that C<goto> suffers). Think of it as a goto with an intervening core dump and reincarnation. If C<LABEL> is omitted, restarts the program from the top. B<WARNING>: Any files opened at the time of the dump will I<not> be open any more when the program is reincarnated, with possible resulting confusion by Perl. This function is now largely obsolete, mostly because it's very hard to convert a core file into an executable. That's why you should now invoke it as C<CORE::dump()>, if you don't want to be warned against a possible typo. Portability issues: L<perlport/dump>. =item each HASH X<each> X<hash, iterator> =item each ARRAY X<array, iterator> =item each EXPR =for Pod::Functions retrieve the next key/value pair from a hash When called on a hash in list context, returns a 2-element list consisting of the key and value for the next element of a hash. In Perl 5.12 and later only, it will also return the index and value for the next element of an array so that you can iterate over it; older Perls consider this a syntax error. When called in scalar context, returns only the key (not the value) in a hash, or the index in an array. Hash entries are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be in the same order as either the C<keys> or C<values> function would produce on the same (unmodified) hash. Since Perl 5.8.2 the ordering can be different even between different runs of Perl for security reasons (see L<perlsec/"Algorithmic Complexity Attacks">). After C<each> has returned all entries from the hash or array, the next call to C<each> returns the empty list in list context and C<undef> in scalar context; the next call following I<that> one restarts iteration. Each hash or array has its own internal iterator, accessed by C<each>, C<keys>, and C<values>. The iterator is implicitly reset when C<each> has reached the end as just described; it can be explicitly reset by calling C<keys> or C<values> on the hash or array. If you add or delete a hash's elements while iterating over it, entries may be skipped or duplicated--so don't do that. Exception: In the current implementation, it is always safe to delete the item most recently returned by C<each()>, so the following code works properly: while (($key, $value) = each %hash) { print $key, "\n"; delete $hash{$key}; # This is safe } This prints out your environment like the printenv(1) program, but in a different order: while (($key,$value) = each %ENV) { print "$key=$value\n"; } Starting with Perl 5.14, C<each> can take a scalar EXPR, which must hold reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of C<each> is considered highly experimental. The exact behaviour may change in a future version of Perl. while (($key,$value) = each $hashref) { ... } To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.012; # so keys/values/each work on arrays use 5.014; # so keys/values/each work on scalars (experimental) See also C<keys>, C<values>, and C<sort>. =item eof FILEHANDLE X<eof> X<end of file> X<end-of-file> =item eof () =item eof =for Pod::Functions test a filehandle for its end Returns 1 if the next read on FILEHANDLE will return end of file I<or> if FILEHANDLE is not open. FILEHANDLE may be an expression whose value gives the real filehandle. (Note that this function actually reads a character and then C<ungetc>s it, so isn't useful in an interactive context.) Do not read from a terminal file (or call C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such as terminals may lose the end-of-file condition if you do. An C<eof> without an argument uses the last file read. Using C<eof()> with empty parentheses is different. It refers to the pseudo file formed from the files listed on the command line and accessed via the C<< <> >> operator. Since C<< <> >> isn't explicitly opened, as a normal filehandle is, an C<eof()> before C<< <> >> has been used will cause C<@ARGV> to be examined to determine if input is available. Similarly, an C<eof()> after C<< <> >> has returned end-of-file will assume you are processing another C<@ARGV> list, and if you haven't set C<@ARGV>, will read input from C<STDIN>; see L<perlop/"I/O Operators">. In a C<< while (<>) >> loop, C<eof> or C<eof(ARGV)> can be used to detect the end of each file, whereas C<eof()> will detect the end of the very last file only. Examples: # reset line numbering on each input file while (<>) { next if /^\s*#/; # skip comments print "$.\t$_"; } continue { close ARGV if eof; # Not eof()! } # insert dashes just before last line of last file while (<>) { if (eof()) { # check for end of last file print "--------------\n"; } print; last if eof(); # needed if we're reading from a terminal } Practical hint: you almost never need to use C<eof> in Perl, because the input operators typically return C<undef> when they run out of data or encounter an error. =item eval EXPR X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> X<error, handling> X<exception, handling> =item eval BLOCK =item eval =for Pod::Functions catch exceptions or compile and run code In the first form, the return value of EXPR is parsed and executed as if it were a little Perl program. The value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program. This means, that in particular, any outer lexical variables are visible to it, and any package variable settings or subroutine and format definitions remain afterwards. Note that the value is parsed every time the C<eval> executes. If EXPR is omitted, evaluates C<$_>. This form is typically used to delay parsing and subsequent execution of the text of EXPR until run time. If the C<unicode_eval> feature is enabled (which is the default under a C<use 5.16> or higher declaration), EXPR or C<$_> is treated as a string of characters, so C<use utf8> declarations have no effect, and source filters are forbidden. In the absence of the C<unicode_eval> feature, the string will sometimes be treated as characters and sometimes as bytes, depending on the internal encoding, and source filters activated within the C<eval> exhibit the erratic, but historical, behaviour of affecting some outer file scope that is still compiling. See also the L</evalbytes> keyword, which always treats its input as a byte stream and works properly with source filters, and the L<feature> pragma. In the second form, the code within the BLOCK is parsed only once--at the same time the code surrounding the C<eval> itself was parsed--and executed within the context of the current Perl program. This form is typically used to trap exceptions more efficiently than the first (see below), while also providing the benefit of checking the code within BLOCK at compile time. The final semicolon, if any, may be omitted from the value of EXPR or within the BLOCK. In both forms, the value returned is the value of the last expression evaluated inside the mini-program; a return statement may be also used, just as with subroutines. The expression providing the return value is evaluated in void, scalar, or list context, depending on the context of the C<eval> itself. See L</wantarray> for more on how the evaluation context can be determined. If there is a syntax error or runtime error, or a C<die> statement is executed, C<eval> returns C<undef> in scalar context or an empty list in list context, and C<$@> is set to the error message. (Prior to 5.16, a bug caused C<undef> to be returned in list context for syntax errors, but not for runtime errors.) If there was no error, C<$@> is set to the empty string. A control flow operator like C<last> or C<goto> can bypass the setting of C<$@>. Beware that using C<eval> neither silences Perl from printing warnings to STDERR, nor does it stuff the text of warning messages into C<$@>. To do either of those, you have to use the C<$SIG{__WARN__}> facility, or turn off warnings inside the BLOCK or EXPR using S<C<no warnings 'all'>>. See L</warn>, L<perlvar>, L<warnings> and L<perllexwarn>. Note that, because C<eval> traps otherwise-fatal errors, it is useful for determining whether a particular feature (such as C<socket> or C<symlink>) is implemented. It is also Perl's exception-trapping mechanism, where the die operator is used to raise exceptions. If you want to trap errors when loading an XS module, some problems with the binary interface (such as Perl version skew) may be fatal even with C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See L<perlrun>. If the code to be executed doesn't vary, you may use the eval-BLOCK form to trap run-time errors without incurring the penalty of recompiling each time. The error, if any, is still returned in C<$@>. Examples: # make divide-by-zero nonfatal eval { $answer = $a / $b; }; warn $@ if $@; # same thing, but less efficient eval '$answer = $a / $b'; warn $@ if $@; # a compile-time error eval { $answer = }; # WRONG # a run-time error eval '$answer ='; # sets $@ Using the C<eval{}> form as an exception trap in libraries does have some issues. Due to the current arguably broken state of C<__DIE__> hooks, you may wish not to trigger any C<__DIE__> hooks that user code may have installed. You can use the C<local $SIG{__DIE__}> construct for this purpose, as this example shows: # a private exception trap for divide-by-zero eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; warn $@ if $@; This is especially significant, given that C<__DIE__> hooks can call C<die> again, which has the effect of changing their error messages: # __DIE__ hooks may modify error messages { local $SIG{'__DIE__'} = sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x }; eval { die "foo lives here" }; print $@ if $@; # prints "bar lives here" } Because this promotes action at a distance, this counterintuitive behavior may be fixed in a future release. With an C<eval>, you should be especially careful to remember what's being looked at when: eval $x; # CASE 1 eval "$x"; # CASE 2 eval '$x'; # CASE 3 eval { $x }; # CASE 4 eval "\$$x++"; # CASE 5 $$x++; # CASE 6 Cases 1 and 2 above behave identically: they run the code contained in the variable $x. (Although case 2 has misleading double quotes making the reader wonder what else might be happening (nothing is).) Cases 3 and 4 likewise behave in the same way: they run the code C<'$x'>, which does nothing but return the value of $x. (Case 4 is preferred for purely visual reasons, but it also has the advantage of compiling at compile-time instead of at run-time.) Case 5 is a place where normally you I<would> like to use double quotes, except that in this particular situation, you can just use symbolic references instead, as in case 6. Before Perl 5.14, the assignment to C<$@> occurred before restoration of localized variables, which means that for your code to run on older versions, a temporary is required if you want to mask some but not all errors: # alter $@ on nefarious repugnancy only { my $e; { local $@; # protect existing $@ eval { test_repugnancy() }; # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only $@ =~ /nefarious/ and $e = $@; } die $e if defined $e } C<eval BLOCK> does I<not> count as a loop, so the loop control statements C<next>, C<last>, or C<redo> cannot be used to leave or restart the block. An C<eval ''> executed within the C<DB> package doesn't see the usual surrounding lexical scope, but rather the scope of the first non-DB piece of code that called it. You don't normally need to worry about this unless you are writing a Perl debugger. =item evalbytes EXPR X<evalbytes> =item evalbytes =for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream This function is like L</eval> with a string argument, except it always parses its argument, or C<$_> if EXPR is omitted, as a string of bytes. A string containing characters whose ordinal value exceeds 255 results in an error. Source filters activated within the evaluated code apply to the code itself. This function is only available under the C<evalbytes> feature, a C<use v5.16> (or higher) declaration, or with a C<CORE::> prefix. See L<feature> for more information. =item exec LIST X<exec> X<execute> =item exec PROGRAM LIST =for Pod::Functions abandon this program to run another The C<exec> function executes a system command I<and never returns>; use C<system> instead of C<exec> if you want it to return. It fails and returns false only if the command does not exist I<and> it is executed directly instead of via your system's command shell (see below). Since it's a common mistake to use C<exec> instead of C<system>, Perl warns you if C<exec> is called in void context and if there is a following statement that isn't C<die>, C<warn>, or C<exit> (if C<-w> is set--but you always do that, right?). If you I<really> want to follow an C<exec> with some other statement, you can use one of these styles to avoid the warning: exec ('foo') or print STDERR "couldn't exec foo: $!"; { exec ('foo') }; print STDERR "couldn't exec foo: $!"; If there is more than one argument in LIST, or if LIST is an array with more than one value, calls execvp(3) with the arguments in LIST. If there is only one scalar argument or an array with one element in it, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is C</bin/sh -c> on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to C<execvp>, which is more efficient. Examples: exec '/bin/echo', 'Your arguments are: ', @ARGV; exec "sort $outfile | uniq"; If you don't really want to execute the first argument, but want to lie to the program you are executing about its own name, you can specify the program you actually want to run as an "indirect object" (without a comma) in front of the LIST. (This always forces interpretation of the LIST as a multivalued list, even if there is only a single scalar in the list.) Example: $shell = '/bin/csh'; exec $shell '-sh'; # pretend it's a login shell or, more directly, exec {'/bin/csh'} '-sh'; # pretend it's a login shell When the arguments get executed via the system shell, results are subject to its quirks and capabilities. See L<perlop/"`STRING`"> for details. Using an indirect object with C<exec> or C<system> is also more secure. This usage (which also works fine with system()) forces interpretation of the arguments as a multivalued list, even if the list had just one argument. That way you're safe from the shell expanding wildcards or splitting up words with whitespace in them. @args = ( "echo surprise" ); exec @args; # subject to shell escapes # if @args == 1 exec { $args[0] } @args; # safe even with one-arg list The first version, the one without the indirect object, ran the I<echo> program, passing it C<"surprise"> an argument. The second version didn't; it tried to run a program named I<"echo surprise">, didn't find it, and set C<$?> to a non-zero value indicating failure. Beginning with v5.6.0, Perl attempts to flush all files opened for output before the exec, but this may not be supported on some platforms (see L<perlport>). To be safe, you may need to set C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of C<IO::Handle> on any open handles to avoid lost output. Note that C<exec> will not call your C<END> blocks, nor will it invoke C<DESTROY> methods on your objects. Portability issues: L<perlport/exec>. =item exists EXPR X<exists> X<autovivification> =for Pod::Functions test whether a hash key is present Given an expression that specifies an element of a hash, returns true if the specified element in the hash has ever been initialized, even if the corresponding value is undefined. print "Exists\n" if exists $hash{$key}; print "Defined\n" if defined $hash{$key}; print "True\n" if $hash{$key}; exists may also be called on array elements, but its behavior is much less obvious and is strongly tied to the use of L</delete> on arrays. B<Be aware> that calling exists on array values is deprecated and likely to be removed in a future version of Perl. print "Exists\n" if exists $array[$index]; print "Defined\n" if defined $array[$index]; print "True\n" if $array[$index]; A hash or array element can be true only if it's defined and defined only if it exists, but the reverse doesn't necessarily hold true. Given an expression that specifies the name of a subroutine, returns true if the specified subroutine has ever been declared, even if it is undefined. Mentioning a subroutine name for exists or defined does not count as declaring it. Note that a subroutine that does not exist may still be callable: its package may have an C<AUTOLOAD> method that makes it spring into existence the first time that it is called; see L<perlsub>. print "Exists\n" if exists &subroutine; print "Defined\n" if defined &subroutine; Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash or array key lookup or subroutine name: if (exists $ref->{A}->{B}->{$key}) { } if (exists $hash{A}{B}{$key}) { } if (exists $ref->{A}->{B}->[$ix]) { } if (exists $hash{A}{B}[$ix]) { } if (exists &{$ref->{A}{B}{$key}}) { } Although the most deeply nested array or hash element will not spring into existence just because its existence was tested, any intervening ones will. Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring into existence due to the existence test for the $key element above. This happens anywhere the arrow operator is used, including even here: undef $ref; if (exists $ref->{"Some key"}) { } print $ref; # prints HASH(0x80d3d5c) This surprising autovivification in what does not at first--or even second--glance appear to be an lvalue context may be fixed in a future release. Use of a subroutine call, rather than a subroutine name, as an argument to exists() is an error. exists ⊂ # OK exists &sub(); # Error =item exit EXPR X<exit> X<terminate> X<abort> =item exit =for Pod::Functions terminate this program Evaluates EXPR and exits immediately with that value. Example: $ans = <STDIN>; exit 0 if $ans =~ /^[Xx]/; See also C<die>. If EXPR is omitted, exits with C<0> status. The only universally recognized values for EXPR are C<0> for success and C<1> for error; other values are subject to interpretation depending on the environment in which the Perl program is running. For example, exiting 69 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause the mailer to return the item undelivered, but that's not true everywhere. Don't use C<exit> to abort a subroutine if there's any chance that someone might want to trap whatever error happened. Use C<die> instead, which can be trapped by an C<eval>. The exit() function does not always exit immediately. It calls any defined C<END> routines first, but these C<END> routines may not themselves abort the exit. Likewise any object destructors that need to be called are called before the real exit. C<END> routines and destructors can change the exit status by modifying C<$?>. If this is a problem, you can call C<POSIX::_exit($status)> to avoid END and destructor processing. See L<perlmod> for details. Portability issues: L<perlport/exit>. =item exp EXPR X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> =item exp =for Pod::Functions raise I<e> to a power Returns I<e> (the natural logarithm base) to the power of EXPR. If EXPR is omitted, gives C<exp($_)>. =item fc EXPR X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> =item fc =for Pod::Functions +fc return casefolded version of a string Returns the casefolded version of EXPR. This is the internal function implementing the C<\F> escape in double-quoted strings. Casefolding is the process of mapping strings to a form where case differences are erased; comparing two strings in their casefolded form is effectively a way of asking if two strings are equal, regardless of case. Roughly, if you ever found yourself writing this lc($this) eq lc($that) # Wrong! # or uc($this) eq uc($that) # Also wrong! # or $this =~ /\Q$that/i # Right! Now you can write fc($this) eq fc($that) And get the correct results. Perl only implements the full form of casefolding. For further information on casefolding, refer to the Unicode Standard, specifically sections 3.13 C<Default Case Operations>, 4.2 C<Case-Normative>, and 5.18 C<Case Mappings>, available at L<http://www.unicode.org/versions/latest/>, as well as the Case Charts available at L<http://www.unicode.org/charts/case/>. If EXPR is omitted, uses C<$_>. This function behaves the same way under various pragma, such as in a locale, as L</lc> does. While the Unicode Standard defines two additional forms of casefolding, one for Turkic languages and one that never maps one character into multiple characters, these are not provided by the Perl core; However, the CPAN module C<Unicode::Casing> may be used to provide an implementation. This keyword is available only when the C<"fc"> feature is enabled, or when prefixed with C<CORE::>; See L<feature>. Alternately, include a C<use v5.16> or later to the current scope. =item fcntl FILEHANDLE,FUNCTION,SCALAR X<fcntl> =for Pod::Functions file control system call Implements the fcntl(2) function. You'll probably have to say use Fcntl; first to get the correct constant definitions. Argument processing and value returned work just like C<ioctl> below. For example: use Fcntl; fcntl($filehandle, F_GETFL, $packed_return_buffer) or die "can't fcntl F_GETFL: $!"; You don't have to check for C<defined> on the return from C<fcntl>. Like C<ioctl>, it maps a C<0> return from the system call into C<"0 but true"> in Perl. This string is true in boolean context and C<0> in numeric context. It is also exempt from the normal B<-w> warnings on improper numeric conversions. Note that C<fcntl> raises an exception if used on a machine that doesn't implement fcntl(2). See the Fcntl module or your fcntl(2) manpage to learn what functions are available on your system. Here's an example of setting a filehandle named C<REMOTE> to be non-blocking at the system level. You'll have to negotiate C<$|> on your own, though. use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); $flags = fcntl(REMOTE, F_GETFL, 0) or die "Can't get flags for the socket: $!\n"; $flags = fcntl(REMOTE, F_SETFL, $flags | O_NONBLOCK) or die "Can't set flags for the socket: $!\n"; Portability issues: L<perlport/fcntl>. =item __FILE__ X<__FILE__> =for Pod::Functions the name of the current source file A special token that returns the name of the file in which it occurs. =item fileno FILEHANDLE X<fileno> =for Pod::Functions return file descriptor from filehandle Returns the file descriptor for a filehandle, or undefined if the filehandle is not open. If there is no real file descriptor at the OS level, as can happen with filehandles connected to memory objects via C<open> with a reference for the third argument, -1 is returned. This is mainly useful for constructing bitmaps for C<select> and low-level POSIX tty-handling operations. If FILEHANDLE is an expression, the value is taken as an indirect filehandle, generally its name. You can use this to find out whether two handles refer to the same underlying descriptor: if (fileno(THIS) == fileno(THAT)) { print "THIS and THAT are dups\n"; } =item flock FILEHANDLE,OPERATION X<flock> X<lock> X<locking> =for Pod::Functions lock an entire file with an advisory lock Calls flock(2), or an emulation of it, on FILEHANDLE. Returns true for success, false on failure. Produces a fatal error if used on a machine that doesn't implement flock(2), fcntl(2) locking, or lockf(3). C<flock> is Perl's portable file-locking interface, although it locks entire files only, not records. Two potentially non-obvious but traditional C<flock> semantics are that it waits indefinitely until the lock is granted, and that its locks are B<merely advisory>. Such discretionary locks are more flexible, but offer fewer guarantees. This means that programs that do not also use C<flock> may modify files locked with C<flock>. See L<perlport>, your port's specific documentation, and your system-specific local manpages for details. It's best to assume traditional behavior if you're writing portable programs. (But if you're not, you should as always feel perfectly free to write for your own system's idiosyncrasies (sometimes called "features"). Slavish adherence to portability concerns shouldn't get in the way of your getting your job done.) OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but you can use the symbolic names if you import them from the L<Fcntl> module, either individually, or as a group using the C<:flock> tag. LOCK_SH requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN releases a previously requested lock. If LOCK_NB is bitwise-or'ed with LOCK_SH or LOCK_EX, then C<flock> returns immediately rather than blocking waiting for the lock; check the return status to see if you got it. To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE before locking or unlocking it. Note that the emulation built with lockf(3) doesn't provide shared locks, and it requires that FILEHANDLE be open with write intent. These are the semantics that lockf(3) implements. Most if not all systems implement lockf(3) in terms of fcntl(2) locking, though, so the differing semantics shouldn't bite too many people. Note that the fcntl(2) emulation of flock(3) requires that FILEHANDLE be open with read intent to use LOCK_SH and requires that it be open with write intent to use LOCK_EX. Note also that some versions of C<flock> cannot lock things over the network; you would need to use the more system-specific C<fcntl> for that. If you like you can force Perl to ignore your system's flock(2) function, and so provide its own fcntl(2)-based emulation, by passing the switch C<-Ud_flock> to the F<Configure> program when you configure and build a new Perl. Here's a mailbox appender for BSD systems. use Fcntl qw(:flock SEEK_END); # import LOCK_* and SEEK_END constants sub lock { my ($fh) = @_; flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n"; # and, in case someone appended while we were waiting... seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n"; } sub unlock { my ($fh) = @_; flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n"; } open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}") or die "Can't open mailbox: $!"; lock($mbox); print $mbox $msg,"\n\n"; unlock($mbox); On systems that support a real flock(2), locks are inherited across fork() calls, whereas those that must resort to the more capricious fcntl(2) function lose their locks, making it seriously harder to write servers. See also L<DB_File> for other flock() examples. Portability issues: L<perlport/flock>. =item fork X<fork> X<child> X<parent> =for Pod::Functions create a new process just like this one Does a fork(2) system call to create a new process running the same program at the same point. It returns the child pid to the parent process, C<0> to the child process, or C<undef> if the fork is unsuccessful. File descriptors (and sometimes locks on those descriptors) are shared, while everything else is copied. On most systems supporting fork(), great care has gone into making it extremely efficient (for example, using copy-on-write technology on data pages), making it the dominant paradigm for multitasking over the last few decades. Beginning with v5.6.0, Perl attempts to flush all files opened for output before forking the child process, but this may not be supported on some platforms (see L<perlport>). To be safe, you may need to set C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of C<IO::Handle> on any open handles to avoid duplicate output. If you C<fork> without ever waiting on your children, you will accumulate zombies. On some systems, you can avoid this by setting C<$SIG{CHLD}> to C<"IGNORE">. See also L<perlipc> for more examples of forking and reaping moribund children. Note that if your forked child inherits system file descriptors like STDIN and STDOUT that are actually connected by a pipe or socket, even if you exit, then the remote server (such as, say, a CGI script or a backgrounded job launched from a remote shell) won't think you're done. You should reopen those to F</dev/null> if it's any issue. On some platforms such as Windows, where the fork() system call is not available, Perl can be built to emulate fork() in the Perl interpreter. The emulation is designed, at the level of the Perl program, to be as compatible as possible with the "Unix" fork(). However it has limitations that have to be considered in code intended to be portable. See L<perlfork> for more details. Portability issues: L<perlport/fork>. =item format X<format> =for Pod::Functions declare a picture format with use by the write() function Declare a picture format for use by the C<write> function. For example: format Something = Test: @<<<<<<<< @||||| @>>>>> $str, $%, '$' . int($num) . $str = "widget"; $num = $cost/$quantity; $~ = 'Something'; write; See L<perlform> for many details and examples. =item formline PICTURE,LIST X<formline> =for Pod::Functions internal function used for formats This is an internal function used by C<format>s, though you may call it, too. It formats (see L<perlform>) a list of values according to the contents of PICTURE, placing the output into the format output accumulator, C<$^A> (or C<$ACCUMULATOR> in English). Eventually, when a C<write> is done, the contents of C<$^A> are written to some filehandle. You could also read C<$^A> and then set C<$^A> back to C<"">. Note that a format typically does one C<formline> per line of form, but the C<formline> function itself doesn't care how many newlines are embedded in the PICTURE. This means that the C<~> and C<~~> tokens treat the entire PICTURE as a single line. You may therefore need to use multiple formlines to implement a single record format, just like the C<format> compiler. Be careful if you put double quotes around the picture, because an C<@> character may be taken to mean the beginning of an array name. C<formline> always returns true. See L<perlform> for other examples. If you are trying to use this instead of C<write> to capture the output, you may find it easier to open a filehandle to a scalar (C<< open $fh, ">", \$output >>) and write to that instead. =item getc FILEHANDLE X<getc> X<getchar> X<character> X<file, read> =item getc =for Pod::Functions get the next character from the filehandle Returns the next character from the input file attached to FILEHANDLE, or the undefined value at end of file or if there was an error (in the latter case C<$!> is set). If FILEHANDLE is omitted, reads from STDIN. This is not particularly efficient. However, it cannot be used by itself to fetch single characters without waiting for the user to hit enter. For that, try something more like: if ($BSD_STYLE) { system "stty cbreak </dev/tty >/dev/tty 2>&1"; } else { system "stty", '-icanon', 'eol', "\001"; } $key = getc(STDIN); if ($BSD_STYLE) { system "stty -cbreak </dev/tty >/dev/tty 2>&1"; } else { system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL } print "\n"; Determination of whether $BSD_STYLE should be set is left as an exercise to the reader. The C<POSIX::getattr> function can do this more portably on systems purporting POSIX compliance. See also the C<Term::ReadKey> module from your nearest CPAN site; details on CPAN can be found under L<perlmodlib/CPAN>. =item getlogin X<getlogin> X<login> =for Pod::Functions return who logged in at this tty This implements the C library function of the same name, which on most systems returns the current login from F</etc/utmp>, if any. If it returns the empty string, use C<getpwuid>. $login = getlogin || getpwuid($<) || "Kilroy"; Do not consider C<getlogin> for authentication: it is not as secure as C<getpwuid>. Portability issues: L<perlport/getlogin>. =item getpeername SOCKET X<getpeername> X<peer> =for Pod::Functions find the other end of a socket connection Returns the packed sockaddr address of the other end of the SOCKET connection. use Socket; $hersockaddr = getpeername(SOCK); ($port, $iaddr) = sockaddr_in($hersockaddr); $herhostname = gethostbyaddr($iaddr, AF_INET); $herstraddr = inet_ntoa($iaddr); =item getpgrp PID X<getpgrp> X<group> =for Pod::Functions get process group Returns the current process group for the specified PID. Use a PID of C<0> to get the current process group for the current process. Will raise an exception if used on a machine that doesn't implement getpgrp(2). If PID is omitted, returns the process group of the current process. Note that the POSIX version of C<getpgrp> does not accept a PID argument, so only C<PID==0> is truly portable. Portability issues: L<perlport/getpgrp>. =item getppid X<getppid> X<parent> X<pid> =for Pod::Functions get parent process ID Returns the process id of the parent process. Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work around non-POSIX thread semantics the minority of Linux systems (and Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation has since been removed. See the documentation for L<$$|perlvar/$$> for details. Portability issues: L<perlport/getppid>. =item getpriority WHICH,WHO X<getpriority> X<priority> X<nice> =for Pod::Functions get current nice value Returns the current priority for a process, a process group, or a user. (See L<getpriority(2)>.) Will raise a fatal exception if used on a machine that doesn't implement getpriority(2). Portability issues: L<perlport/getpriority>. =item getpwnam NAME X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> X<endnetent> X<endprotoent> X<endservent> =for Pod::Functions get passwd record given user login name =item getgrnam NAME =for Pod::Functions get group record given group name =item gethostbyname NAME =for Pod::Functions get host record given name =item getnetbyname NAME =for Pod::Functions get networks record given name =item getprotobyname NAME =for Pod::Functions get protocol record given name =item getpwuid UID =for Pod::Functions get passwd record given user ID =item getgrgid GID =for Pod::Functions get group record given group user ID =item getservbyname NAME,PROTO =for Pod::Functions get services record given its name =item gethostbyaddr ADDR,ADDRTYPE =for Pod::Functions get host record given its address =item getnetbyaddr ADDR,ADDRTYPE =for Pod::Functions get network record given its address =item getprotobynumber NUMBER =for Pod::Functions get protocol record numeric protocol =item getservbyport PORT,PROTO =for Pod::Functions get services record given numeric port =item getpwent =for Pod::Functions get next passwd record =item getgrent =for Pod::Functions get next group record =item gethostent =for Pod::Functions get next hosts record =item getnetent =for Pod::Functions get next networks record =item getprotoent =for Pod::Functions get next protocols record =item getservent =for Pod::Functions get next services record =item setpwent =for Pod::Functions prepare passwd file for use =item setgrent =for Pod::Functions prepare group file for use =item sethostent STAYOPEN =for Pod::Functions prepare hosts file for use =item setnetent STAYOPEN =for Pod::Functions prepare networks file for use =item setprotoent STAYOPEN =for Pod::Functions prepare protocols file for use =item setservent STAYOPEN =for Pod::Functions prepare services file for use =item endpwent =for Pod::Functions be done using passwd file =item endgrent =for Pod::Functions be done using group file =item endhostent =for Pod::Functions be done using hosts file =item endnetent =for Pod::Functions be done using networks file =item endprotoent =for Pod::Functions be done using protocols file =item endservent =for Pod::Functions be done using services file These routines are the same as their counterparts in the system C library. In list context, the return values from the various get routines are as follows: ($name,$passwd,$uid,$gid, $quota,$comment,$gcos,$dir,$shell,$expire) = getpw* ($name,$passwd,$gid,$members) = getgr* ($name,$aliases,$addrtype,$length,@addrs) = gethost* ($name,$aliases,$addrtype,$net) = getnet* ($name,$aliases,$proto) = getproto* ($name,$aliases,$port,$proto) = getserv* (If the entry doesn't exist you get an empty list.) The exact meaning of the $gcos field varies but it usually contains the real name of the user (as opposed to the login name) and other information pertaining to the user. Beware, however, that in many system users are able to change this information and therefore it cannot be trusted and therefore the $gcos is tainted (see L<perlsec>). The $passwd and $shell, user's encrypted password and login shell, are also tainted, for the same reason. In scalar context, you get the name, unless the function was a lookup by name, in which case you get the other thing, whatever it is. (If the entry doesn't exist you get the undefined value.) For example: $uid = getpwnam($name); $name = getpwuid($num); $name = getpwent(); $gid = getgrnam($name); $name = getgrgid($num); $name = getgrent(); #etc. In I<getpw*()> the fields $quota, $comment, and $expire are special in that they are unsupported on many systems. If the $quota is unsupported, it is an empty scalar. If it is supported, it usually encodes the disk quota. If the $comment field is unsupported, it is an empty scalar. If it is supported it usually encodes some administrative comment about the user. In some systems the $quota field may be $change or $age, fields that have to do with password aging. In some systems the $comment field may be $class. The $expire field, if present, encodes the expiration period of the account or the password. For the availability and the exact meaning of these fields in your system, please consult getpwnam(3) and your system's F<pwd.h> file. You can also find out from within Perl what your $quota and $comment fields mean and whether you have the $expire field by using the C<Config> module and the values C<d_pwquota>, C<d_pwage>, C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password files are supported only if your vendor has implemented them in the intuitive fashion that calling the regular C library routines gets the shadow versions if you're running under privilege or if there exists the shadow(3) functions as found in System V (this includes Solaris and Linux). Those systems that implement a proprietary shadow password facility are unlikely to be supported. The $members value returned by I<getgr*()> is a space-separated list of the login names of the members of the group. For the I<gethost*()> functions, if the C<h_errno> variable is supported in C, it will be returned to you via C<$?> if the function call fails. The C<@addrs> value returned by a successful call is a list of raw addresses returned by the corresponding library call. In the Internet domain, each address is four bytes long; you can unpack it by saying something like: ($a,$b,$c,$d) = unpack('W4',$addr[0]); The Socket library makes this slightly easier: use Socket; $iaddr = inet_aton("127.1"); # or whatever address $name = gethostbyaddr($iaddr, AF_INET); # or going the other way $straddr = inet_ntoa($iaddr); In the opposite way, to resolve a hostname to the IP address you can write this: use Socket; $packed_ip = gethostbyname("www.perl.org"); if (defined $packed_ip) { $ip_address = inet_ntoa($packed_ip); } Make sure C<gethostbyname()> is called in SCALAR context and that its return value is checked for definedness. The C<getprotobynumber> function, even though it only takes one argument, has the precedence of a list operator, so beware: getprotobynumber $number eq 'icmp' # WRONG getprotobynumber($number eq 'icmp') # actually means this getprotobynumber($number) eq 'icmp' # better this way If you get tired of remembering which element of the return list contains which return value, by-name interfaces are provided in standard modules: C<File::stat>, C<Net::hostent>, C<Net::netent>, C<Net::protoent>, C<Net::servent>, C<Time::gmtime>, C<Time::localtime>, and C<User::grent>. These override the normal built-ins, supplying versions that return objects with the appropriate names for each field. For example: use File::stat; use User::pwent; $is_his = (stat($filename)->uid == pwent($whoever)->uid); Even though it looks as though they're the same method calls (uid), they aren't, because a C<File::stat> object is different from a C<User::pwent> object. Portability issues: L<perlport/getpwnam> to L<perlport/endservent>. =item getsockname SOCKET X<getsockname> =for Pod::Functions retrieve the sockaddr for a given socket Returns the packed sockaddr address of this end of the SOCKET connection, in case you don't know the address because you have several different IPs that the connection might have come in on. use Socket; $mysockaddr = getsockname(SOCK); ($port, $myaddr) = sockaddr_in($mysockaddr); printf "Connect to %s [%s]\n", scalar gethostbyaddr($myaddr, AF_INET), inet_ntoa($myaddr); =item getsockopt SOCKET,LEVEL,OPTNAME X<getsockopt> =for Pod::Functions get socket options on a given socket Queries the option named OPTNAME associated with SOCKET at a given LEVEL. Options may exist at multiple protocol levels depending on the socket type, but at least the uppermost socket level SOL_SOCKET (defined in the C<Socket> module) will exist. To query options at another level the protocol number of the appropriate protocol controlling the option should be supplied. For example, to indicate that an option is to be interpreted by the TCP protocol, LEVEL should be set to the protocol number of TCP, which you can get using C<getprotobyname>. The function returns a packed string representing the requested socket option, or C<undef> on error, with the reason for the error placed in C<$!>. Just what is in the packed string depends on LEVEL and OPTNAME; consult getsockopt(2) for details. A common case is that the option is an integer, in which case the result is a packed integer, which you can decode using C<unpack> with the C<i> (or C<I>) format. Here's an example to test whether Nagle's algorithm is enabled on a socket: use Socket qw(:all); defined(my $tcp = getprotobyname("tcp")) or die "Could not determine the protocol number for tcp"; # my $tcp = IPPROTO_TCP; # Alternative my $packed = getsockopt($socket, $tcp, TCP_NODELAY) or die "getsockopt TCP_NODELAY: $!"; my $nodelay = unpack("I", $packed); print "Nagle's algorithm is turned ", $nodelay ? "off\n" : "on\n"; Portability issues: L<perlport/getsockopt>. =item glob EXPR X<glob> X<wildcard> X<filename, expansion> X<expand> =item glob =for Pod::Functions expand filenames using wildcards In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell F</bin/csh> would do. In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted. This is the internal function implementing the C<< <*.c> >> operator, but you can use it directly. If EXPR is omitted, C<$_> is used. The C<< <*.c> >> operator is discussed in more detail in L<perlop/"I/O Operators">. Note that C<glob> splits its arguments on whitespace and treats each segment as separate pattern. As such, C<glob("*.c *.h")> matches all files with a F<.c> or F<.h> extension. The expression C<glob(".* *")> matches all files in the current working directory. If you want to glob filenames that might contain whitespace, you'll have to use extra quotes around the spacey filename to protect it. For example, to glob filenames that have an C<e> followed by a space followed by an C<f>, use either of: @spacies = <"*e f*">; @spacies = glob '"*e f*"'; @spacies = glob q("*e f*"); If you had to get a variable through, you could do this: @spacies = glob "'*${var}e f*'"; @spacies = glob qq("*${var}e f*"); If non-empty braces are the only wildcard characters used in the C<glob>, no filenames are matched, but potentially many strings are returned. For example, this produces nine strings, one for each pairing of fruits and colors: @many = glob "{apple,tomato,cherry}={green,yellow,red}"; Beginning with v5.6.0, this operator is implemented using the standard C<File::Glob> extension. See L<File::Glob> for details, including C<bsd_glob> which does not treat whitespace as a pattern separator. Portability issues: L<perlport/glob>. =item gmtime EXPR X<gmtime> X<UTC> X<Greenwich> =item gmtime =for Pod::Functions convert UNIX time into record or string using Greenwich time Works just like L</localtime> but the returned values are localized for the standard Greenwich time zone. Note: When called in list context, $isdst, the last value returned by gmtime, is always C<0>. There is no Daylight Saving Time in GMT. Portability issues: L<perlport/gmtime>. =item goto LABEL X<goto> X<jump> X<jmp> =item goto EXPR =item goto &NAME =for Pod::Functions create spaghetti code The C<goto-LABEL> form finds the statement labeled with LABEL and resumes execution there. It can't be used to get out of a block or subroutine given to C<sort>. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as C<last> or C<die>. The author of Perl has never felt the need to use this form of C<goto> (in Perl, that is; C is another matter). (The difference is that C does not offer named loops combined with loop control. Perl does, and this replaces most structured uses of C<goto> in other languages.) The C<goto-EXPR> form expects a label name, whose scope will be resolved dynamically. This allows for computed C<goto>s per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability: goto ("FOO", "BAR", "GLARCH")[$i]; As shown in this example, C<goto-EXPR> is exempt from the "looks like a function" rule. A pair of parentheses following it does not (necessarily) delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>. Use of C<goto-LABEL> or C<goto-EXPR> to jump into a construct is deprecated and will issue a warning. Even then, it may not be used to go into any construct that requires initialization, such as a subroutine or a C<foreach> loop. It also can't be used to go into a construct that is optimized away. The C<goto-&NAME> form is quite different from the other forms of C<goto>. In fact, it isn't a goto in the normal sense at all, and doesn't have the stigma associated with other gotos. Instead, it exits the current subroutine (losing any changes set by local()) and immediately calls in its place the named subroutine using the current value of @_. This is used by C<AUTOLOAD> subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to C<@_> in the current subroutine are propagated to the other subroutine.) After the C<goto>, not even C<caller> will be able to tell that this routine was called first. NAME needn't be the name of a subroutine; it can be a scalar variable containing a code reference or a block that evaluates to a code reference. =item grep BLOCK LIST X<grep> =item grep EXPR,LIST =for Pod::Functions locate elements in a list test true against a given criterion This is similar in spirit to, but not the same as, grep(1) and its relatives. In particular, it is not limited to using regular expressions. Evaluates the BLOCK or EXPR for each element of LIST (locally setting C<$_> to each element) and returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true. @foo = grep(!/^#/, @bar); # weed out comments or equivalently, @foo = grep {!/^#/} @bar; # weed out comments Note that C<$_> is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Similarly, grep returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by grep (for example, in a C<foreach>, C<map> or another C<grep>) actually modifies the element in the original list. This is usually something to be avoided when writing clear code. If C<$_> is lexical in the scope where the C<grep> appears (because it has been declared with C<my $_>) then, in addition to being locally aliased to the list elements, C<$_> keeps being lexical inside the block; i.e., it can't be seen from the outside, avoiding any potential side-effects. See also L</map> for a list composed of the results of the BLOCK or EXPR. =item hex EXPR X<hex> X<hexadecimal> =item hex =for Pod::Functions convert a string to a hexadecimal number Interprets EXPR as a hex string and returns the corresponding value. (To convert strings that might start with either C<0>, C<0x>, or C<0b>, see L</oct>.) If EXPR is omitted, uses C<$_>. print hex '0xAf'; # prints '175' print hex 'aF'; # same Hex strings may only represent integers. Strings that would cause integer overflow trigger a warning. Leading whitespace is not stripped, unlike oct(). To present something as hex, look into L</printf>, L</sprintf>, and L</unpack>. =item import LIST X<import> =for Pod::Functions patch a module's namespace into your own There is no builtin C<import> function. It is just an ordinary method (subroutine) defined (or inherited) by modules that wish to export names to another module. The C<use> function calls the C<import> method for the package used. See also L</use>, L<perlmod>, and L<Exporter>. =item index STR,SUBSTR,POSITION X<index> X<indexOf> X<InStr> =item index STR,SUBSTR =for Pod::Functions find a substring within a string The index function searches for one string within another, but without the wildcard-like behavior of a full regular-expression pattern match. It returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. POSITION before the beginning of the string or after its end is treated as if it were the beginning or the end, respectively. POSITION and the return value are based at zero. If the substring is not found, C<index> returns -1. =item int EXPR X<int> X<integer> X<truncate> X<trunc> X<floor> =item int =for Pod::Functions get the integer portion of a number Returns the integer portion of EXPR. If EXPR is omitted, uses C<$_>. You should not use this function for rounding: one because it truncates towards C<0>, and two because machine representations of floating-point numbers can sometimes produce counterintuitive results. For example, C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's because it's really more like -268.99999999999994315658 instead. Usually, the C<sprintf>, C<printf>, or the C<POSIX::floor> and C<POSIX::ceil> functions will serve you better than will int(). =item ioctl FILEHANDLE,FUNCTION,SCALAR X<ioctl> =for Pod::Functions system-dependent device control system call Implements the ioctl(2) function. You'll probably first have to say require "sys/ioctl.ph"; # probably in $Config{archlib}/sys/ioctl.ph to get the correct function definitions. If F<sys/ioctl.ph> doesn't exist or doesn't have the correct definitions you'll have to roll your own, based on your C header files such as F<< <sys/ioctl.h> >>. (There is a Perl script called B<h2ph> that comes with the Perl kit that may help you in this, but it's nontrivial.) SCALAR will be read and/or written depending on the FUNCTION; a C pointer to the string value of SCALAR will be passed as the third argument of the actual C<ioctl> call. (If SCALAR has no string value but does have a numeric value, that value will be passed rather than a pointer to the string value. To guarantee this to be true, add a C<0> to the scalar before using it.) The C<pack> and C<unpack> functions may be needed to manipulate the values of structures used by C<ioctl>. The return value of C<ioctl> (and C<fcntl>) is as follows: if OS returns: then Perl returns: -1 undefined value 0 string "0 but true" anything else that number Thus Perl returns true on success and false on failure, yet you can still easily determine the actual value returned by the operating system: $retval = ioctl(...) || -1; printf "System returned %d\n", $retval; The special string C<"0 but true"> is exempt from B<-w> complaints about improper numeric conversions. Portability issues: L<perlport/ioctl>. =item join EXPR,LIST X<join> =for Pod::Functions join a list into a string using a separator Joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns that new string. Example: $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); Beware that unlike C<split>, C<join> doesn't take a pattern as its first argument. Compare L</split>. =item keys HASH X<keys> X<key> =item keys ARRAY =item keys EXPR =for Pod::Functions retrieve list of indices from a hash Called in list context, returns a list consisting of all the keys of the named hash, or in Perl 5.12 or later only, the indices of an array. Perl releases prior to 5.12 will produce a syntax error if you try to use an array argument. In scalar context, returns the number of keys or indices. The keys of a hash are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be the same order as either the C<values> or C<each> function produces (given that the hash has not been modified). Since Perl 5.8.1 the ordering can be different even between different runs of Perl for security reasons (see L<perlsec/"Algorithmic Complexity Attacks">). As a side effect, calling keys() resets the internal interator of the HASH or ARRAY (see L</each>). In particular, calling keys() in void context resets the iterator with no other overhead. Here is yet another way to print your environment: @keys = keys %ENV; @values = values %ENV; while (@keys) { print pop(@keys), '=', pop(@values), "\n"; } or how about sorted by key: foreach $key (sort(keys %ENV)) { print $key, '=', $ENV{$key}, "\n"; } The returned values are copies of the original keys in the hash, so modifying them will not affect the original hash. Compare L</values>. To sort a hash by value, you'll need to use a C<sort> function. Here's a descending numeric sort of a hash by its values: foreach $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { printf "%4d %s\n", $hash{$key}, $key; } Used as an lvalue, C<keys> allows you to increase the number of hash buckets allocated for the given hash. This can gain you a measure of efficiency if you know the hash is going to get big. (This is similar to pre-extending an array by assigning a larger number to $#array.) If you say keys %hash = 200; then C<%hash> will have at least 200 buckets allocated for it--256 of them, in fact, since it rounds up to the next power of two. These buckets will be retained even if you do C<%hash = ()>, use C<undef %hash> if you want to free the storage while C<%hash> is still in scope. You can't shrink the number of buckets allocated for the hash using C<keys> in this way (but you needn't worry about doing this by accident, as trying has no effect). C<keys @array> in an lvalue context is a syntax error. Starting with Perl 5.14, C<keys> can take a scalar EXPR, which must contain a reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of C<keys> is considered highly experimental. The exact behaviour may change in a future version of Perl. for (keys $hashref) { ... } for (keys $obj->get_arrayref) { ... } To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.012; # so keys/values/each work on arrays use 5.014; # so keys/values/each work on scalars (experimental) See also C<each>, C<values>, and C<sort>. =item kill SIGNAL, LIST =item kill SIGNAL X<kill> X<signal> =for Pod::Functions send a signal to a process or process group Sends a signal to a list of processes. Returns the number of processes successfully signaled (which is not necessarily the same as the number actually killed). $cnt = kill 1, $child1, $child2; kill 9, @goners; If SIGNAL is zero, no signal is sent to the process, but C<kill> checks whether it's I<possible> to send a signal to it (that means, to be brief, that the process is owned by the same user, or we are the super-user). This is useful to check that a child process is still alive (even if only as a zombie) and hasn't changed its UID. See L<perlport> for notes on the portability of this construct. Unlike in the shell, if SIGNAL is negative, it kills process groups instead of processes. That means you usually want to use positive not negative signals. You may also use a signal name in quotes. The behavior of kill when a I<PROCESS> number is zero or negative depends on the operating system. For example, on POSIX-conforming systems, zero will signal the current process group and -1 will signal all processes. See L<perlipc/"Signals"> for more details. On some platforms such as Windows where the fork() system call is not available. Perl can be built to emulate fork() at the interpreter level. This emulation has limitations related to kill that have to be considered, for code running on Windows and in code intended to be portable. See L<perlfork> for more details. If there is no I<LIST> of processes, no signal is sent, and the return value is 0. This form is sometimes used, however, because it causes tainting checks to be run. But see L<perlsec/Laundering and Detecting Tainted Data>. Portability issues: L<perlport/kill>. =item last LABEL X<last> X<break> =item last =for Pod::Functions exit a block prematurely The C<last> command is like the C<break> statement in C (as used in loops); it immediately exits the loop in question. If the LABEL is omitted, the command refers to the innermost enclosing loop. The C<continue> block, if any, is not executed: LINE: while (<STDIN>) { last LINE if /^$/; # exit when done with header #... } C<last> cannot be used to exit a block that returns a value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop that executes once. Thus C<last> can be used to effect an early exit out of such a block. See also L</continue> for an illustration of how C<last>, C<next>, and C<redo> work. =item lc EXPR X<lc> X<lowercase> =item lc =for Pod::Functions return lower-case version of a string Returns a lowercased version of EXPR. This is the internal function implementing the C<\L> escape in double-quoted strings. If EXPR is omitted, uses C<$_>. What gets returned depends on several factors: =over =item If C<use bytes> is in effect: =over =item On EBCDIC platforms The results are what the C language system call C<tolower()> returns. =item On ASCII platforms The results follow ASCII semantics. Only characters C<A-Z> change, to C<a-z> respectively. =back =item Otherwise, if C<use locale> (but not C<use locale ':not_characters'>) is in effect: Respects current LC_CTYPE locale for code points < 256; and uses Unicode semantics for the remaining code points (this last can only happen if the UTF8 flag is also set). See L<perllocale>. A deficiency in this is that case changes that cross the 255/256 boundary are not well-defined. For example, the lower case of LATIN CAPITAL LETTER SHARP S (U+1E9E) in Unicode semantics is U+00DF (on ASCII platforms). But under C<use locale>, the lower case of U+1E9E is itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the current locale, and Perl has no way of knowing if that character even exists in the locale, much less what code point it is. Perl returns the input character unchanged, for all instances (and there aren't many) where the 255/256 boundary would otherwise be crossed. =item Otherwise, If EXPR has the UTF8 flag set: Unicode semantics are used for the case change. =item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'>) is in effect: Unicode semantics are used for the case change. =item Otherwise: =over =item On EBCDIC platforms The results are what the C language system call C<tolower()> returns. =item On ASCII platforms ASCII semantics are used for the case change. The lowercase of any character outside the ASCII range is the character itself. =back =back =item lcfirst EXPR X<lcfirst> X<lowercase> =item lcfirst =for Pod::Functions return a string with just the next letter in lower case Returns the value of EXPR with the first character lowercased. This is the internal function implementing the C<\l> escape in double-quoted strings. If EXPR is omitted, uses C<$_>. This function behaves the same way under various pragmata, such as in a locale, as L</lc> does. =item length EXPR X<length> X<size> =item length =for Pod::Functions return the number of bytes in a string Returns the length in I<characters> of the value of EXPR. If EXPR is omitted, returns the length of C<$_>. If EXPR is undefined, returns C<undef>. This function cannot be used on an entire array or hash to find out how many elements these have. For that, use C<scalar @array> and C<scalar keys %hash>, respectively. Like all Perl character operations, length() normally deals in logical characters, not physical bytes. For how many bytes a string encoded as UTF-8 would take up, use C<length(Encode::encode_utf8(EXPR))> (you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>. =item __LINE__ X<__LINE__> =for Pod::Functions the current source line number A special token that compiles to the current line number. =item link OLDFILE,NEWFILE X<link> =for Pod::Functions create a hard link in the filesystem Creates a new filename linked to the old filename. Returns true for success, false otherwise. Portability issues: L<perlport/link>. =item listen SOCKET,QUEUESIZE X<listen> =for Pod::Functions register your socket as a server Does the same thing that the listen(2) system call does. Returns true if it succeeded, false otherwise. See the example in L<perlipc/"Sockets: Client/Server Communication">. =item local EXPR X<local> =for Pod::Functions create a temporary value for a global variable (dynamic scoping) You really probably want to be using C<my> instead, because C<local> isn't what most people think of as "local". See L<perlsub/"Private Variables via my()"> for details. A local modifies the listed variables to be local to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses. See L<perlsub/"Temporary Values via local()"> for details, including issues with tied arrays and hashes. The C<delete local EXPR> construct can also be used to localize the deletion of array/hash elements to the current block. See L<perlsub/"Localized deletion of elements of composite types">. =item localtime EXPR X<localtime> X<ctime> =item localtime =for Pod::Functions convert UNIX time into record or string using local time Converts a time as returned by the time function to a 9-element list with the time analyzed for the local time zone. Typically used as follows: # 0 1 2 3 4 5 6 7 8 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); All list elements are numeric and come straight out of the C `struct tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours of the specified time. C<$mday> is the day of the month and C<$mon> the month in the range C<0..11>, with 0 indicating January and 11 indicating December. This makes it easy to get a month name from a list: my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); print "$abbr[$mon] $mday"; # $mon=9, $mday=18 gives "Oct 18" C<$year> contains the number of years since 1900. To get a 4-digit year write: $year += 1900; To get the last two digits of the year (e.g., "01" in 2001) do: $year = sprintf("%02d", $year % 100); C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating Wednesday. C<$yday> is the day of the year, in the range C<0..364> (or C<0..365> in leap years.) C<$isdst> is true if the specified time occurs during Daylight Saving Time, false otherwise. If EXPR is omitted, C<localtime()> uses the current time (as returned by time(3)). In scalar context, C<localtime()> returns the ctime(3) value: $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" The format of this scalar value is B<not> locale-dependent but built into Perl. For GMT instead of local time use the L</gmtime> builtin. See also the C<Time::Local> module (for converting seconds, minutes, hours, and such back to the integer value returned by time()), and the L<POSIX> module's strftime(3) and mktime(3) functions. To get somewhat similar but locale-dependent date strings, set up your locale environment variables appropriately (please see L<perllocale>) and try for example: use POSIX qw(strftime); $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; # or for GMT formatted appropriately for your locale: $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; Note that the C<%a> and C<%b>, the short forms of the day of the week and the month of the year, may not necessarily be three characters wide. The L<Time::gmtime> and L<Time::localtime> modules provide a convenient, by-name access mechanism to the gmtime() and localtime() functions, respectively. For a comprehensive date and time representation look at the L<DateTime> module on CPAN. Portability issues: L<perlport/localtime>. =item lock THING X<lock> =for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method This function places an advisory lock on a shared variable or referenced object contained in I<THING> until the lock goes out of scope. The value returned is the scalar itself, if the argument is a scalar, or a reference, if the argument is a hash, array or subroutine. lock() is a "weak keyword" : this means that if you've defined a function by this name (before any calls to it), that function will be called instead. If you are not under C<use threads::shared> this does nothing. See L<threads::shared>. =item log EXPR X<log> X<logarithm> X<e> X<ln> X<base> =item log =for Pod::Functions retrieve the natural logarithm for a number Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted, returns the log of C<$_>. To get the log of another base, use basic algebra: The base-N log of a number is equal to the natural log of that number divided by the natural log of N. For example: sub log10 { my $n = shift; return log($n)/log(10); } See also L</exp> for the inverse operation. =item lstat FILEHANDLE X<lstat> =item lstat EXPR =item lstat DIRHANDLE =item lstat =for Pod::Functions stat a symbolic link Does the same thing as the C<stat> function (including setting the special C<_> filehandle) but stats a symbolic link instead of the file the symbolic link points to. If symbolic links are unimplemented on your system, a normal C<stat> is done. For much more detailed information, please see the documentation for C<stat>. If EXPR is omitted, stats C<$_>. Portability issues: L<perlport/lstat>. =item m// =for Pod::Functions match a string with a regular expression pattern The match operator. See L<perlop/"Regexp Quote-Like Operators">. =item map BLOCK LIST X<map> =item map EXPR,LIST =for Pod::Functions apply a change to a list to get back a new list with the changes Evaluates the BLOCK or EXPR for each element of LIST (locally setting C<$_> to each element) and returns the list value composed of the results of each such evaluation. In scalar context, returns the total number of elements so generated. Evaluates BLOCK or EXPR in list context, so each element of LIST may produce zero, one, or more elements in the returned value. @chars = map(chr, @numbers); translates a list of numbers to the corresponding characters. my @squares = map { $_ * $_ } @numbers; translates a list of numbers to their squared values. my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers; shows that number of returned elements can differ from the number of input elements. To omit an element, return an empty list (). This could also be achieved by writing my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers; which makes the intention more clear. Map always returns a list, which can be assigned to a hash such that the elements become key/value pairs. See L<perldata> for more details. %hash = map { get_a_key_for($_) => $_ } @array; is just a funny way to write %hash = (); foreach (@array) { $hash{get_a_key_for($_)} = $_; } Note that C<$_> is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Using a regular C<foreach> loop for this purpose would be clearer in most cases. See also L</grep> for an array composed of those items of the original list for which the BLOCK or EXPR evaluates to true. If C<$_> is lexical in the scope where the C<map> appears (because it has been declared with C<my $_>), then, in addition to being locally aliased to the list elements, C<$_> keeps being lexical inside the block; that is, it can't be seen from the outside, avoiding any potential side-effects. C<{> starts both hash references and blocks, so C<map { ...> could be either the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look ahead for the closing C<}> it has to take a guess at which it's dealing with based on what it finds just after the C<{>. Usually it gets it right, but if it doesn't it won't realize something is wrong until it gets to the C<}> and encounters the missing (or unexpected) comma. The syntax error will be reported close to the C<}>, but you'll need to change something near the C<{> such as using a unary C<+> to give Perl some help: %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right %hash = map { ("\L$_" => 1) } @array # this also works %hash = map { lc($_) => 1 } @array # as does this. %hash = map +( lc($_) => 1 ), @array # this is EXPR and works! %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array) or to force an anon hash constructor use C<+{>: @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs comma at end to get a list of anonymous hashes each with only one entry apiece. =item mkdir FILENAME,MASK X<mkdir> X<md> X<directory, create> =item mkdir FILENAME =item mkdir =for Pod::Functions create a directory Creates the directory specified by FILENAME, with permissions specified by MASK (as modified by C<umask>). If it succeeds it returns true; otherwise it returns false and sets C<$!> (errno). MASK defaults to 0777 if omitted, and FILENAME defaults to C<$_> if omitted. In general, it is better to create directories with a permissive MASK and let the user modify that with their C<umask> than it is to supply a restrictive MASK and give the user no way to be more permissive. The exceptions to this rule are when the file or directory should be kept private (mail files, for instance). The perlfunc(1) entry on C<umask> discusses the choice of MASK in more detail. Note that according to the POSIX 1003.1-1996 the FILENAME may have any number of trailing slashes. Some operating and filesystems do not get this right, so Perl automatically removes all trailing slashes to keep everyone happy. To recursively create a directory structure, look at the C<mkpath> function of the L<File::Path> module. =item msgctl ID,CMD,ARG X<msgctl> =for Pod::Functions SysV IPC message control operations Calls the System V IPC function msgctl(2). You'll probably have to say use IPC::SysV; first to get the correct constant definitions. If CMD is C<IPC_STAT>, then ARG must be a variable that will hold the returned C<msqid_ds> structure. Returns like C<ioctl>: the undefined value for error, C<"0 but true"> for zero, or the actual return value otherwise. See also L<perlipc/"SysV IPC"> and the documentation for C<IPC::SysV> and C<IPC::Semaphore>. Portability issues: L<perlport/msgctl>. =item msgget KEY,FLAGS X<msgget> =for Pod::Functions get SysV IPC message queue Calls the System V IPC function msgget(2). Returns the message queue id, or C<undef> on error. See also L<perlipc/"SysV IPC"> and the documentation for C<IPC::SysV> and C<IPC::Msg>. Portability issues: L<perlport/msgget>. =item msgrcv ID,VAR,SIZE,TYPE,FLAGS X<msgrcv> =for Pod::Functions receive a SysV IPC message from a message queue Calls the System V IPC function msgrcv to receive a message from message queue ID into variable VAR with a maximum message size of SIZE. Note that when a message is received, the message type as a native long integer will be the first thing in VAR, followed by the actual message. This packing may be opened with C<unpack("l! a*")>. Taints the variable. Returns true if successful, false on error. See also L<perlipc/"SysV IPC"> and the documentation for C<IPC::SysV> and C<IPC::SysV::Msg>. Portability issues: L<perlport/msgrcv>. =item msgsnd ID,MSG,FLAGS X<msgsnd> =for Pod::Functions send a SysV IPC message to a message queue Calls the System V IPC function msgsnd to send the message MSG to the message queue ID. MSG must begin with the native long integer message type, be followed by the length of the actual message, and then finally the message itself. This kind of packing can be achieved with C<pack("l! a*", $type, $message)>. Returns true if successful, false on error. See also the C<IPC::SysV> and C<IPC::SysV::Msg> documentation. Portability issues: L<perlport/msgsnd>. =item my EXPR X<my> =item my TYPE EXPR =item my EXPR : ATTRS =item my TYPE EXPR : ATTRS =for Pod::Functions declare and assign a local variable (lexical scoping) A C<my> declares the listed variables to be local (lexically) to the enclosing block, file, or C<eval>. If more than one value is listed, the list must be placed in parentheses. The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE is currently bound to the use of the C<fields> pragma, and attributes are handled using the C<attributes> pragma, or starting from Perl 5.8.0 also via the C<Attribute::Handlers> module. See L<perlsub/"Private Variables via my()"> for details, and L<fields>, L<attributes>, and L<Attribute::Handlers>. =item next LABEL X<next> X<continue> =item next =for Pod::Functions iterate a block prematurely The C<next> command is like the C<continue> statement in C; it starts the next iteration of the loop: LINE: while (<STDIN>) { next LINE if /^#/; # discard comments #... } Note that if there were a C<continue> block on the above, it would get executed even on discarded lines. If LABEL is omitted, the command refers to the innermost enclosing loop. C<next> cannot be used to exit a block which returns a value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop that executes once. Thus C<next> will exit such a block early. See also L</continue> for an illustration of how C<last>, C<next>, and C<redo> work. =item no MODULE VERSION LIST X<no declarations> X<unimporting> =item no MODULE VERSION =item no MODULE LIST =item no MODULE =item no VERSION =for Pod::Functions unimport some module symbols or semantics at compile time See the C<use> function, of which C<no> is the opposite. =item oct EXPR X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin> =item oct =for Pod::Functions convert a string to an octal number Interprets EXPR as an octal string and returns the corresponding value. (If EXPR happens to start off with C<0x>, interprets it as a hex string. If EXPR starts off with C<0b>, it is interpreted as a binary string. Leading whitespace is ignored in all three cases.) The following will handle decimal, binary, octal, and hex in standard Perl notation: $val = oct($val) if $val =~ /^0/; If EXPR is omitted, uses C<$_>. To go the other way (produce a number in octal), use sprintf() or printf(): $dec_perms = (stat("filename"))[2] & 07777; $oct_perm_str = sprintf "%o", $perms; The oct() function is commonly used when a string such as C<644> needs to be converted into a file mode, for example. Although Perl automatically converts strings into numbers as needed, this automatic conversion assumes base 10. Leading white space is ignored without warning, as too are any trailing non-digits, such as a decimal point (C<oct> only handles non-negative integers, not negative integers or floating point). =item open FILEHANDLE,EXPR X<open> X<pipe> X<file, open> X<fopen> =item open FILEHANDLE,MODE,EXPR =item open FILEHANDLE,MODE,EXPR,LIST =item open FILEHANDLE,MODE,REFERENCE =item open FILEHANDLE =for Pod::Functions open a file, pipe, or descriptor Opens the file whose filename is given by EXPR, and associates it with FILEHANDLE. Simple examples to open a file for reading: open(my $fh, "<", "input.txt") or die "cannot open < input.txt: $!"; and for writing: open(my $fh, ">", "output.txt") or die "cannot open > output.txt: $!"; (The following is a comprehensive reference to open(): for a gentler introduction you may consider L<perlopentut>.) If FILEHANDLE is an undefined scalar variable (or array or hash element), a new filehandle is autovivified, meaning that the variable is assigned a reference to a newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an expression, its value is the real filehandle. (This is considered a symbolic reference, so C<use strict "refs"> should I<not> be in effect.) If EXPR is omitted, the global (package) scalar variable of the same name as the FILEHANDLE contains the filename. (Note that lexical variables--those declared with C<my> or C<state>--will not work for this purpose; so if you're using C<my> or C<state>, specify EXPR in your call to open.) If three (or more) arguments are specified, the open mode (including optional encoding) in the second argument are distinct from the filename in the third. If MODE is C<< < >> or nothing, the file is opened for input. If MODE is C<< > >>, the file is opened for output, with existing files first being truncated ("clobbered") and nonexisting files newly created. If MODE is C<<< >> >>>, the file is opened for appending, again being created if necessary. You can put a C<+> in front of the C<< > >> or C<< < >> to indicate that you want both read and write access to the file; thus C<< +< >> is almost always preferred for read/write updates--the C<< +> >> mode would clobber the file first. You can't usually use either read-write mode for updating textfiles, since they have variable-length records. See the B<-i> switch in L<perlrun> for a better approach. The file is created with permissions of C<0666> modified by the process's C<umask> value. These various prefixes correspond to the fopen(3) modes of C<r>, C<r+>, C<w>, C<w+>, C<a>, and C<a+>. In the one- and two-argument forms of the call, the mode and filename should be concatenated (in that order), preferably separated by white space. You can--but shouldn't--omit the mode in these forms when that mode is C<< < >>. It is always safe to use the two-argument form of C<open> if the filename argument is a known literal. For three or more arguments if MODE is C<|->, the filename is interpreted as a command to which output is to be piped, and if MODE is C<-|>, the filename is interpreted as a command that pipes output to us. In the two-argument (and one-argument) form, one should replace dash (C<->) with the command. See L<perlipc/"Using open() for IPC"> for more examples of this. (You are not allowed to C<open> to a command that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and L<perlipc/"Bidirectional Communication with Another Process"> for alternatives.) In the form of pipe opens taking three or more arguments, if LIST is specified (extra arguments after the command name) then LIST becomes arguments to the command invoked if the platform supports it. The meaning of C<open> with more than three arguments for non-pipe modes is not yet defined, but experimental "layers" may give extra LIST arguments meaning. In the two-argument (and one-argument) form, opening C<< <- >> or C<-> opens STDIN and opening C<< >- >> opens STDOUT. You may (and usually should) use the three-argument form of open to specify I/O layers (sometimes referred to as "disciplines") to apply to the handle that affect how the input and output are processed (see L<open> and L<PerlIO> for more details). For example: open(my $fh, "<:encoding(UTF-8)", "filename") || die "can't open UTF-8 encoded filename: $!"; opens the UTF8-encoded file containing Unicode characters; see L<perluniintro>. Note that if layers are specified in the three-argument form, then default layers stored in ${^OPEN} (see L<perlvar>; usually set by the B<open> pragma or the switch B<-CioD>) are ignored. Those layers will also be ignored if you specifying a colon with no name following it. In that case the default layer for the operating system (:raw on Unix, :crlf on Windows) is used. Open returns nonzero on success, the undefined value otherwise. If the C<open> involved a pipe, the return value happens to be the pid of the subprocess. If you're running Perl on a system that distinguishes between text files and binary files, then you should check out L</binmode> for tips for dealing with this. The key distinction between systems that need C<binmode> and those that don't is their text file formats. Systems like Unix, Mac OS, and Plan 9, that end lines with a single character and encode that character in C as C<"\n"> do not need C<binmode>. The rest need it. When opening a file, it's seldom a good idea to continue if the request failed, so C<open> is frequently used with C<die>. Even if C<die> won't do what you want (say, in a CGI script, where you want to format a suitable error message (but there are modules that can help with that problem)) always check the return value from opening a file. As a special case the three-argument form with a read/write mode and the third argument being C<undef>: open(my $tmp, "+>", undef) or die ... opens a filehandle to an anonymous temporary file. Also using C<< +< >> works for symmetry, but you really should consider writing something to the temporary file first. You will need to seek() to do the reading. Since v5.8.0, Perl has built using PerlIO by default. Unless you've changed this (such as building Perl with C<Configure -Uuseperlio>), you can open filehandles directly to Perl scalars via: open($fh, ">", \$variable) || .. To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first: close STDOUT; open(STDOUT, ">", \$variable) or die "Can't open STDOUT: $!"; General examples: $ARTICLE = 100; open(ARTICLE) or die "Can't find article $ARTICLE: $!\n"; while (<ARTICLE>) {... open(LOG, ">>/usr/spool/news/twitlog"); # (log is reserved) # if the open fails, output is discarded open(my $dbase, "+<", "dbase.mine") # open for update or die "Can't open 'dbase.mine' for update: $!"; open(my $dbase, "+<dbase.mine") # ditto or die "Can't open 'dbase.mine' for update: $!"; open(ARTICLE, "-|", "caesar <$article") # decrypt article or die "Can't start caesar: $!"; open(ARTICLE, "caesar <$article |") # ditto or die "Can't start caesar: $!"; open(EXTRACT, "|sort >Tmp$$") # $$ is our process id or die "Can't start sort: $!"; # in-memory files open(MEMORY, ">", \$var) or die "Can't open memory file: $!"; print MEMORY "foo!\n"; # output will appear in $var # process argument list of files along with any includes foreach $file (@ARGV) { process($file, "fh00"); } sub process { my($filename, $input) = @_; $input++; # this is a string increment unless (open($input, "<", $filename)) { print STDERR "Can't open $filename: $!\n"; return; } local $_; while (<$input>) { # note use of indirection if (/^#include "(.*)"/) { process($1, $input); next; } #... # whatever } } See L<perliol> for detailed info on PerlIO. You may also, in the Bourne shell tradition, specify an EXPR beginning with C<< >& >>, in which case the rest of the string is interpreted as the name of a filehandle (or file descriptor, if numeric) to be duped (as C<dup(2)>) and opened. You may use C<&> after C<< > >>, C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>. The mode you specify should match the mode of the original filehandle. (Duping a filehandle does not take into account any existing contents of IO buffers.) If you use the three-argument form, then you can pass either a number, the name of a filehandle, or the normal "reference to a glob". Here is a script that saves, redirects, and restores C<STDOUT> and C<STDERR> using various methods: #!/usr/bin/perl open(my $oldout, ">&STDOUT") or die "Can't dup STDOUT: $!"; open(OLDERR, ">&", \*STDERR) or die "Can't dup STDERR: $!"; open(STDOUT, '>', "foo.out") or die "Can't redirect STDOUT: $!"; open(STDERR, ">&STDOUT") or die "Can't dup STDOUT: $!"; select STDERR; $| = 1; # make unbuffered select STDOUT; $| = 1; # make unbuffered print STDOUT "stdout 1\n"; # this works for print STDERR "stderr 1\n"; # subprocesses too open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!"; open(STDERR, ">&OLDERR") or die "Can't dup OLDERR: $!"; print STDOUT "stdout 2\n"; print STDERR "stderr 2\n"; If you specify C<< '<&=X' >>, where C<X> is a file descriptor number or a filehandle, then Perl will do an equivalent of C's C<fdopen> of that file descriptor (and not call C<dup(2)>); this is more parsimonious of file descriptors. For example: # open for input, reusing the fileno of $fd open(FILEHANDLE, "<&=$fd") or open(FILEHANDLE, "<&=", $fd) or # open for append, using the fileno of OLDFH open(FH, ">>&=", OLDFH) or open(FH, ">>&=OLDFH") Being parsimonious on filehandles is also useful (besides being parsimonious) for example when something is dependent on file descriptors, like for example locking using flock(). If you do just C<< open(A, ">>&B") >>, the filehandle A will not have the same file descriptor as B, and therefore flock(A) will not flock(B) nor vice versa. But with C<< open(A, ">>&=B") >>, the filehandles will share the same underlying system file descriptor. Note that under Perls older than 5.8.0, Perl uses the standard C library's' fdopen() to implement the C<=> functionality. On many Unix systems, fdopen() fails when file descriptors exceed a certain value, typically 255. For Perls 5.8.0 and later, PerlIO is (most often) the default. You can see whether your Perl was built with PerlIO by running C<perl -V> and looking for the C<useperlio=> line. If C<useperlio> is C<define>, you have PerlIO; otherwise you don't. If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> with the one- or two-argument forms of C<open>), an implicit C<fork> is done, so C<open> returns twice: in the parent process it returns the pid of the child process, and in the child process it returns (a defined) C<0>. Use C<defined($pid)> or C<//> to determine whether the open was successful. For example, use either $child_pid = open(FROM_KID, "-|") // die "can't fork: $!"; or $child_pid = open(TO_KID, "|-") // die "can't fork: $!"; followed by if ($child_pid) { # am the parent: # either write TO_KID or else read FROM_KID ... wait $child_pid; } else { # am the child; use STDIN/STDOUT normally ... exit; } The filehandle behaves normally for the parent, but I/O to that filehandle is piped from/to the STDOUT/STDIN of the child process. In the child process, the filehandle isn't opened--I/O happens from/to the new STDOUT/STDIN. Typically this is used like the normal piped open when you want to exercise more control over just how the pipe command gets executed, such as when running setuid and you don't want to have to scan shell commands for metacharacters. The following blocks are more or less equivalent: open(FOO, "|tr '[a-z]' '[A-Z]'"); open(FOO, "|-", "tr '[a-z]' '[A-Z]'"); open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]'; open(FOO, "|-", "tr", '[a-z]', '[A-Z]'); open(FOO, "cat -n '$file'|"); open(FOO, "-|", "cat -n '$file'"); open(FOO, "-|") || exec "cat", "-n", $file; open(FOO, "-|", "cat", "-n", $file); The last two examples in each block show the pipe as "list form", which is not yet supported on all platforms. A good rule of thumb is that if your platform has a real C<fork()> (in other words, if your platform is Unix, including Linux and MacOS X), you can use the list form. You would want to use the list form of the pipe so you can pass literal arguments to the command without risk of the shell interpreting any shell metacharacters in them. However, this also bars you from opening pipes to commands that intentionally contain shell metacharacters, such as: open(FOO, "|cat -n | expand -4 | lpr") // die "Can't open pipeline to lpr: $!"; See L<perlipc/"Safe Pipe Opens"> for more examples of this. Beginning with v5.6.0, Perl will attempt to flush all files opened for output before any operation that may do a fork, but this may not be supported on some platforms (see L<perlport>). To be safe, you may need to set C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of C<IO::Handle> on any open handles. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor as determined by the value of C<$^F>. See L<perlvar/$^F>. Closing any piped filehandle causes the parent process to wait for the child to finish, then returns the status value in C<$?> and C<${^CHILD_ERROR_NATIVE}>. The filename passed to the one- and two-argument forms of open() will have leading and trailing whitespace deleted and normal redirection characters honored. This property, known as "magic open", can often be used to good effect. A user could specify a filename of F<"rsh cat file |">, or you could change certain filenames as needed: $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/; open(FH, $filename) or die "Can't open $filename: $!"; Use the three-argument form to open a file with arbitrary weird characters in it, open(FOO, "<", $file) || die "can't open < $file: $!"; otherwise it's necessary to protect any leading and trailing whitespace: $file =~ s#^(\s)#./$1#; open(FOO, "< $file\0") || die "open failed: $!"; (this may not work on some bizarre filesystems). One should conscientiously choose between the I<magic> and I<three-argument> form of open(): open(IN, $ARGV[0]) || die "can't open $ARGV[0]: $!"; will allow the user to specify an argument of the form C<"rsh cat file |">, but will not work on a filename that happens to have a trailing space, while open(IN, "<", $ARGV[0]) || die "can't open < $ARGV[0]: $!"; will have exactly the opposite restrictions. If you want a "real" C C<open> (see L<open(2)> on your system), then you should use the C<sysopen> function, which involves no such magic (but may use subtly different filemodes than Perl open(), which is mapped to C fopen()). This is another way to protect your filenames from interpretation. For example: use IO::Handle; sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL) or die "sysopen $path: $!"; $oldfh = select(HANDLE); $| = 1; select($oldfh); print HANDLE "stuff $$\n"; seek(HANDLE, 0, 0); print "File contains: ", <HANDLE>; Using the constructor from the C<IO::Handle> package (or one of its subclasses, such as C<IO::File> or C<IO::Socket>), you can generate anonymous filehandles that have the scope of the variables used to hold them, then automatically (but silently) close once their reference counts become zero, typically at scope exit: use IO::File; #... sub read_myfile_munged { my $ALL = shift; # or just leave it undef to autoviv my $handle = IO::File->new; open($handle, "<", "myfile") or die "myfile: $!"; $first = <$handle> or return (); # Automatically closed here. mung($first) or die "mung failed"; # Or here. return (first, <$handle>) if $ALL; # Or here. return $first; # Or here. } B<WARNING:> The previous example has a bug because the automatic close that happens when the refcount on C<handle> does not properly detect and report failures. I<Always> close the handle yourself and inspect the return value. close($handle) || warn "close failed: $!"; See L</seek> for some details about mixing reading and writing. Portability issues: L<perlport/open>. =item opendir DIRHANDLE,EXPR X<opendir> =for Pod::Functions open a directory Opens a directory named EXPR for processing by C<readdir>, C<telldir>, C<seekdir>, C<rewinddir>, and C<closedir>. Returns true if successful. DIRHANDLE may be an expression whose value can be used as an indirect dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined scalar variable (or array or hash element), the variable is assigned a reference to a new anonymous dirhandle; that is, it's autovivified. DIRHANDLEs have their own namespace separate from FILEHANDLEs. See the example at C<readdir>. =item ord EXPR X<ord> X<encoding> =item ord =for Pod::Functions find a character's numeric representation Returns the numeric value of the first character of EXPR. If EXPR is an empty string, returns 0. If EXPR is omitted, uses C<$_>. (Note I<character>, not byte.) For the reverse, see L</chr>. See L<perlunicode> for more about Unicode. =item our EXPR X<our> X<global> =item our TYPE EXPR =item our EXPR : ATTRS =item our TYPE EXPR : ATTRS =for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping) C<our> associates a simple name with a package variable in the current package for use within the current scope. When C<use strict 'vars'> is in effect, C<our> lets you use declared global variables without qualifying them with package names, within the lexical scope of the C<our> declaration. In this way C<our> differs from C<use vars>, which is package-scoped. Unlike C<my> or C<state>, which allocates storage for a variable and associates a simple name with that storage for use within the current scope, C<our> associates a simple name with a package (read: global) variable in the current package, for use within the current lexical scope. In other words, C<our> has the same scoping rules as C<my> or C<state>, but does not necessarily create a variable. If more than one value is listed, the list must be placed in parentheses. our $foo; our($bar, $baz); An C<our> declaration declares a global variable that will be visible across its entire lexical scope, even across package boundaries. The package in which the variable is entered is determined at the point of the declaration, not at the point 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 20, as it refers to $Foo::bar Multiple C<our> declarations with the same name in the same lexical scope are allowed if they are in different packages. If they happen to be in the same package, Perl will emit warnings if you have asked for them, just like multiple C<my> declarations. Unlike a second C<my> declaration, which will bind the name to a fresh variable, a second C<our> declaration in the same package, in the same scope, is merely redundant. 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 warning but has no other effect print $bar; # still prints 30 An C<our> declaration may also have a list of attributes associated with it. The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE is currently bound to the use of the C<fields> pragma, and attributes are handled using the C<attributes> pragma, or, starting from Perl 5.8.0, also via the C<Attribute::Handlers> module. See L<perlsub/"Private Variables via my()"> for details, and L<fields>, L<attributes>, and L<Attribute::Handlers>. =item pack TEMPLATE,LIST X<pack> =for Pod::Functions convert a list into a binary representation Takes a LIST of values and converts it into a string using the rules given by the TEMPLATE. The resulting string is the concatenation of the converted values. Typically, each converted value looks like its machine-level representation. For example, on 32-bit machines an integer may be represented by a sequence of 4 bytes, which will in Perl be presented as a string that's 4 characters long. See L<perlpacktut> for an introduction to this function. The TEMPLATE is a sequence of characters that give the order and type of values, as follows: a A string with arbitrary binary data, will be null padded. A A text (ASCII) string, will be space padded. Z A null-terminated (ASCIZ) string, will be null padded. b A bit string (ascending bit order inside each byte, like vec()). B A bit string (descending bit order inside each byte). h A hex string (low nybble first). H A hex string (high nybble first). c A signed char (8-bit) value. C An unsigned char (octet) value. W An unsigned char value (can be greater than 255). s A signed short (16-bit) value. S An unsigned short value. l A signed long (32-bit) value. L An unsigned long value. q A signed quad (64-bit) value. Q An unsigned quad value. (Quads are available only if your system supports 64-bit integer values _and_ if Perl has been compiled to support those. Raises an exception otherwise.) i A signed integer value. I A unsigned integer value. (This 'integer' is _at_least_ 32 bits wide. Its exact size depends on what a local C compiler calls 'int'.) n An unsigned short (16-bit) in "network" (big-endian) order. N An unsigned long (32-bit) in "network" (big-endian) order. v An unsigned short (16-bit) in "VAX" (little-endian) order. V An unsigned long (32-bit) in "VAX" (little-endian) order. j A Perl internal signed integer value (IV). J A Perl internal unsigned integer value (UV). f A single-precision float in native format. d A double-precision float in native format. F A Perl internal floating-point value (NV) in native format D A float of long-double precision in native format. (Long doubles are available only if your system supports long double values _and_ if Perl has been compiled to support those. Raises an exception otherwise.) p A pointer to a null-terminated string. P A pointer to a structure (fixed-length string). u A uuencoded string. U A Unicode character number. Encodes to a character in char- acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in byte mode. w A BER compressed integer (not an ASN.1 BER, see perlpacktut for details). Its bytes represent an unsigned integer in base 128, most significant digit first, with as few digits as possible. Bit eight (the high bit) is set on each byte except the last. x A null byte (a.k.a ASCII NUL, "\000", chr(0)) X Back up a byte. @ Null-fill or truncate to absolute position, counted from the start of the innermost ()-group. . Null-fill or truncate to absolute position specified by the value. ( Start of a ()-group. One or more modifiers below may optionally follow certain letters in the TEMPLATE (the second column lists letters for which the modifier is valid): ! sSlLiI Forces native (short, long, int) sizes instead of fixed (16-/32-bit) sizes. xX Make x and X act as alignment commands. nNvV Treat integers as signed instead of unsigned. @. Specify position as byte offset in the internal representation of the packed string. Efficient but dangerous. > sSiIlLqQ Force big-endian byte-order on the type. jJfFdDpP (The "big end" touches the construct.) < sSiIlLqQ Force little-endian byte-order on the type. jJfFdDpP (The "little end" touches the construct.) The C<< > >> and C<< < >> modifiers can also be used on C<()> groups to force a particular byte-order on all components in that group, including all its subgroups. The following rules apply: =over =item * Each letter may optionally be followed by a number indicating the repeat count. A numeric repeat count may optionally be enclosed in brackets, as in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>, C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means something else, described below. Supplying a C<*> for the repeat count instead of a number means to use however many items are left, except for: =over =item * C<@>, C<x>, and C<X>, where it is equivalent to C<0>. =item * <.>, where it means relative to the start of the string. =item * C<u>, where it is equivalent to 1 (or 45, which here is equivalent). =back One can replace a numeric repeat count with a template letter enclosed in brackets to use the packed byte length of the bracketed template for the repeat count. For example, the template C<x[L]> skips as many bytes as in a packed long, and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when variable-expanded) unpacks. If the template in brackets contains alignment commands (such as C<x![d]>), its packed length is calculated as if the start of the template had the maximal possible alignment. When used with C<Z>, a C<*> as the repeat count is guaranteed to add a trailing null byte, so the resulting string is always one byte longer than the byte length of the item itself. When used with C<@>, the repeat count represents an offset from the start of the innermost C<()> group. When used with C<.>, the repeat count determines the starting position to calculate the value offset as follows: =over =item * If the repeat count is C<0>, it's relative to the current position. =item * If the repeat count is C<*>, the offset is relative to the start of the packed string. =item * And if it's an integer I<n>, the offset is relative to the start of the I<n>th innermost C<( )> group, or to the start of the string if I<n> is bigger then the group level. =back The repeat count for C<u> is interpreted as the maximal number of bytes to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat count should not be more than 65. =item * The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as needed. When unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything after the first null, and C<a> returns data with no stripping at all. If the value to pack is too long, the result is truncated. If it's too long and an explicit count is provided, C<Z> packs only C<$count-1> bytes, followed by a null byte. Thus C<Z> always packs a trailing null, except when the count is 0. =item * Likewise, the C<b> and C<B> formats pack a string that's that many bits long. Each such format generates 1 bit of the result. These are typically followed by a repeat count like C<B8> or C<B64>. Each result bit is based on the least-significant bit of the corresponding input character, i.e., on C<ord($char)%2>. In particular, characters C<"0"> and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">. Starting from the beginning of the input string, each 8-tuple of characters is converted to 1 character of output. With format C<b>, the first character of the 8-tuple determines the least-significant bit of a character; with format C<B>, it determines the most-significant bit of a character. If the length of the input string is not evenly divisible by 8, the remainder is packed as if the input string were padded by null characters at the end. Similarly during unpacking, "extra" bits are ignored. If the input string is longer than needed, remaining characters are ignored. A C<*> for the repeat count uses all characters of the input field. On unpacking, bits are converted to a string of C<0>s and C<1>s. =item * The C<h> and C<H> formats pack a string that many nybbles (4-bit groups, representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. For each such format, pack() generates 4 bits of result. With non-alphabetical characters, the result is based on the 4 least-significant bits of the input character, i.e., on C<ord($char)%16>. In particular, characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result is compatible with the usual hexadecimal digits, so that C<"a"> and C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex characters with this format. Starting from the beginning of the template to pack(), each pair of characters is converted to 1 character of output. With format C<h>, the first character of the pair determines the least-significant nybble of the output character; with format C<H>, it determines the most-significant nybble. If the length of the input string is not even, it behaves as if padded by a null character at the end. Similarly, "extra" nybbles are ignored during unpacking. If the input string is longer than needed, extra characters are ignored. A C<*> for the repeat count uses all characters of the input field. For unpack(), nybbles are converted to a string of hexadecimal digits. =item * The C<p> format packs a pointer to a null-terminated string. You are responsible for ensuring that the string is not a temporary value, as that could potentially get deallocated before you got around to using the packed result. The C<P> format packs a pointer to a structure of the size indicated by the length. A null pointer is created if the corresponding value for C<p> or C<P> is C<undef>; similarly with unpack(), where a null pointer unpacks into C<undef>. If your system has a strange pointer size--meaning a pointer is neither as big as an int nor as big as a long--it may not be possible to pack or unpack pointers in big- or little-endian byte order. Attempting to do so raises an exception. =item * The C</> template character allows packing and unpacking of a sequence of items where the packed structure contains a packed item count followed by the packed items themselves. This is useful when the structure you're unpacking has encoded the sizes or repeat counts for some of its fields within the structure itself as separate fields. For C<pack>, you write I<length-item>C</>I<sequence-item>, and the I<length-item> describes how the length value is packed. Formats likely to be of most use are integer-packing ones like C<n> for Java strings, C<w> for ASN.1 or SNMP, and C<N> for Sun XDR. For C<pack>, I<sequence-item> may have a repeat count, in which case the minimum of that and the number of available items is used as the argument for I<length-item>. If it has no repeat count or uses a '*', the number of available items is used. For C<unpack>, an internal stack of integer arguments unpacked so far is used. You write C</>I<sequence-item> and the repeat count is obtained by popping off the last element from the stack. The I<sequence-item> must not have a repeat count. If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">), the I<length-item> is the string length, not the number of strings. With an explicit repeat count for pack, the packed string is adjusted to that length. For example: This code: gives this result: unpack("W/a", "\004Gurusamy") ("Guru") unpack("a3/A A*", "007 Bond J ") (" Bond", "J") unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") pack("n/a* w/a","hello,","world") "\000\006hello,\005world" pack("a/W2", ord("a") .. ord("z")) "2ab" The I<length-item> is not returned explicitly from C<unpack>. Supplying a count to the I<length-item> format letter is only useful with C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may introduce C<"\000"> characters, which Perl does not regard as legal in numeric strings. =item * The integer types C<s>, C<S>, C<l>, and C<L> may be followed by a C<!> modifier to specify native shorts or longs. As shown in the example above, a bare C<l> means exactly 32 bits, although the native C<long> as seen by the local C compiler may be larger. This is mainly an issue on 64-bit platforms. You can see whether using C<!> makes any difference this way: printf "format s is %d, s! is %d\n", length pack("s"), length pack("s!"); printf "format l is %d, l! is %d\n", length pack("l"), length pack("l!"); C<i!> and C<I!> are also allowed, but only for completeness' sake: they are identical to C<i> and C<I>. The actual sizes (in bytes) of native shorts, ints, longs, and long longs on the platform where Perl was built are also available from the command line: $ perl -V:{short,int,long{,long}}size shortsize='2'; intsize='4'; longsize='4'; longlongsize='8'; or programmatically via the C<Config> module: use Config; print $Config{shortsize}, "\n"; print $Config{intsize}, "\n"; print $Config{longsize}, "\n"; print $Config{longlongsize}, "\n"; C<$Config{longlongsize}> is undefined on systems without long long support. =item * The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are inherently non-portable between processors and operating systems because they obey native byteorder and endianness. For example, a 4-byte integer 0x12345678 (305419896 decimal) would be ordered natively (arranged in and handled by the CPU registers) into bytes as 0x12 0x34 0x56 0x78 # big-endian 0x78 0x56 0x34 0x12 # little-endian Basically, Intel and VAX CPUs are little-endian, while everybody else, including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) them in little-endian mode, but SGI/Cray uses them in big-endian mode. The names I<big-endian> and I<little-endian> are comic references to the egg-eating habits of the little-endian Lilliputians and the big-endian Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>. This entered computer lingo via the paper "On Holy Wars and a Plea for Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980. Some systems may have even weirder byte orders such as 0x56 0x78 0x12 0x34 0x34 0x12 0x78 0x56 You can determine your system endianness with this incantation: printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678); The byteorder on the platform where Perl was built is also available via L<Config>: use Config; print "$Config{byteorder}\n"; or from the command line: $ perl -V:byteorder Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321"> and C<"87654321"> are big-endian. For portably packed integers, either use the formats C<n>, C<N>, C<v>, and C<V> or else use the C<< > >> and C<< < >> modifiers described immediately below. See also L<perlport>. =item * Starting with Perl 5.9.2, integer and floating-point formats, along with the C<p> and C<P> formats and C<()> groups, may all be followed by the C<< > >> or C<< < >> endianness modifiers to respectively enforce big- or little-endian byte-order. These modifiers are especially useful given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers, 64-bit integers, or floating-point values. Here are some concerns to keep in mind when using an endianness modifier: =over =item * Exchanging signed integers between different platforms works only when all platforms store them in the same format. Most platforms store signed integers in two's-complement notation, so usually this is not an issue. =item * The C<< > >> or C<< < >> modifiers can only be used on floating-point formats on big- or little-endian machines. Otherwise, attempting to use them raises an exception. =item * Forcing big- or little-endian byte-order on floating-point values for data exchange can work only if all platforms use the same binary representation such as IEEE floating-point. Even if all platforms are using IEEE, there may still be subtle differences. Being able to use C<< > >> or C<< < >> on floating-point values can be useful, but also dangerous if you don't know exactly what you're doing. It is not a general way to portably store floating-point values. =item * When using C<< > >> or C<< < >> on a C<()> group, this affects all types inside the group that accept byte-order modifiers, including all subgroups. It is silently ignored for all other types. You are not allowed to override the byte-order within a group that already has a byte-order modifier suffix. =back =item * Real numbers (floats and doubles) are in native machine format only. Due to the multiplicity of floating-point formats and the lack of a standard "network" representation for them, no facility for interchange has been made. This means that packed floating-point data written on one machine may not be readable on another, even if both use IEEE floating-point arithmetic (because the endianness of the memory representation is not part of the IEEE spec). See also L<perlport>. If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >> modifiers to force big- or little-endian byte-order on floating-point values. Because Perl uses doubles (or long doubles, if configured) internally for all numeric calculation, converting from double into float and thence to double again loses precision, so C<unpack("f", pack("f", $foo)>) will not in general equal $foo. =item * Pack and unpack can operate in two modes: character mode (C<C0> mode) where the packed string is processed per character, and UTF-8 mode (C<U0> mode) where the packed string is processed in its UTF-8-encoded Unicode form on a byte-by-byte basis. Character mode is the default unless the format string starts with C<U>. You can always switch mode mid-format with an explicit C<C0> or C<U0> in the format. This mode remains in effect until the next mode change, or until the end of the C<()> group it (directly) applies to. Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode bytes is not necessarily obvious. Probably only the first of these is what you want: $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' 03B1.03C9 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' CE.B1.CF.89 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' CE.B1.CF.89 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' C3.8E.C2.B1.C3.8F.C2.89 Those examples also illustrate that you should not try to use C<pack>/C<unpack> as a substitute for the L<Encode> module. =item * You must yourself do any alignment or padding by inserting, for example, enough C<"x">es while packing. There is no way for pack() and unpack() to know where characters are going to or coming from, so they handle their output and input as flat sequences of characters. =item * A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may take a repeat count either as postfix, or for unpack(), also via the C</> template character. Within each repetition of a group, positioning with C<@> starts over at 0. Therefore, the result of pack("@1A((@2A)@3A)", qw[X Y Z]) is the string C<"\0X\0\0YZ">. =item * C<x> and C<X> accept the C<!> modifier to act as alignment commands: they jump forward or back to the closest position aligned at a multiple of C<count> characters. For example, to pack() or unpack() a C structure like struct { char c; /* one signed, 8-bit character */ double d; char cc[2]; } one may need to use the template C<c x![d] d c[2]>. This assumes that doubles must be aligned to the size of double. For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1; both are no-ops. =item * C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to represent signed 16-/32-bit integers in big-/little-endian order. This is portable only when all platforms sharing packed data use the same binary representation for signed integers; for example, when all platforms use two's-complement representation. =item * Comments can be embedded in a TEMPLATE using C<#> through the end of line. White space can separate pack codes from each other, but modifiers and repeat counts must follow immediately. Breaking complex templates into individual line-by-line components, suitably annotated, can do as much to improve legibility and maintainability of pack/unpack formats as C</x> can for complicated pattern matches. =item * If TEMPLATE requires more arguments than pack() is given, pack() assumes additional C<""> arguments. If TEMPLATE requires fewer arguments than given, extra arguments are ignored. =back Examples: $foo = pack("WWWW",65,66,67,68); # foo eq "ABCD" $foo = pack("W4",65,66,67,68); # same thing $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); # same thing with Unicode circled letters. $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); # same thing with Unicode circled letters. You don't get the # UTF-8 bytes because the U at the start of the format caused # a switch to U0-mode, so the UTF-8 bytes get joined into # characters $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" # This is the UTF-8 encoding of the string in the # previous example $foo = pack("ccxxcc",65,66,67,68); # foo eq "AB\0\0CD" # NOTE: The examples above featuring "W" and "c" are true # only on ASCII and ASCII-derived systems such as ISO Latin 1 # and UTF-8. On EBCDIC systems, the first example would be # $foo = pack("WWWW",193,194,195,196); $foo = pack("s2",1,2); # "\001\000\002\000" on little-endian # "\000\001\000\002" on big-endian $foo = pack("a4","abcd","x","y","z"); # "abcd" $foo = pack("aaaa","abcd","x","y","z"); # "axyz" $foo = pack("a14","abcdefg"); # "abcdefg\0\0\0\0\0\0\0" $foo = pack("i9pl", gmtime); # a real struct tm (on my system anyway) $utmp_template = "Z8 Z8 Z16 L"; $utmp = pack($utmp_template, @utmp1); # a struct utmp (BSDish) @utmp2 = unpack($utmp_template, $utmp); # "@utmp1" eq "@utmp2" sub bintodec { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } $foo = pack('sx2l', 12, 34); # short 12, two zero bytes padding, long 34 $bar = pack('s@4l', 12, 34); # short 12, zero fill to position 4, long 34 # $foo eq $bar $baz = pack('s.l', 12, 4, 34); # short 12, zero fill to position 4, long 34 $foo = pack('nN', 42, 4711); # pack big-endian 16- and 32-bit unsigned integers $foo = pack('S>L>', 42, 4711); # exactly the same $foo = pack('s<l<', -42, 4711); # pack little-endian 16- and 32-bit signed integers $foo = pack('(sl)<', -42, 4711); # exactly the same The same template may generally also be used in unpack(). =item package NAMESPACE =item package NAMESPACE VERSION X<package> X<module> X<namespace> X<version> =item package NAMESPACE BLOCK =item package NAMESPACE VERSION BLOCK X<package> X<module> X<namespace> X<version> =for Pod::Functions declare a separate global namespace Declares the BLOCK or the rest of the compilation unit as being in the given namespace. The scope of the package declaration is either the supplied code BLOCK or, in the absence of a BLOCK, from the declaration itself through the end of current scope (the enclosing block, file, or C<eval>). That is, the forms without a BLOCK are operative through the end of the current scope, just like the C<my>, C<state>, and C<our> operators. All unqualified dynamic identifiers in this scope will be in the given namespace, except where overridden by another C<package> declaration or when they're one of the special identifiers that qualify into C<main::>, like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables. A package statement affects dynamic variables only, including those you've used C<local> on, but I<not> lexical variables, which are created with C<my>, C<state>, or C<our>. Typically it would be the first declaration in a file included by C<require> or C<use>. You can switch into a package in more than one place, since this only determines which default symbol table the compiler uses for the rest of that block. You can refer to identifiers in other packages than the current one by prefixing the identifier with the package name and a double colon, as in C<$SomePack::var> or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main> package as assumed. That is, C<$::sail> is equivalent to C<$main::sail> (as well as to C<$main'sail>, still seen in ancient code, mostly from Perl 4). If VERSION is provided, C<package> sets the C<$VERSION> variable in the given namespace to a L<version> object with the VERSION provided. VERSION must be a "strict" style version number as defined by the L<version> module: a positive decimal number (integer or decimal-fraction) without exponentiation or else a dotted-decimal v-string with a leading 'v' character and at least three components. You should set C<$VERSION> only once per package. See L<perlmod/"Packages"> for more information about packages, modules, and classes. See L<perlsub> for other scoping issues. =item __PACKAGE__ X<__PACKAGE__> =for Pod::Functions +5.004 the current package A special token that returns the name of the package in which it occurs. =item pipe READHANDLE,WRITEHANDLE X<pipe> =for Pod::Functions open a pair of connected filehandles Opens a pair of connected pipes like the corresponding system call. 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 IO buffering, so you may need to set C<$|> to flush your WRITEHANDLE after each command, depending on the application. See L<IPC::Open2>, L<IPC::Open3>, and L<perlipc/"Bidirectional Communication with Another Process"> for examples of such things. On systems that support a close-on-exec flag on files, that flag is set on all newly opened file descriptors whose C<fileno>s are I<higher> than the current value of $^F (by default 2 for C<STDERR>). See L<perlvar/$^F>. =item pop ARRAY X<pop> X<stack> =item pop EXPR =item pop =for Pod::Functions remove the last element from an array and return it Pops and returns the last value of the array, shortening the array by one element. Returns the undefined value if the array is empty, although this may also happen at other times. If ARRAY is omitted, pops the C<@ARGV> array in the main program, but the C<@_> array in subroutines, just like C<shift>. Starting with Perl 5.14, C<pop> can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<pop> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) =item pos SCALAR X<pos> X<match, position> =item pos =for Pod::Functions find or set the offset for the last/next m//g search Returns the offset of where the last C<m//g> search left off for the variable in question (C<$_> is used when the variable is not specified). Note that 0 is a valid match offset. C<undef> indicates that the search position is reset (usually due to match failure, but can also be because no match has yet been run on the scalar). C<pos> directly accesses the location used by the regexp engine to store the offset, so assigning to C<pos> will change that offset, and so will also influence the C<\G> zero-width assertion in regular expressions. Both of these effects take place for the next match, so you can't affect the position with C<pos> during the current match, such as in C<(?{pos() = 5})> or C<s//pos() = 5/e>. Setting C<pos> also resets the I<matched with zero-length> flag, described under L<perlre/"Repeated Patterns Matching a Zero-length Substring">. Because a failed C<m//gc> match doesn't reset the offset, the return from C<pos> won't change either in this case. See L<perlre> and L<perlop>. =item print FILEHANDLE LIST X<print> =item print FILEHANDLE =item print LIST =item print =for Pod::Functions output a list to a filehandle Prints a string or a list of strings. Returns true if successful. FILEHANDLE may be a scalar variable containing the name of or a reference to the filehandle, thus introducing one level of indirection. (NOTE: If FILEHANDLE is a variable and the next token is a term, it may be misinterpreted as an operator unless you interpose a C<+> or put parentheses around the arguments.) If FILEHANDLE is omitted, prints to the last selected (see L</select>) output handle. If LIST is omitted, prints C<$_> to the currently selected output handle. To use FILEHANDLE alone to print the content of C<$_> to it, you must use a real filehandle like C<FH>, not an indirect one like C<$fh>. To set the default output handle to something other than STDOUT, use the select operation. The current value of C<$,> (if any) is printed between each LIST item. The current value of C<$\> (if any) is printed after the entire LIST has been printed. Because print takes a LIST, anything in the LIST is evaluated in list context, including any subroutines whose return lists you pass to C<print>. Be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print; put parentheses around all arguments (or interpose a C<+>, but that doesn't look as good). If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead, in which case the LIST may not be omitted: print { $files[$i] } "stuff\n"; print { $OK ? STDOUT : STDERR } "stuff\n"; Printing to a closed pipe or socket will generate a SIGPIPE signal. See L<perlipc> for more on signal handling. =item printf FILEHANDLE FORMAT, LIST X<printf> =item printf FILEHANDLE =item printf FORMAT, LIST =item printf =for Pod::Functions output a formatted list to a filehandle Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that C<$\> (the output record separator) is not appended. The first argument of the list will be interpreted as the C<printf> format. See L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format argument. If you omit the LIST, C<$_> is used; to use FILEHANDLE without a LIST, you must use a real filehandle like C<FH>, not an indirect one like C<$fh>. If C<use locale> (including C<use locale ':not_characters'>) is in effect and POSIX::setlocale() has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC locale setting. See L<perllocale> and L<POSIX>. Don't fall into the trap of using a C<printf> when a simple C<print> would do. The C<print> is more efficient and less error prone. =item prototype FUNCTION X<prototype> =for Pod::Functions +5.002 get the prototype (if any) of a subroutine Returns the prototype of a function as a string (or C<undef> if the function has no prototype). FUNCTION is a reference to, or the name of, the function whose prototype you want to retrieve. If FUNCTION is a string starting with C<CORE::>, the rest is taken as a name for a Perl builtin. If the builtin is not I<overridable> (such as C<qw//>) or if its arguments cannot be adequately expressed by a prototype (such as C<system>), prototype() returns C<undef>, because the builtin does not really behave like a Perl function. Otherwise, the string describing the equivalent prototype is returned. =item push ARRAY,LIST X<push> X<stack> =item push EXPR,LIST =for Pod::Functions append one or more elements to an array Treats ARRAY as a stack by appending the values of LIST to the end of ARRAY. The length of ARRAY increases by the length of LIST. Has the same effect as for $value (LIST) { $ARRAY[++$#ARRAY] = $value; } but is more efficient. Returns the number of elements in the array following the completed C<push>. Starting with Perl 5.14, C<push> can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<push> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) =item q/STRING/ =for Pod::Functions singly quote a string =item qq/STRING/ =for Pod::Functions doubly quote a string =item qw/STRING/ =for Pod::Functions quote a list of words =item qx/STRING/ =for Pod::Functions backquote quote a string Generalized quotes. See L<perlop/"Quote-Like Operators">. =item qr/STRING/ =for Pod::Functions +5.005 compile pattern Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">. =item quotemeta EXPR X<quotemeta> X<metacharacter> =item quotemeta =for Pod::Functions quote regular expression magic characters Returns the value of EXPR with all the ASCII non-"word" characters backslashed. (That is, all ASCII characters not matching C</[A-Za-z_0-9]/> will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the C<\Q> escape in double-quoted strings. (See below for the behavior on non-ASCII code points.) If EXPR is omitted, uses C<$_>. quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into regular expressions, because by default an interpolated variable will be considered a mini-regular expression. For example: my $sentence = 'The quick brown fox jumped over the lazy dog'; my $substring = 'quick.*?fox'; $sentence =~ s{$substring}{big bad wolf}; Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>. On the other hand: my $sentence = 'The quick brown fox jumped over the lazy dog'; my $substring = 'quick.*?fox'; $sentence =~ s{\Q$substring\E}{big bad wolf}; Or: my $sentence = 'The quick brown fox jumped over the lazy dog'; my $substring = 'quick.*?fox'; my $quoted_substring = quotemeta($substring); $sentence =~ s{$quoted_substring}{big bad wolf}; Will both leave the sentence as is. Normally, when accepting literal string input from the user, quotemeta() or C<\Q> must be used. In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded strings, but not quoted in UTF-8 strings. Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for quoting non-ASCII characters; the quoting of ASCII characters is unchanged. Also unchanged is the quoting of non-UTF-8 strings when outside the scope of a C<use feature 'unicode_strings'>, which is to quote all characters in the upper Latin1 range. This provides complete backwards compatibility for old programs which do not use Unicode. (Note that C<unicode_strings> is automatically enabled within the scope of a S<C<use v5.12>> or greater.) Within the scope of C<use locale>, all non-ASCII Latin1 code points are quoted whether the string is encoded as UTF-8 or not. As mentioned above, locale does not affect the quoting of ASCII-range characters. This protects against those locales where characters such as C<"|"> are considered to be word characters. Otherwise, Perl quotes non-ASCII characters using an adaptation from Unicode (see L<http://www.unicode.org/reports/tr31/>.) The only code points that are quoted are those that have any of the Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, Default_Ignorable_Code_Point, or General_Category=Control. Of these properties, the two important ones are Pattern_Syntax and Pattern_White_Space. They have been set up by Unicode for exactly this purpose of deciding which characters in a regular expression pattern should be quoted. No character that can be in an identifier has these properties. Perl promises, that if we ever add regular expression pattern metacharacters to the dozen already defined (C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the Pattern_Syntax property. Perl also promises, that if we ever add characters that are considered to be white space in regular expressions (currently mostly affected by C</x>), they will all have the Pattern_White_Space property. Unicode promises that the set of code points that have these two properties will never change, so something that is not quoted in v5.16 will never need to be quoted in any future Perl release. (Not all the code points that match Pattern_Syntax have actually had characters assigned to them; so there is room to grow, but they are quoted whether assigned or not. Perl, of course, would never use an unassigned code point as an actual metacharacter.) Quoting characters that have the other 3 properties is done to enhance the readability of the regular expression and not because they actually need to be quoted for regular expression purposes (characters with the White_Space property are likely to be indistinguishable on the page or screen from those with the Pattern_White_Space property; and the other two properties contain non-printing characters). =item rand EXPR X<rand> X<random> =item rand =for Pod::Functions retrieve the next pseudorandom number Returns a random fractional number greater than or equal to C<0> and less than the value of EXPR. (EXPR should be positive.) If EXPR is omitted, the value C<1> is used. Currently EXPR with the value C<0> is also special-cased as C<1> (this was undocumented before Perl 5.8.0 and is subject to change in future versions of Perl). Automatically calls C<srand> unless C<srand> has already been called. See also C<srand>. Apply C<int()> to the value returned by C<rand()> if you want random integers instead of random fractional numbers. For example, int(rand(10)) returns a random integer between C<0> and C<9>, inclusive. (Note: If your rand function consistently returns numbers that are too large or too small, then your version of Perl was probably compiled with the wrong number of RANDBITS.) B<C<rand()> is not cryptographically secure. You should not rely on it in security-sensitive situations.> As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, and L<Math::TrulyRandom>. =item read FILEHANDLE,SCALAR,LENGTH,OFFSET X<read> X<file, read> =item read FILEHANDLE,SCALAR,LENGTH =for Pod::Functions fixed-length buffered input from a filehandle Attempts to read LENGTH I<characters> of data into variable SCALAR from the specified FILEHANDLE. Returns the number of characters actually read, C<0> at end of file, or undef if there was an error (in the latter case C<$!> is also set). SCALAR will be grown or shrunk so that the last character actually read is the last character of the scalar after the read. An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with C<"\0"> bytes before the result of the read is appended. The call is implemented in terms of either Perl's or your system's native fread(3) library function. To get a true read(2) system call, see L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>. Note the I<characters>: depending on the status of the filehandle, either (8-bit) bytes or characters are read. By default, all filehandles operate on bytes, but for example if the filehandle has been opened with the C<:utf8> I/O layer (see L</open>, and the C<open> pragma, L<open>), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the C<:encoding> pragma: in that case pretty much any characters can be read. =item readdir DIRHANDLE X<readdir> =for Pod::Functions get a directory from a directory handle Returns the next directory entry for a directory opened by C<opendir>. If used in list context, returns all the rest of the entries in the directory. If there are no more entries, returns the undefined value in scalar context and the empty list in list context. If you're planning to filetest the return values out of a C<readdir>, you'd better prepend the directory in question. Otherwise, because we didn't C<chdir> there, it would have been testing the wrong file. opendir(my $dh, $some_dir) || die "can't opendir $some_dir: $!"; @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); closedir $dh; As of Perl 5.11.2 you can use a bare C<readdir> in a C<while> loop, which will set C<$_> on every iteration. opendir(my $dh, $some_dir) || die; while(readdir $dh) { print "$some_dir/$_\n"; } closedir $dh; To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious failures, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.012; # so readdir assigns to $_ in a lone while test =item readline EXPR =item readline X<readline> X<gets> X<fgets> =for Pod::Functions fetch a record from a file Reads from the filehandle whose typeglob is contained in EXPR (or from C<*ARGV> if EXPR is not provided). In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns C<undef>. In list context, reads until end-of-file is reached and returns a list of lines. Note that the notion of "line" used here is whatever you may have defined with C<$/> or C<$INPUT_RECORD_SEPARATOR>). See L<perlvar/"$/">. When C<$/> is set to C<undef>, when C<readline> is in scalar context (i.e., file slurp mode), and when an empty file is read, it returns C<''> the first time, followed by C<undef> subsequently. This is the internal function implementing the C<< <EXPR> >> operator, but you can use it directly. The C<< <EXPR> >> operator is discussed in more detail in L<perlop/"I/O Operators">. $line = <STDIN>; $line = readline(*STDIN); # same thing If C<readline> encounters an operating system error, C<$!> will be set with the corresponding error message. It can be helpful to check C<$!> when you are reading from filehandles you don't trust, such as a tty or a socket. The following example uses the operator form of C<readline> and dies if the result is not defined. while ( ! eof($fh) ) { defined( $_ = <$fh> ) or die "readline failed: $!"; ... } Note that you have can't handle C<readline> errors that way with the C<ARGV> filehandle. In that case, you have to open each element of C<@ARGV> yourself since C<eof> handles C<ARGV> differently. foreach my $arg (@ARGV) { open(my $fh, $arg) or warn "Can't open $arg: $!"; while ( ! eof($fh) ) { defined( $_ = <$fh> ) or die "readline failed for $arg: $!"; ... } } =item readlink EXPR X<readlink> =item readlink =for Pod::Functions determine where a symbolic link is pointing Returns the value of a symbolic link, if symbolic links are implemented. If not, raises an exception. If there is a system error, returns the undefined value and sets C<$!> (errno). If EXPR is omitted, uses C<$_>. Portability issues: L<perlport/readlink>. =item readpipe EXPR =item readpipe X<readpipe> =for Pod::Functions execute a system command and collect standard output EXPR is executed as a system command. The collected standard output of the command is returned. In scalar context, it comes back as a single (potentially multi-line) string. In list context, returns a list of lines (however you've defined lines with C<$/> or C<$INPUT_RECORD_SEPARATOR>). This is the internal function implementing the C<qx/EXPR/> operator, but you can use it directly. The C<qx/EXPR/> operator is discussed in more detail in L<perlop/"I/O Operators">. If EXPR is omitted, uses C<$_>. =item recv SOCKET,SCALAR,LENGTH,FLAGS X<recv> =for Pod::Functions receive a message over a Socket Receives a message on a socket. Attempts to receive LENGTH characters of data into variable SCALAR from the specified SOCKET filehandle. SCALAR will be grown or shrunk to the length actually read. Takes the same flags as the system call of the same name. Returns the address of the sender if SOCKET's protocol supports this; returns an empty string otherwise. If there's an error, returns the undefined value. This call is actually implemented in terms of recvfrom(2) system call. See L<perlipc/"UDP: Message Passing"> for examples. Note the I<characters>: depending on the status of the socket, either (8-bit) bytes or characters are received. By default all sockets operate on bytes, but for example if the socket has been changed using binmode() to operate with the C<:encoding(utf8)> I/O layer (see the C<open> pragma, L<open>), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the C<:encoding> pragma: in that case pretty much any characters can be read. =item redo LABEL X<redo> =item redo =for Pod::Functions start this loop iteration over again The C<redo> command restarts the loop block without evaluating the conditional again. The C<continue> block, if any, is not executed. If the LABEL is omitted, the command refers to the innermost enclosing loop. Programs that want to lie to themselves about what was just input normally use this command: # a simpleminded Pascal comment stripper # (warning: assumes no { or } in strings) LINE: while (<STDIN>) { while (s|({.*}.*){.*}|$1 |) {} s|{.*}| |; if (s|{.*| |) { $front = $_; while (<STDIN>) { if (/}/) { # end of comment? s|^|$front\{|; redo LINE; } } } print; } C<redo> cannot be used to retry a block that returns a value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop that executes once. Thus C<redo> inside such a block will effectively turn it into a looping construct. See also L</continue> for an illustration of how C<last>, C<next>, and C<redo> work. =item ref EXPR X<ref> X<reference> =item ref =for Pod::Functions find out the type of thing being referenced Returns a non-empty string if EXPR is a reference, the empty string otherwise. If EXPR is not specified, C<$_> will be used. The value returned depends on the type of thing the reference is a reference to. Builtin types include: SCALAR ARRAY HASH CODE REF GLOB LVALUE FORMAT IO VSTRING Regexp If the referenced object has been blessed into a package, then that package name is returned instead. You can think of C<ref> as a C<typeof> operator. if (ref($r) eq "HASH") { print "r is a reference to a hash.\n"; } unless (ref($r)) { print "r is not a reference at all.\n"; } The return value C<LVALUE> indicates a reference to an lvalue that is not a variable. You get this from taking the reference of function calls like C<pos()> or C<substr()>. C<VSTRING> is returned if the reference points to a L<version string|perldata/"Version Strings">. The result C<Regexp> indicates that the argument is a regular expression resulting from C<qr//>. See also L<perlref>. =item rename OLDNAME,NEWNAME X<rename> X<move> X<mv> X<ren> =for Pod::Functions change a filename Changes the name of a file; an existing file NEWNAME will be clobbered. Returns true for success, false otherwise. Behavior of this function varies wildly depending on your system implementation. For example, it will usually not work across file system boundaries, even though the system I<mv> command sometimes compensates for this. Other restrictions include whether it works on directories, open files, or pre-existing files. Check L<perlport> and either the rename(2) manpage or equivalent system documentation for details. For a platform independent C<move> function look at the L<File::Copy> module. Portability issues: L<perlport/rename>. =item require VERSION X<require> =item require EXPR =item require =for Pod::Functions load in external functions from a library at runtime Demands a version of Perl specified by VERSION, or demands some semantics specified by EXPR or by C<$_> if EXPR is not supplied. VERSION may be either a numeric argument such as 5.006, which will be compared to C<$]>, or a literal of the form v5.6.1, which will be compared to C<$^V> (aka $PERL_VERSION). An exception is raised if VERSION is greater than the version of the current Perl interpreter. Compare with L</use>, which can do a similar check at compile time. Specifying VERSION as a literal of the form v5.6.1 should generally be avoided, because it leads to misleading error messages under earlier versions of Perl that do not support this syntax. The equivalent numeric version should be used instead. require v5.6.1; # run time version check require 5.6.1; # ditto require 5.006_001; # ditto; preferred for backwards compatibility Otherwise, C<require> demands that a library file be included if it hasn't already been included. The file is included via the do-FILE mechanism, which is essentially just a variety of C<eval> with the caveat that lexical variables in the invoking script will be invisible to the included code. Has semantics similar to the following subroutine: sub require { my ($filename) = @_; if (exists $INC{$filename}) { return 1 if $INC{$filename}; die "Compilation failed in require"; } my ($realfilename,$result); ITER: { foreach $prefix (@INC) { $realfilename = "$prefix/$filename"; if (-f $realfilename) { $INC{$filename} = $realfilename; $result = do $realfilename; last ITER; } } die "Can't find $filename in \@INC"; } if ($@) { $INC{$filename} = undef; die $@; } elsif (!$result) { delete $INC{$filename}; die "$filename did not return true value"; } else { return $result; } } Note that the file will not be included twice under the same specified name. The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with C<1;> unless you're sure it'll return true otherwise. But it's better just to put the C<1;>, in case you add more statements. If EXPR is a bareword, the require assumes a "F<.pm>" extension and replaces "F<::>" with "F</>" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace. In other words, if you try this: require Foo::Bar; # a splendid bareword The require function will actually look for the "F<Foo/Bar.pm>" file in the directories specified in the C<@INC> array. But if you try this: $class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of the "" The require function will look for the "F<Foo::Bar>" file in the @INC array and will complain about not finding "F<Foo::Bar>" there. In this case you can do: eval "require $class"; Now that you understand how C<require> looks for files with a bareword argument, there is a little extra functionality going on behind the scenes. Before C<require> looks for a "F<.pm>" extension, it will first look for a similar filename with a "F<.pmc>" extension. If this file is found, it will be loaded in place of any file ending in a "F<.pm>" extension. You can also insert hooks into the import facility by putting Perl code directly into the @INC array. There are three forms of hooks: subroutine references, array references, and blessed objects. Subroutine references are the simplest case. When the inclusion system walks through @INC and encounters a subroutine, this subroutine gets called with two parameters, the first a reference to itself, and the second the name of the file to be included (e.g., "F<Foo/Bar.pm>"). The subroutine should return either nothing or else a list of up to three values in the following order: =over =item 1 A filehandle, from which the file will be read. =item 2 A reference to a subroutine. If there is no filehandle (previous item), then this subroutine is expected to generate one line of source code per call, writing the line into C<$_> and returning 1, then finally at end of file returning 0. If there is a filehandle, then the subroutine will be called to act as a simple source filter, with the line as read in C<$_>. Again, return 1 for each valid line, and 0 after all lines have been returned. =item 3 Optional state for the subroutine. The state is passed in as C<$_[1]>. A reference to the subroutine itself is passed in as C<$_[0]>. =back If an empty list, C<undef>, or nothing that matches the first 3 values above is returned, then C<require> looks at the remaining elements of @INC. Note that this filehandle must be a real filehandle (strictly a typeglob or reference to a typeglob, whether blessed or unblessed); tied filehandles will be ignored and processing will stop there. If the hook is an array reference, its first element must be a subroutine reference. This subroutine is called as above, but the first parameter is the array reference. This lets you indirectly pass arguments to the subroutine. In other words, you can write: push @INC, \&my_sub; sub my_sub { my ($coderef, $filename) = @_; # $coderef is \&my_sub ... } or: push @INC, [ \&my_sub, $x, $y, ... ]; sub my_sub { my ($arrayref, $filename) = @_; # Retrieve $x, $y, ... my @parameters = @$arrayref[1..$#$arrayref]; ... } If the hook is an object, it must provide an INC method that will be called as above, the first parameter being the object itself. (Note that you must fully qualify the sub's name, as unqualified C<INC> is always forced into package C<main>.) Here is a typical code layout: # In Foo.pm package Foo; sub new { ... } sub Foo::INC { my ($self, $filename) = @_; ... } # In the main program push @INC, Foo->new(...); These hooks are also permitted to set the %INC entry corresponding to the files they have loaded. See L<perlvar/%INC>. For a yet-more-powerful import facility, see L</use> and L<perlmod>. =item reset EXPR X<reset> =item reset =for Pod::Functions clear all variables of a given name Generally used in a C<continue> block at the end of a loop to clear variables and reset C<??> searches so that they work again. The expression is interpreted as a list of single characters (hyphens allowed for ranges). All variables and arrays beginning with one of those letters are reset to their pristine state. If the expression is omitted, one-match searches (C<?pattern?>) are reset to match again. Only resets variables or searches in the current package. Always returns 1. Examples: reset 'X'; # reset all X variables reset 'a-z'; # reset lower case variables reset; # just reset ?one-time? searches Resetting C<"A-Z"> is not recommended because you'll wipe out your C<@ARGV> and C<@INC> arrays and your C<%ENV> hash. Resets only package variables; lexical variables are unaffected, but they clean themselves up on scope exit anyway, so you'll probably want to use them instead. See L</my>. =item return EXPR X<return> =item return =for Pod::Functions get out of a function early Returns from a subroutine, C<eval>, or C<do FILE> with the value given in EXPR. Evaluation of EXPR may be in list, scalar, or void context, depending on how the return value will be used, and the context may vary from one execution to the next (see L</wantarray>). If no EXPR is given, returns an empty list in list context, the undefined value in scalar context, and (of course) nothing at all in void context. (In the absence of an explicit C<return>, a subroutine, eval, or do FILE automatically returns the value of the last expression evaluated.) =item reverse LIST X<reverse> X<rev> X<invert> =for Pod::Functions flip a string or a list In list context, returns a list value consisting of the elements of LIST in the opposite order. In scalar context, concatenates the elements of LIST and returns a string value with all characters in the opposite order. print join(", ", reverse "world", "Hello"); # Hello, world print scalar reverse "dlrow ,", "olleH"; # Hello, world Used without arguments in scalar context, reverse() reverses C<$_>. $_ = "dlrow ,olleH"; print reverse; # No output, list context print scalar reverse; # Hello, world Note that reversing an array to itself (as in C<@a = reverse @a>) will preserve non-existent elements whenever possible, i.e., for non magical arrays or tied arrays with C<EXISTS> and C<DELETE> methods. This operator is also handy for inverting a hash, although there are some caveats. If a value is duplicated in the original hash, only one of those can be represented as a key in the inverted hash. Also, this has to unwind one hash and build a whole new one, which may take some time on a large hash, such as from a DBM file. %by_name = reverse %by_address; # Invert the hash =item rewinddir DIRHANDLE X<rewinddir> =for Pod::Functions reset directory handle Sets the current position to the beginning of the directory for the C<readdir> routine on DIRHANDLE. Portability issues: L<perlport/rewinddir>. =item rindex STR,SUBSTR,POSITION X<rindex> =item rindex STR,SUBSTR =for Pod::Functions right-to-left substring search Works just like index() except that it returns the position of the I<last> occurrence of SUBSTR in STR. If POSITION is specified, returns the last occurrence beginning at or before that position. =item rmdir FILENAME X<rmdir> X<rd> X<directory, remove> =item rmdir =for Pod::Functions remove a directory Deletes the directory specified by FILENAME if that directory is empty. If it succeeds it returns true; otherwise it returns false and sets C<$!> (errno). If FILENAME is omitted, uses C<$_>. To remove a directory tree recursively (C<rm -rf> on Unix) look at the C<rmtree> function of the L<File::Path> module. =item s/// =for Pod::Functions replace a pattern with a string The substitution operator. See L<perlop/"Regexp Quote-Like Operators">. =item say FILEHANDLE LIST X<say> =item say FILEHANDLE =item say LIST =item say =for Pod::Functions +say output a list to a filehandle, appending a newline Just like C<print>, but implicitly appends a newline. C<say LIST> is simply an abbreviation for C<{ local $\ = "\n"; print LIST }>. To use FILEHANDLE without a LIST to print the contents of C<$_> to it, you must use a real filehandle like C<FH>, not an indirect one like C<$fh>. This keyword is available only when the C<"say"> feature is enabled, or when prefixed with C<CORE::>; see L<feature>. Alternately, include a C<use v5.10> or later to the current scope. =item scalar EXPR X<scalar> X<context> =for Pod::Functions force a scalar context Forces EXPR to be interpreted in scalar context and returns the value of EXPR. @counts = ( scalar @a, scalar @b, scalar @c ); There is no equivalent operator to force an expression to be interpolated in list context because in practice, this is never needed. If you really wanted to do so, however, you could use the construction C<@{[ (some expression) ]}>, but usually a simple C<(some expression)> suffices. Because C<scalar> is a unary operator, if you accidentally use a parenthesized list for the EXPR, this behaves as a scalar comma expression, evaluating all but the last element in void context and returning the final element evaluated in scalar context. This is seldom what you want. The following single statement: print uc(scalar(&foo,$bar)),$baz; is the moral equivalent of these two: &foo; print(uc($bar),$baz); See L<perlop> for more details on unary operators and the comma operator. =item seek FILEHANDLE,POSITION,WHENCE X<seek> X<fseek> X<filehandle, position> =for Pod::Functions reposition file pointer for random-access I/O Sets FILEHANDLE's position, just like the C<fseek> call of C<stdio>. FILEHANDLE may be an expression whose value gives the name of the filehandle. The values for WHENCE are C<0> to set the new position I<in bytes> to POSITION; C<1> to set it to the current position plus POSITION; and C<2> to set it to EOF plus POSITION, typically negative. For WHENCE you may use the constants C<SEEK_SET>, C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end of the file) from the L<Fcntl> module. Returns C<1> on success, false otherwise. Note the I<in bytes>: even if the filehandle has been set to operate on characters (for example by using the C<:encoding(utf8)> open layer), tell() will return byte offsets, not character offsets (because implementing that would render seek() and tell() rather slow). If you want to position the file for C<sysread> or C<syswrite>, don't use C<seek>, because buffering makes its effect on the file's read-write position unpredictable and non-portable. Use C<sysseek> instead. Due to the rules and rigors of ANSI C, on some systems you have to do a seek whenever you switch between reading and writing. Amongst other things, this may have the effect of calling stdio's clearerr(3). A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position: seek(TEST,0,1); This is also useful for applications emulating C<tail -f>. Once you hit EOF on your read and then sleep for a while, you (probably) have to stick in a dummy seek() to reset things. The C<seek> doesn't change the position, but it I<does> clear the end-of-file condition on the handle, so that the next C<< <FILE> >> makes Perl try again to read something. (We hope.) If that doesn't work (some I/O implementations are particularly cantankerous), you might need something like this: for (;;) { for ($curpos = tell(FILE); $_ = <FILE>; $curpos = tell(FILE)) { # search for some stuff and put it into files } sleep($for_a_while); seek(FILE, $curpos, 0); } =item seekdir DIRHANDLE,POS X<seekdir> =for Pod::Functions reposition directory pointer Sets the current position for the C<readdir> routine on DIRHANDLE. POS must be a value returned by C<telldir>. C<seekdir> also has the same caveats about possible directory compaction as the corresponding system library routine. =item select FILEHANDLE X<select> X<filehandle, default> =item select =for Pod::Functions reset default output or do I/O multiplexing Returns the currently selected filehandle. If FILEHANDLE is supplied, sets the new current default filehandle for output. This has two effects: first, a C<write> or a C<print> without a filehandle default to this FILEHANDLE. Second, references to variables related to output will refer to this output channel. For example, to set the top-of-form format for more than one output channel, you might do the following: select(REPORT1); $^ = 'report1_top'; select(REPORT2); $^ = 'report2_top'; FILEHANDLE may be an expression whose value gives the name of the actual filehandle. Thus: $oldfh = select(STDERR); $| = 1; select($oldfh); Some programmers may prefer to think of filehandles as objects with methods, preferring to write the last example as: use IO::Handle; STDERR->autoflush(1); Portability issues: L<perlport/select>. =item select RBITS,WBITS,EBITS,TIMEOUT X<select> This calls the select(2) syscall with the bit masks specified, which can be constructed using C<fileno> and C<vec>, along these lines: $rin = $win = $ein = ''; vec($rin, fileno(STDIN), 1) = 1; vec($win, fileno(STDOUT), 1) = 1; $ein = $rin | $win; If you want to select on many filehandles, you may wish to write a subroutine like this: sub fhbits { my @fhlist = @_; my $bits = ""; for my $fh (@fhlist) { vec($bits, fileno($fh), 1) = 1; } return $bits; } $rin = fhbits(*STDIN, *TTY, *MYSOCK); The usual idiom is: ($nfound,$timeleft) = select($rout=$rin, $wout=$win, $eout=$ein, $timeout); or to block until something becomes ready just do this $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef); Most systems do not bother to return anything useful in $timeleft, so calling select() in scalar context just returns $nfound. Any of the bit masks can also be undef. The timeout, if specified, is in seconds, which may be fractional. Note: not all implementations are capable of returning the $timeleft. If not, they always return $timeleft equal to the supplied $timeout. You can effect a sleep of 250 milliseconds this way: select(undef, undef, undef, 0.25); Note that whether C<select> gets restarted after signals (say, SIGALRM) is implementation-dependent. See also L<perlport> for notes on the portability of C<select>. On error, C<select> behaves just like select(2): it returns -1 and sets C<$!>. On some Unixes, select(2) may report a socket file descriptor as "ready for reading" even when no data is available, and thus any subsequent C<read> would block. This can be avoided if you always use O_NONBLOCK on the socket. See select(2) and fcntl(2) for further details. The standard C<IO::Select> module provides a user-friendlier interface to C<select>, mostly because it does all the bit-mask work for you. B<WARNING>: One should not attempt to mix buffered I/O (like C<read> or <FH>) with C<select>, except as permitted by POSIX, and even then only on POSIX systems. You have to use C<sysread> instead. Portability issues: L<perlport/select>. =item semctl ID,SEMNUM,CMD,ARG X<semctl> =for Pod::Functions SysV semaphore control operations Calls the System V IPC function semctl(2). You'll probably have to say use IPC::SysV; first to get the correct constant definitions. If CMD is IPC_STAT or GETALL, then ARG must be a variable that will hold the returned semid_ds structure or semaphore value array. Returns like C<ioctl>: the undefined value for error, "C<0 but true>" for zero, or the actual return value otherwise. The ARG must consist of a vector of native short integers, which may be created with C<pack("s!",(0)x$nsem)>. See also L<perlipc/"SysV IPC">, C<IPC::SysV>, C<IPC::Semaphore> documentation. Portability issues: L<perlport/semctl>. =item semget KEY,NSEMS,FLAGS X<semget> =for Pod::Functions get set of SysV semaphores Calls the System V IPC function semget(2). Returns the semaphore id, or the undefined value on error. See also L<perlipc/"SysV IPC">, C<IPC::SysV>, C<IPC::SysV::Semaphore> documentation. Portability issues: L<perlport/semget>. =item semop KEY,OPSTRING X<semop> =for Pod::Functions SysV semaphore operations Calls the System V IPC function semop(2) for semaphore operations such as signalling and waiting. OPSTRING must be a packed array of semop structures. Each semop structure can be generated with C<pack("s!3", $semnum, $semop, $semflag)>. The length of OPSTRING implies the number of semaphore operations. Returns true if successful, false on error. As an example, the following code waits on semaphore $semnum of semaphore id $semid: $semop = pack("s!3", $semnum, -1, 0); die "Semaphore trouble: $!\n" unless semop($semid, $semop); To signal the semaphore, replace C<-1> with C<1>. See also L<perlipc/"SysV IPC">, C<IPC::SysV>, and C<IPC::SysV::Semaphore> documentation. Portability issues: L<perlport/semop>. =item send SOCKET,MSG,FLAGS,TO X<send> =item send SOCKET,MSG,FLAGS =for Pod::Functions send a message over a socket Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET filehandle. Takes the same flags as the system call of the same name. On unconnected sockets, you must specify a destination to I<send to>, in which case it does a sendto(2) syscall. Returns the number of characters sent, or the undefined value on error. The sendmsg(2) syscall is currently unimplemented. See L<perlipc/"UDP: Message Passing"> for examples. Note the I<characters>: depending on the status of the socket, either (8-bit) bytes or characters are sent. By default all sockets operate on bytes, but for example if the socket has been changed using binmode() to operate with the C<:encoding(utf8)> I/O layer (see L</open>, or the C<open> pragma, L<open>), the I/O will operate on UTF-8 encoded Unicode characters, not bytes. Similarly for the C<:encoding> pragma: in that case pretty much any characters can be sent. =item setpgrp PID,PGRP X<setpgrp> X<group> =for Pod::Functions set the process group of a process Sets the current process group for the specified PID, C<0> for the current process. Raises an exception when used on a machine that doesn't implement POSIX setpgid(2) or BSD setpgrp(2). If the arguments are omitted, it defaults to C<0,0>. Note that the BSD 4.2 version of C<setpgrp> does not accept any arguments, so only C<setpgrp(0,0)> is portable. See also C<POSIX::setsid()>. Portability issues: L<perlport/setpgrp>. =item setpriority WHICH,WHO,PRIORITY X<setpriority> X<priority> X<nice> X<renice> =for Pod::Functions set a process's nice value Sets the current priority for a process, a process group, or a user. (See setpriority(2).) Raises an exception when used on a machine that doesn't implement setpriority(2). Portability issues: L<perlport/setpriority>. =item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL X<setsockopt> =for Pod::Functions set some socket options Sets the socket option requested. Returns C<undef> on error. Use integer constants provided by the C<Socket> module for LEVEL and OPNAME. Values for LEVEL can also be obtained from getprotobyname. OPTVAL might either be a packed string or an integer. An integer OPTVAL is shorthand for pack("i", OPTVAL). An example disabling Nagle's algorithm on a socket: use Socket qw(IPPROTO_TCP TCP_NODELAY); setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); Portability issues: L<perlport/setsockopt>. =item shift ARRAY X<shift> =item shift EXPR =item shift =for Pod::Functions remove the first element of an array, and return it Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the C<@_> array within the lexical scope of subroutines and formats, and the C<@ARGV> array outside a subroutine and also within the lexical scopes established by the C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}>, C<UNITCHECK {}>, and C<END {}> constructs. Starting with Perl 5.14, C<shift> can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<shift> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) See also C<unshift>, C<push>, and C<pop>. C<shift> and C<unshift> do the same thing to the left end of an array that C<pop> and C<push> do to the right end. =item shmctl ID,CMD,ARG X<shmctl> =for Pod::Functions SysV shared memory operations Calls the System V IPC function shmctl. You'll probably have to say use IPC::SysV; first to get the correct constant definitions. If CMD is C<IPC_STAT>, then ARG must be a variable that will hold the returned C<shmid_ds> structure. Returns like ioctl: C<undef> for error; "C<0> but true" for zero; and the actual return value otherwise. See also L<perlipc/"SysV IPC"> and C<IPC::SysV> documentation. Portability issues: L<perlport/shmctl>. =item shmget KEY,SIZE,FLAGS X<shmget> =for Pod::Functions get SysV shared memory segment identifier Calls the System V IPC function shmget. Returns the shared memory segment id, or C<undef> on error. See also L<perlipc/"SysV IPC"> and C<IPC::SysV> documentation. Portability issues: L<perlport/shmget>. =item shmread ID,VAR,POS,SIZE X<shmread> X<shmwrite> =for Pod::Functions read SysV shared memory =item shmwrite ID,STRING,POS,SIZE =for Pod::Functions write SysV shared memory Reads or writes the System V shared memory segment ID starting at position POS for size SIZE by attaching to it, copying in/out, and detaching from it. When reading, VAR must be a variable that will hold the data read. When writing, if STRING is too long, only SIZE bytes are used; if STRING is too short, nulls are written to fill out SIZE bytes. Return true if successful, false on error. shmread() taints the variable. See also L<perlipc/"SysV IPC">, C<IPC::SysV>, and the C<IPC::Shareable> module from CPAN. Portability issues: L<perlport/shmread> and L<perlport/shmwrite>. =item shutdown SOCKET,HOW X<shutdown> =for Pod::Functions close down just half of a socket connection Shuts down a socket connection in the manner indicated by HOW, which has the same interpretation as in the syscall of the same name. shutdown(SOCKET, 0); # I/we have stopped reading data shutdown(SOCKET, 1); # I/we have stopped writing data shutdown(SOCKET, 2); # I/we have stopped using this socket This is useful with sockets when you want to tell the other side you're done writing but not done reading, or vice versa. It's also a more insistent form of close because it also disables the file descriptor in any forked copies in other processes. Returns C<1> for success; on error, returns C<undef> if the first argument is not a valid filehandle, or returns C<0> and sets C<$!> for any other failure. =item sin EXPR X<sin> X<sine> X<asin> X<arcsine> =item sin =for Pod::Functions return the sine of a number Returns the sine of EXPR (expressed in radians). If EXPR is omitted, returns sine of C<$_>. For the inverse sine operation, you may use the C<Math::Trig::asin> function, or use this relation: sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) } =item sleep EXPR X<sleep> X<pause> =item sleep =for Pod::Functions block for some number of seconds Causes the script to sleep for (integer) EXPR seconds, or forever if no argument is given. Returns the integer number of seconds actually slept. May be interrupted if the process receives a signal such as C<SIGALRM>. eval { local $SIG{ALARM} = sub { die "Alarm!\n" }; sleep; }; die $@ unless $@ eq "Alarm!\n"; You probably cannot mix C<alarm> and C<sleep> calls, because C<sleep> is often implemented using C<alarm>. On some older systems, it may sleep up to a full second less than what you requested, depending on how it counts seconds. Most modern systems always sleep the full amount. They may appear to sleep longer than that, however, because your process might not be scheduled right away in a busy multitasking system. For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep(). You may also use Perl's four-argument version of select() leaving the first three arguments undefined, or you might be able to use the C<syscall> interface to access setitimer(2) if your system supports it. See L<perlfaq8> for details. See also the POSIX module's C<pause> function. =item socket SOCKET,DOMAIN,TYPE,PROTOCOL X<socket> =for Pod::Functions create a socket Opens a socket of the specified kind and attaches it to filehandle SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for the syscall of the same name. You should C<use Socket> first to get the proper definitions imported. See the examples in L<perlipc/"Sockets: Client/Server Communication">. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See L<perlvar/$^F>. =item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL X<socketpair> =for Pod::Functions create a pair of sockets Creates an unnamed pair of sockets in the specified domain, of the specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as for the syscall of the same name. If unimplemented, raises an exception. Returns true if successful. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptors, as determined by the value of $^F. See L<perlvar/$^F>. Some systems defined C<pipe> in terms of C<socketpair>, in which a call to C<pipe(Rdr, Wtr)> is essentially: use Socket; socketpair(Rdr, Wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC); shutdown(Rdr, 1); # no more writing for reader shutdown(Wtr, 0); # no more reading for writer See L<perlipc> for an example of socketpair use. Perl 5.8 and later will emulate socketpair using IP sockets to localhost if your system implements sockets but not socketpair. Portability issues: L<perlport/socketpair>. =item sort SUBNAME LIST X<sort> X<qsort> X<quicksort> X<mergesort> =item sort BLOCK LIST =item sort LIST =for Pod::Functions sort a list of values In list context, this sorts the LIST and returns the sorted list value. In scalar context, the behaviour of C<sort()> is undefined. If SUBNAME or BLOCK is omitted, C<sort>s in standard string comparison order. If SUBNAME is specified, it gives the name of a subroutine that returns an integer less than, equal to, or greater than C<0>, depending on how the elements of the list are to be ordered. (The C<< <=> >> and C<cmp> operators are extremely useful in such routines.) SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use. In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine. If the subroutine's prototype is C<($$)>, the elements to be compared are passed by reference in C<@_>, as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables $a and $b (see example below). Note that in the latter case, it is usually highly counter-productive to declare $a and $b as lexicals. If the subroutine is an XSUB, the elements to be compared are pushed on to the stack, the way arguments are usually passed to XSUBs. $a and $b are not set. The values to be compared are always passed by reference and should not be modified. You also cannot exit out of the sort block or subroutine using any of the loop control operators described in L<perlsyn> or with C<goto>. When C<use locale> (but not C<use locale 'not_characters'>) is in effect, C<sort LIST> sorts LIST according to the current collation locale. See L<perllocale>. sort() returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by sort() (for example, in a C<foreach>, C<map> or C<grep>) actually modifies the element in the original list. This is usually something to be avoided when writing clear code. Perl 5.6 and earlier used a quicksort algorithm to implement sort. That algorithm was not stable, so I<could> go quadratic. (A I<stable> sort preserves the input order of elements that compare equal. Although quicksort's run time is O(NlogN) when averaged over all arrays of length N, the time can be O(N**2), I<quadratic> behavior, for some inputs.) In 5.7, the quicksort implementation was replaced with a stable mergesort algorithm whose worst-case behavior is O(NlogN). But benchmarks indicated that for some inputs, on some platforms, the original quicksort was faster. 5.8 has a sort pragma for limited control of the sort. Its rather blunt control of the underlying algorithm may not persist into future Perls, but the ability to characterize the input or output in implementation independent ways quite probably will. See L<the sort pragma|sort>. Examples: # sort lexically @articles = sort @files; # same thing, but with explicit sort routine @articles = sort {$a cmp $b} @files; # now case-insensitively @articles = sort {fc($a) cmp fc($b)} @files; # same thing in reversed order @articles = sort {$b cmp $a} @files; # sort numerically ascending @articles = sort {$a <=> $b} @files; # sort numerically descending @articles = sort {$b <=> $a} @files; # this sorts the %age hash by value instead of key # using an in-line function @eldest = sort { $age{$b} <=> $age{$a} } keys %age; # sort using explicit subroutine name sub byage { $age{$a} <=> $age{$b}; # presuming numeric } @sortedclass = sort byage @class; sub backwards { $b cmp $a } @harry = qw(dog cat x Cain Abel); @george = qw(gone chased yz Punished Axed); print sort @harry; # prints AbelCaincatdogx print sort backwards @harry; # prints xdogcatCainAbel print sort @george, 'to', @harry; # prints AbelAxedCainPunishedcatchaseddoggonetoxyz # inefficiently sort by descending numeric compare using # the first integer after the first = sign, or the # whole record case-insensitively otherwise my @new = sort { ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] || fc($a) cmp fc($b) } @old; # same thing, but much more efficiently; # we'll build auxiliary indices instead # for speed my @nums = @caps = (); for (@old) { push @nums, ( /=(\d+)/ ? $1 : undef ); push @caps, fc($_); } my @new = @old[ sort { $nums[$b] <=> $nums[$a] || $caps[$a] cmp $caps[$b] } 0..$#old ]; # same thing, but without any temps @new = map { $_->[0] } sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] } map { [$_, /=(\d+)/, fc($_)] } @old; # using a prototype allows you to use any comparison subroutine # as a sort subroutine (including other package's subroutines) package other; sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are not set here package main; @new = sort other::backwards @old; # guarantee stability, regardless of algorithm use sort 'stable'; @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; # force use of mergesort (not portable outside Perl 5.8) use sort '_mergesort'; # note discouraging _ @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; Warning: syntactical care is required when sorting the list returned from a function. If you want to sort the list returned by the function call C<find_records(@key)>, you can use: @contact = sort { $a cmp $b } find_records @key; @contact = sort +find_records(@key); @contact = sort &find_records(@key); @contact = sort(find_records(@key)); If instead you want to sort the array @key with the comparison routine C<find_records()> then you can use: @contact = sort { find_records() } @key; @contact = sort find_records(@key); @contact = sort(find_records @key); @contact = sort(find_records (@key)); If you're using strict, you I<must not> declare $a and $b as lexicals. They are package globals. That means that if you're in the C<main> package and type @articles = sort {$b <=> $a} @files; then C<$a> and C<$b> are C<$main::a> and C<$main::b> (or C<$::a> and C<$::b>), but if you're in the C<FooPack> package, it's the same as typing @articles = sort {$FooPack::b <=> $FooPack::a} @files; The comparison function is required to behave. If it returns inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and sometimes saying the opposite, for example) the results are not well-defined. Because C<< <=> >> returns C<undef> when either operand is C<NaN> (not-a-number), be careful when sorting with a comparison function like C<< $a <=> $b >> any lists that might contain a C<NaN>. The following example takes advantage that C<NaN != NaN> to eliminate any C<NaN>s from the input list. @result = sort { $a <=> $b } grep { $_ == $_ } @input; =item splice ARRAY or EXPR,OFFSET,LENGTH,LIST X<splice> =item splice ARRAY or EXPR,OFFSET,LENGTH =item splice ARRAY or EXPR,OFFSET =item splice ARRAY or EXPR =for Pod::Functions add or remove elements anywhere in an array Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. In list context, returns the elements removed from the array. In scalar context, returns the last element removed, or C<undef> if no elements are removed. The array grows or shrinks as necessary. If OFFSET is negative then it starts that far from the end of the array. If LENGTH is omitted, removes everything from OFFSET onward. If LENGTH is negative, removes the elements from OFFSET onward except for -LENGTH elements at the end of the array. If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array, Perl issues a warning, and splices at the end of the array. The following equivalences hold (assuming C<< $#a >= $i >> ) push(@a,$x,$y) splice(@a,@a,0,$x,$y) pop(@a) splice(@a,-1) shift(@a) splice(@a,0,1) unshift(@a,$x,$y) splice(@a,0,0,$x,$y) $a[$i] = $y splice(@a,$i,1,$y) Example, assuming array lengths are passed before arrays: sub aeq { # compare two list values my(@a) = splice(@_,0,shift); my(@b) = splice(@_,0,shift); return 0 unless @a == @b; # same len? while (@a) { return 0 if pop(@a) ne pop(@b); } return 1; } if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... } Starting with Perl 5.14, C<splice> can take scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<splice> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) =item split /PATTERN/,EXPR,LIMIT X<split> =item split /PATTERN/,EXPR =item split /PATTERN/ =item split =for Pod::Functions split up a string using a regexp delimiter Splits the string EXPR into a list of strings and returns the list in list context, or the size of the list in scalar context. If only PATTERN is given, EXPR defaults to C<$_>. Anything in EXPR that matches PATTERN is taken to be a separator that separates the EXPR into substrings (called "I<fields>") that do B<not> include the separator. Note that a separator may be longer than one character or even have no characters at all (the empty string, which is a zero-width match). The PATTERN need not be constant; an expression may be used to specify a pattern that varies at runtime. If PATTERN matches the empty string, the EXPR is split at the match position (between characters). As an example, the following: print join(':', split('b', 'abc')), "\n"; uses the 'b' in 'abc' as a separator to produce the output 'a:c'. However, this: print join(':', split('', 'abc')), "\n"; uses empty string matches as separators to produce the output 'a:b:c'; thus, the empty string may be used to split EXPR into a list of its component characters. As a special case for C<split>, the empty pattern given in L<match operator|perlop/"m/PATTERN/msixpodualgc"> syntax (C<//>) specifically matches the empty string, which is contrary to its usual interpretation as the last successful match. If PATTERN is C</^/>, then it is treated as if it used the L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it isn't much use otherwise. As another special case, C<split> emulates the default behavior of the command line tool B<awk> when the PATTERN is either omitted or a I<literal string> composed of a single space character (such as S<C<' '>> or S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were C</\s+/>; in particular, this means that I<any> contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing only a single space character to be a separator. If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering the previously described I<awk> emulation. If LIMIT is specified and positive, it represents the maximum number of fields into which the EXPR may be split; in other words, LIMIT is one greater than the maximum number of times EXPR may be split. Thus, the LIMIT value C<1> means that EXPR may be split a maximum of zero times, producing a maximum of one field (namely, the entire value of EXPR). For instance: print join(':', split(//, 'abc', 1)), "\n"; produces the output 'abc', and this: print join(':', split(//, 'abc', 2)), "\n"; produces the output 'a:bc', and each of these: print join(':', split(//, 'abc', 3)), "\n"; print join(':', split(//, 'abc', 4)), "\n"; produces the output 'a:b:c'. If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced. If LIMIT is omitted (or, equivalently, zero), then it is usually treated as if it were instead negative but with the exception that trailing empty fields are stripped (empty leading fields are always preserved); if all fields are empty, then all fields are considered to be trailing (and are thus stripped in this case). Thus, the following: print join(':', split(',', 'a,b,c,,,')), "\n"; produces the output 'a:b:c', but the following: print join(':', split(',', 'a,b,c,,,', -1)), "\n"; produces the output 'a:b:c:::'. In time-critical applications, it is worthwhile to avoid splitting into more fields than necessary. Thus, when assigning to a list, if LIMIT is omitted (or zero), then LIMIT is treated as though it were one larger than the number of variables in the list; for the following, LIMIT is implicitly 4: ($login, $passwd, $remainder) = split(/:/); Note that splitting an EXPR that evaluates to the empty string always produces zero fields, regardless of the LIMIT specified. An empty leading field is produced when there is a positive-width match at the beginning of EXPR. For instance: print join(':', split(/ /, ' abc')), "\n"; produces the output ':abc'. However, a zero-width match at the beginning of EXPR never produces an empty field, so that: print join(':', split(//, ' abc')); produces the output S<' :a:b:c'> (rather than S<': :a:b:c'>). An empty trailing field, on the other hand, is produced when there is a match at the end of EXPR, regardless of the length of the match (of course, unless a non-zero LIMIT is given explicitly, such fields are removed, as in the last example). Thus: print join(':', split(//, ' abc', -1)), "\n"; produces the output S<' :a:b:c:'>. If the PATTERN contains L<capturing groups|perlretut/Grouping things and hierarchical matching>, then for each separator, an additional field is produced for each substring captured by a group (in the order in which the groups are specified, as per L<backreferences|perlretut/Backreferences>); if any group does not match, then it captures the C<undef> value instead of a substring. Also, note that any such additional field is produced whenever there is a separator (that is, whenever a split occurs), and such an additional field does B<not> count towards the LIMIT. Consider the following expressions evaluated in list context (each returned list is provided in the associated comment): split(/-|,/, "1-10,20", 3) # ('1', '10', '20') split(/(-|,)/, "1-10,20", 3) # ('1', '-', '10', ',', '20') split(/-|(,)/, "1-10,20", 3) # ('1', undef, '10', ',', '20') split(/(-)|,/, "1-10,20", 3) # ('1', '-', '10', undef, '20') split(/(-)|(,)/, "1-10,20", 3) # ('1', '-', undef, '10', undef, ',', '20') =item sprintf FORMAT, LIST X<sprintf> =for Pod::Functions formatted print into a string Returns a string formatted by the usual C<printf> conventions of the C library function C<sprintf>. See below for more details and see L<sprintf(3)> or L<printf(3)> on your system for an explanation of the general principles. For example: # Format number with up to 8 leading zeroes $result = sprintf("%08d", $number); # Round number to 3 digits after decimal point $rounded = sprintf("%.3f", $number); Perl does its own C<sprintf> formatting: it emulates the C function sprintf(3), but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable from Perl. Unlike C<printf>, C<sprintf> does not do what you probably mean when you pass it an array as your first argument. The array is given scalar context, and instead of using the 0th element of the array as the format, Perl will use the count of elements in the array as the format, which is almost never useful. Perl's C<sprintf> permits the following universally-known conversions: %% a percent sign %c a character with the given number %s a string %d a signed integer, in decimal %u an unsigned integer, in decimal %o an unsigned integer, in octal %x an unsigned integer, in hexadecimal %e a floating-point number, in scientific notation %f a floating-point number, in fixed decimal notation %g a floating-point number, in %e or %f notation In addition, Perl permits the following widely-supported conversions: %X like %x, but using upper-case letters %E like %e, but using an upper-case "E" %G like %g, but with an upper-case "E" (if applicable) %b an unsigned integer, in binary %B like %b, but using an upper-case "B" with the # flag %p a pointer (outputs the Perl value's address in hexadecimal) %n special: *stores* the number of characters output so far into the next argument in the parameter list Finally, for backward (and we do mean "backward") compatibility, Perl permits these unnecessary but widely-supported conversions: %i a synonym for %d %D a synonym for %ld %U a synonym for %lu %O a synonym for %lo %F a synonym for %f Note that the number of exponent digits in the scientific notation produced by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the exponent less than 100 is system-dependent: it may be three or less (zero-padded as necessary). In other words, 1.23 times ten to the 99th may be either "1.23e99" or "1.23e099". Between the C<%> and the format letter, you may specify several additional attributes controlling the interpretation of the format. In order, these are: =over 4 =item format parameter index An explicit format parameter index, such as C<2$>. By default sprintf will format the next unused argument in the list, but this allows you to take the arguments out of order: printf '%2$d %1$d', 12, 34; # prints "34 12" printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1" =item flags one or more of: space prefix non-negative number with a space + prefix non-negative number with a plus sign - left-justify within the field 0 use zeros, not spaces, to right-justify # ensure the leading "0" for any octal, prefix non-zero hexadecimal with "0x" or "0X", prefix non-zero binary with "0b" or "0B" For example: printf '<% d>', 12; # prints "< 12>" printf '<%+d>', 12; # prints "<+12>" printf '<%6s>', 12; # prints "< 12>" printf '<%-6s>', 12; # prints "<12 >" printf '<%06s>', 12; # prints "<000012>" printf '<%#o>', 12; # prints "<014>" printf '<%#x>', 12; # prints "<0xc>" printf '<%#X>', 12; # prints "<0XC>" printf '<%#b>', 12; # prints "<0b1100>" printf '<%#B>', 12; # prints "<0B1100>" When a space and a plus sign are given as the flags at once, a plus sign is used to prefix a positive number. printf '<%+ d>', 12; # prints "<+12>" printf '<% +d>', 12; # prints "<+12>" When the # flag and a precision are given in the %o conversion, the precision is incremented if it's necessary for the leading "0". printf '<%#.5o>', 012; # prints "<00012>" printf '<%#.5o>', 012345; # prints "<012345>" printf '<%#.0o>', 0; # prints "<0>" =item vector flag This flag tells Perl to interpret the supplied string as a vector of integers, one for each character in the string. Perl applies the format to each integer in turn, then joins the resulting strings with a separator (a dot C<.> by default). This can be useful for displaying ordinal values of characters in arbitrary strings: printf "%vd", "AB\x{100}"; # prints "65.66.256" printf "version is v%vd\n", $^V; # Perl's version Put an asterisk C<*> before the C<v> to override the string to use to separate the numbers: printf "address is %*vX\n", ":", $addr; # IPv6 address printf "bits are %0*v8b\n", " ", $bits; # random bitstring You can also explicitly specify the argument number to use for the join string using something like C<*2$v>; for example: printf '%*4$vX %*4$vX %*4$vX', @addr[1..3], ":"; # 3 IPv6 addresses =item (minimum) width Arguments are usually formatted to be only as wide as required to display the given value. You can override the width by putting a number here, or get the width from the next argument (with C<*>) or from a specified argument (e.g., with C<*2$>): printf "<%s>", "a"; # prints "<a>" printf "<%6s>", "a"; # prints "< a>" printf "<%*s>", 6, "a"; # prints "< a>" printf "<%*2$s>", "a", 6; # prints "< a>" printf "<%2s>", "long"; # prints "<long>" (does not truncate) If a field width obtained through C<*> is negative, it has the same effect as the C<-> flag: left-justification. =item precision, or maximum width X<precision> You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a C<.> followed by a number. For floating-point formats except C<g> and C<G>, this specifies how many places right of the decimal point to show (the default being 6). For example: # these examples are subject to system-specific variation printf '<%f>', 1; # prints "<1.000000>" printf '<%.1f>', 1; # prints "<1.0>" printf '<%.0f>', 1; # prints "<1>" printf '<%e>', 10; # prints "<1.000000e+01>" printf '<%.1e>', 10; # prints "<1.0e+01>" For "g" and "G", this specifies the maximum number of digits to show, including those prior to the decimal point and those after it; for example: # These examples are subject to system-specific variation. printf '<%g>', 1; # prints "<1>" printf '<%.10g>', 1; # prints "<1>" printf '<%g>', 100; # prints "<100>" printf '<%.1g>', 100; # prints "<1e+02>" printf '<%.2g>', 100.01; # prints "<1e+02>" printf '<%.5g>', 100.01; # prints "<100.01>" printf '<%.4g>', 100.01; # prints "<100>" For integer conversions, specifying a precision implies that the output of the number itself should be zero-padded to this width, where the 0 flag is ignored: printf '<%.6d>', 1; # prints "<000001>" printf '<%+.6d>', 1; # prints "<+000001>" printf '<%-10.6d>', 1; # prints "<000001 >" printf '<%10.6d>', 1; # prints "< 000001>" printf '<%010.6d>', 1; # prints "< 000001>" printf '<%+10.6d>', 1; # prints "< +000001>" printf '<%.6x>', 1; # prints "<000001>" printf '<%#.6x>', 1; # prints "<0x000001>" printf '<%-10.6x>', 1; # prints "<000001 >" printf '<%10.6x>', 1; # prints "< 000001>" printf '<%010.6x>', 1; # prints "< 000001>" printf '<%#10.6x>', 1; # prints "< 0x000001>" For string conversions, specifying a precision truncates the string to fit the specified width: printf '<%.5s>', "truncated"; # prints "<trunc>" printf '<%10.5s>', "truncated"; # prints "< trunc>" You can also get the precision from the next argument using C<.*>: printf '<%.6x>', 1; # prints "<000001>" printf '<%.*x>', 6, 1; # prints "<000001>" If a precision obtained through C<*> is negative, it counts as having no precision at all. printf '<%.*s>', 7, "string"; # prints "<string>" printf '<%.*s>', 3, "string"; # prints "<str>" printf '<%.*s>', 0, "string"; # prints "<>" printf '<%.*s>', -1, "string"; # prints "<string>" printf '<%.*d>', 1, 0; # prints "<0>" printf '<%.*d>', 0, 0; # prints "<>" printf '<%.*d>', -1, 0; # prints "<0>" You cannot currently get the precision from a specified number, but it is intended that this will be possible in the future, for example using C<.*2$>: printf "<%.*2$x>", 1, 6; # INVALID, but in future will print "<000001>" =item size For numeric conversions, you can specify the size to interpret the number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer conversions (C<d u o x X b i D U O>), numbers are usually assumed to be whatever the default integer size is on your platform (usually 32 or 64 bits), but you can override this to use instead one of the standard C types, as supported by the compiler used to build Perl: hh interpret integer as C type "char" or "unsigned char" on Perl 5.14 or later h interpret integer as C type "short" or "unsigned short" j interpret integer as C type "intmax_t" on Perl 5.14 or later, and only with a C99 compiler (unportable) l interpret integer as C type "long" or "unsigned long" q, L, or ll interpret integer as C type "long long", "unsigned long long", or "quad" (typically 64-bit integers) t interpret integer as C type "ptrdiff_t" on Perl 5.14 or later z interpret integer as C type "size_t" on Perl 5.14 or later As of 5.14, none of these raises an exception if they are not supported on your platform. However, if warnings are enabled, a warning of the C<printf> warning class is issued on an unsupported conversion flag. Should you instead prefer an exception, do this: use warnings FATAL => "printf"; If you would like to know about a version dependency before you start running the program, put something like this at its top: use 5.014; # for hh/j/t/z/ printf modifiers You can find out whether your Perl supports quads via L<Config>: use Config; if ($Config{use64bitint} eq "define" || $Config{longsize} >= 8) { print "Nice quads!\n"; } For floating-point conversions (C<e f g E F G>), numbers are usually assumed to be the default floating-point size on your platform (double or long double), but you can force "long double" with C<q>, C<L>, or C<ll> if your platform supports them. You can find out whether your Perl supports long doubles via L<Config>: use Config; print "long doubles\n" if $Config{d_longdbl} eq "define"; You can find out whether Perl considers "long double" to be the default floating-point size to use on your platform via L<Config>: use Config; if ($Config{uselongdouble} eq "define") { print "long doubles by default\n"; } It can also be that long doubles and doubles are the same thing: use Config; ($Config{doublesize} == $Config{longdblsize}) && print "doubles are long doubles\n"; The size specifier C<V> has no effect for Perl code, but is supported for compatibility with XS code. It means "use the standard size for a Perl integer or floating-point number", which is the default. =item order of arguments Normally, sprintf() takes the next unused argument as the value to format for each format specification. If the format specification uses C<*> to require additional arguments, these are consumed from the argument list in the order they appear in the format specification I<before> the value to format. Where an argument is specified by an explicit index, this does not affect the normal order for the arguments, even when the explicitly specified index would have been the next argument. So: printf "<%*.*s>", $a, $b, $c; uses C<$a> for the width, C<$b> for the precision, and C<$c> as the value to format; while: printf "<%*1$.*s>", $a, $b; would use C<$a> for the width and precision, and C<$b> as the value to format. Here are some more examples; be aware that when using an explicit index, the C<$> may need escaping: printf "%2\$d %d\n", 12, 34; # will print "34 12\n" printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n" printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n" =back If C<use locale> (including C<use locale 'not_characters'>) is in effect and POSIX::setlocale() has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC locale. See L<perllocale> and L<POSIX>. =item sqrt EXPR X<sqrt> X<root> X<square root> =item sqrt =for Pod::Functions square root function Return the positive square root of EXPR. If EXPR is omitted, uses C<$_>. Works only for non-negative operands unless you've loaded the C<Math::Complex> module. use Math::Complex; print sqrt(-4); # prints 2i =item srand EXPR X<srand> X<seed> X<randseed> =item srand =for Pod::Functions seed the random number generator Sets and returns the random number seed for the C<rand> operator. The point of the function is to "seed" the C<rand> function so that C<rand> can produce a different sequence each time you run your program. When called with a parameter, C<srand> uses that for the seed; otherwise it (semi-)randomly chooses a seed. In either case, starting with Perl 5.14, it returns the seed. To signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so srand returns the seed If C<srand()> is not called explicitly, it is called implicitly without a parameter at the first use of the C<rand> operator. However, this was not true of versions of Perl before 5.004, so if your script will run under older Perl versions, it should call C<srand>; otherwise most programs won't call C<srand()> at all. But there are a few situations in recent Perls where programs are likely to want to call C<srand>. One is for generating predictable results generally for testing or debugging. There, you use C<srand($seed)>, with the same C<$seed> each time. Another case is that you may want to call C<srand()> after a C<fork()> to avoid child processes sharing the same seed value as the parent (and consequently each other). Do B<not> call C<srand()> (i.e., without an argument) more than once per process. The internal state of the random number generator should contain more entropy than can be provided by any seed, so calling C<srand()> again actually I<loses> randomness. Most implementations of C<srand> take an integer and will silently truncate decimal numbers. This means C<srand(42)> will usually produce the same results as C<srand(42.1)>. To be safe, always pass C<srand> an integer. In versions of Perl prior to 5.004 the default seed was just the current C<time>. This isn't a particularly good seed, so many old programs supply their own seed value (often C<time ^ $$> or C<time ^ ($$ + ($$ << 15))>), but that isn't necessary any more. Frequently called programs (like CGI scripts) that simply use time ^ $$ for a seed can fall prey to the mathematical property that a^b == (a+1)^(b+1) one-third of the time. So don't do that. A typical use of the returned seed is for a test program which has too many combinations to test comprehensively in the time available to it each run. It can test a random subset each time, and should there be a failure, log the seed used for that run so that it can later be used to reproduce the same results. B<C<rand()> is not cryptographically secure. You should not rely on it in security-sensitive situations.> As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, and L<Math::TrulyRandom>. =item stat FILEHANDLE X<stat> X<file, status> X<ctime> =item stat EXPR =item stat DIRHANDLE =item stat =for Pod::Functions get a file's status information Returns a 13-element list giving the status info for a file, either the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is omitted, it stats C<$_> (not C<_>!). Returns the empty list if C<stat> fails. 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: 0 dev device number of filesystem 1 ino inode number 2 mode file mode (type and permissions) 3 nlink number of (hard) links to the file 4 uid numeric user ID of file's owner 5 gid numeric group ID of file's owner 6 rdev the device identifier (special files only) 7 size total size of file, in bytes 8 atime last access time in seconds since the epoch 9 mtime last modify time in seconds since the epoch 10 ctime inode change time in seconds since the epoch (*) 11 blksize preferred block size for file system I/O 12 blocks actual number of blocks allocated (The epoch was at 00:00 January 1, 1970 GMT.) (*) Not all fields are supported on all filesystem types. Notably, the ctime field is non-portable. In particular, you cannot expect it to be a "creation time"; see L<perlport/"Files and Filesystems"> for details. If C<stat> is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last C<stat>, C<lstat>, or filetest are returned. Example: if (-x $file && (($d) = stat(_)) && $d < 0) { print "$file is executable NFS file\n"; } (This works on machines only for which the device number is negative under NFS.) Because the mode contains both the file type and its permissions, you should mask off the file type portion and (s)printf using a C<"%o"> if you want to see the real permissions. $mode = (stat($filename))[2]; printf "Permissions are %04o\n", $mode & 07777; In scalar context, C<stat> returns a boolean value indicating success or failure, and, if successful, sets the information associated with the special filehandle C<_>. The L<File::stat> module provides a convenient, by-name access mechanism: use File::stat; $sb = stat($filename); printf "File is %s, size is %s, perm %04o, mtime %s\n", $filename, $sb->size, $sb->mode & 07777, scalar localtime $sb->mtime; You can import symbolic mode constants (C<S_IF*>) and functions (C<S_IS*>) from the Fcntl module: use Fcntl ':mode'; $mode = (stat($filename))[2]; $user_rwx = ($mode & S_IRWXU) >> 6; $group_read = ($mode & S_IRGRP) >> 3; $other_execute = $mode & S_IXOTH; printf "Permissions are %04o\n", S_IMODE($mode), "\n"; $is_setuid = $mode & S_ISUID; $is_directory = S_ISDIR($mode); You could write the last two using the C<-u> and C<-d> operators. Commonly available C<S_IF*> constants are: # Permissions: read, write, execute, for user, group, others. S_IRWXU S_IRUSR S_IWUSR S_IXUSR S_IRWXG S_IRGRP S_IWGRP S_IXGRP S_IRWXO S_IROTH S_IWOTH S_IXOTH # Setuid/Setgid/Stickiness/SaveText. # Note that the exact meaning of these is system-dependent. S_ISUID S_ISGID S_ISVTX S_ISTXT # File types. Not all are necessarily available on # your system. S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR S_IFIFO S_IFSOCK S_IFWHT S_ENFMT # The following are compatibility aliases for S_IRUSR, # S_IWUSR, and S_IXUSR. S_IREAD S_IWRITE S_IEXEC and the C<S_IF*> functions are S_IMODE($mode) the part of $mode containing the permission bits and the setuid/setgid/sticky bits S_IFMT($mode) the part of $mode containing the file type which can be bit-anded with (for example) S_IFREG or with the following functions # The operators -f, -d, -l, -b, -c, -p, and -S. S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) # No direct -X operator counterpart, but for the first one # the -g operator is often equivalent. The ENFMT stands for # record flocking enforcement, a platform-dependent feature. S_ISENFMT($mode) S_ISWHT($mode) See your native chmod(2) and stat(2) documentation for more details about the C<S_*> constants. To get status info for a symbolic link instead of the target file behind the link, use the C<lstat> function. Portability issues: L<perlport/stat>. =item state EXPR X<state> =item state TYPE EXPR =item state EXPR : ATTRS =item state TYPE EXPR : ATTRS =for Pod::Functions +state declare and assign a persistent lexical variable C<state> declares a lexically scoped variable, just like C<my>. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered. See L<perlsub/"Persistent Private Variables"> for details. C<state> variables are enabled only when the C<use feature "state"> pragma is in effect, unless the keyword is written as C<CORE::state>. See also L<feature>. =item study SCALAR X<study> =item study =for Pod::Functions optimize input data for repeated searches Takes extra time to study SCALAR (C<$_> if unspecified) in anticipation of doing many pattern matches on the string before it is next modified. This may or may not save time, depending on the nature and number of patterns you are searching and the distribution of character frequencies in the string to be searched; you probably want to compare run times with and without it to see which is faster. Those loops that scan for many short constant strings (including the constant parts of more complex patterns) will benefit most. (The way C<study> works is this: a linked list of every character in the string to be searched is made, so we know, for example, where all the C<'k'> characters are. From each search string, the rarest character is selected, based on some static frequency tables constructed from some C programs and English text. Only those places that contain this "rarest" character are examined.) For example, here is a loop that inserts index producing entries before any line containing a certain pattern: while (<>) { study; print ".IX foo\n" if /\bfoo\b/; print ".IX bar\n" if /\bbar\b/; print ".IX blurfl\n" if /\bblurfl\b/; # ... print; } In searching for C</\bfoo\b/>, only locations in C<$_> that contain C<f> will be looked at, because C<f> is rarer than C<o>. In general, this is a big win except in pathological cases. The only question is whether it saves you more time than it took to build the linked list in the first place. Note that if you have to look for strings that you don't know till runtime, you can build an entire loop as a string and C<eval> that to avoid recompiling all your patterns all the time. Together with undefining C<$/> to input entire files as one record, this can be quite fast, often faster than specialized programs like fgrep(1). The following scans a list of files (C<@files>) for a list of words (C<@words>), and prints out the names of those files that contain a match: $search = 'while (<>) { study;'; foreach $word (@words) { $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n"; } $search .= "}"; @ARGV = @files; undef $/; eval $search; # this screams $/ = "\n"; # put back to normal input delimiter foreach $file (sort keys(%seen)) { print $file, "\n"; } =item sub NAME BLOCK X<sub> =item sub NAME (PROTO) BLOCK =item sub NAME : ATTRS BLOCK =item sub NAME (PROTO) : ATTRS BLOCK =for Pod::Functions declare a subroutine, possibly anonymously This is subroutine definition, not a real function I<per se>. Without a BLOCK it's just a forward declaration. Without a NAME, it's an anonymous function declaration, so does return a value: the CODE ref of the closure just created. See L<perlsub> and L<perlref> for details about subroutines and references; see L<attributes> and L<Attribute::Handlers> for more information about attributes. =item __SUB__ X<__SUB__> =for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine A special token that returns the a reference to the current subroutine, or C<undef> outside of a subroutine. This token is only available under C<use v5.16> or the "current_sub" feature. See L<feature>. =item substr EXPR,OFFSET,LENGTH,REPLACEMENT X<substr> X<substring> X<mid> X<left> X<right> =item substr EXPR,OFFSET,LENGTH =item substr EXPR,OFFSET =for Pod::Functions get or alter a portion of a string Extracts a substring out of EXPR and returns it. First character is at offset zero. If OFFSET is negative, starts that far back from the end of the string. If LENGTH is omitted, returns everything through the end of the string. If LENGTH is negative, leaves that many characters off the end of the string. my $s = "The black cat climbed the green tree"; my $color = substr $s, 4, 5; # black my $middle = substr $s, 4, -11; # black cat climbed the my $end = substr $s, 14; # climbed the green tree my $tail = substr $s, -4; # tree my $z = substr $s, -4, 2; # tr You can use the substr() function as an lvalue, in which case EXPR must itself be an lvalue. If you assign something shorter than LENGTH, the string will shrink, and if you assign something longer than LENGTH, the string will grow to accommodate it. To keep the string the same length, you may need to pad or chop your value using C<sprintf>. If OFFSET and LENGTH specify a substring that is partly outside the string, only the part within the string is returned. If the substring is beyond either end of the string, substr() returns the undefined value and produces a warning. When used as an lvalue, specifying a substring that is entirely outside the string raises an exception. Here's an example showing the behavior for boundary cases: my $name = 'fred'; substr($name, 4) = 'dy'; # $name is now 'freddy' my $null = substr $name, 6, 2; # returns "" (no warning) my $oops = substr $name, 7; # returns undef, with warning substr($name, 7) = 'gap'; # raises an exception An alternative to using substr() as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with splice(). my $s = "The black cat climbed the green tree"; my $z = substr $s, 14, 7, "jumped from"; # climbed # $s is now "The black cat jumped from the green tree" Note that the lvalue returned by the three-argument version of substr() acts as a 'magic bullet'; each time it is assigned to, it remembers which part of the original string is being modified; for example: $x = '1234'; for (substr($x,1,2)) { $_ = 'a'; print $x,"\n"; # prints 1a4 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 $x = '56789'; $_ = 'pq'; print $x,"\n"; # prints 5pq9 } With negative offsets, it remembers its position from the end of the string when the target string is modified: $x = '1234'; for (substr($x, -3, 2)) { $_ = 'a'; print $x,"\n"; # prints 1a4, as above $x = 'abcdefg'; print $_,"\n"; # prints f } Prior to Perl version 5.10, the result of using an lvalue multiple times was unspecified. Prior to 5.16, the result with negative offsets was unspecified. =item symlink OLDFILE,NEWFILE X<symlink> X<link> X<symbolic link> X<link, symbolic> =for Pod::Functions create a symbolic link to a file Creates a new filename symbolically linked to the old filename. Returns C<1> for success, C<0> otherwise. On systems that don't support symbolic links, raises an exception. To check for that, use eval: $symlink_exists = eval { symlink("",""); 1 }; Portability issues: L<perlport/symlink>. =item syscall NUMBER, LIST X<syscall> X<system call> =for Pod::Functions execute an arbitrary system call Calls the system call specified as the first element of the list, passing the remaining elements as arguments to the system call. If unimplemented, raises an exception. The arguments are interpreted as follows: if a given argument is numeric, the argument is passed as an int. If not, the pointer to the string value is passed. You are responsible to make sure a string is pre-extended long enough to receive any result that might be written into a string. You can't use a string literal (or other read-only string) as an argument to C<syscall> because Perl has to assume that any string pointer might be written through. If your integer arguments are not literals and have never been interpreted in a numeric context, you may need to add C<0> to them to force them to look like numbers. This emulates the C<syswrite> function (or vice versa): require 'syscall.ph'; # may need to run h2ph $s = "hi there\n"; syscall(&SYS_write, fileno(STDOUT), $s, length $s); Note that Perl supports passing of up to only 14 arguments to your syscall, which in practice should (usually) suffice. Syscall returns whatever value returned by the system call it calls. If the system call fails, C<syscall> returns C<-1> and sets C<$!> (errno). Note that some system calls I<can> legitimately return C<-1>. The proper way to handle such calls is to assign C<$!=0> before the call, then check the value of C<$!> if C<syscall> returns C<-1>. There's a problem with C<syscall(&SYS_pipe)>: it returns the file number of the read end of the pipe it creates, but there is no way to retrieve the file number of the other end. You can avoid this problem by using C<pipe> instead. Portability issues: L<perlport/syscall>. =item sysopen FILEHANDLE,FILENAME,MODE X<sysopen> =item sysopen FILEHANDLE,FILENAME,MODE,PERMS =for Pod::Functions +5.002 open a file, pipe, or descriptor Opens the file whose filename is given by FILENAME, and associates it with FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real filehandle wanted; an undefined scalar will be suitably autovivified. This function calls the underlying operating system's I<open>(2) function 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 standard module C<Fcntl>. See the documentation of your operating system's I<open>(2) syscall to see which values and flag bits are available. You may combine several flags using the C<|>-operator. Some of the most common values are C<O_RDONLY> for opening the file in read-only mode, C<O_WRONLY> for opening the file in write-only mode, and C<O_RDWR> for opening the file in read-write mode. X<O_RDONLY> X<O_RDWR> X<O_WRONLY> For historical reasons, some values work on almost every system supported by Perl: 0 means read-only, 1 means write-only, and 2 means read/write. We know that these values do I<not> work under OS/390 & VM/ESA Unix and on the Macintosh; you probably don't want to use them in new code. If the file named by FILENAME does not exist and the C<open> call creates it (typically because MODE includes the C<O_CREAT> flag), then the value of PERMS specifies the permissions of the newly created file. If you omit the PERMS argument to C<sysopen>, Perl uses the octal value C<0666>. These permission values need to be in octal, and are modified by your process's current C<umask>. X<O_CREAT> In many systems the C<O_EXCL> flag is available for opening files in exclusive mode. This is B<not> locking: exclusiveness means here that if the file already exists, sysopen() fails. C<O_EXCL> may not work on network filesystems, and has no effect unless the C<O_CREAT> flag is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from being opened if it is a symbolic link. It does not protect against symbolic links in the file's path. X<O_EXCL> Sometimes you may want to truncate an already-existing file. This can be done using the C<O_TRUNC> flag. The behavior of C<O_TRUNC> with C<O_RDONLY> is undefined. X<O_TRUNC> You should seldom if ever use C<0644> as argument to C<sysopen>, because that takes away the user's option to have a more permissive umask. Better to omit it. See the perlfunc(1) entry on C<umask> for more on this. Note that C<sysopen> depends on the fdopen() C library function. On many Unix systems, fdopen() is known to fail when file descriptors exceed a certain value, typically 255. If you need more file descriptors than that, consider rebuilding Perl to use the C<sfio> library, or perhaps using the POSIX::open() function. See L<perlopentut> for a kinder, gentler explanation of opening files. Portability issues: L<perlport/sysopen>. =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET X<sysread> =item sysread FILEHANDLE,SCALAR,LENGTH =for Pod::Functions fixed-length unbuffered input from a filehandle Attempts to read LENGTH bytes of data into variable SCALAR from the specified FILEHANDLE, using the read(2). It bypasses buffered IO, so mixing this with other kinds of reads, C<print>, C<write>, C<seek>, C<tell>, or C<eof> can cause confusion because the perlio or stdio layers usually buffers data. Returns the number of bytes actually read, C<0> at end of file, or undef if there was an error (in the latter case C<$!> is also set). SCALAR will be grown or shrunk so that the last byte actually read is the last byte of the scalar after the read. An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with C<"\0"> bytes before the result of the read is appended. There is no syseof() function, which is ok, since eof() doesn't work well on device files (like ttys) anyway. Use sysread() and check for a return value for 0 to decide whether you're done. Note that if the filehandle has been marked as C<:utf8> Unicode characters are read instead of bytes (the LENGTH, OFFSET, and the return value of sysread() are in Unicode characters). The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. See L</binmode>, L</open>, and the C<open> pragma, L<open>. =item sysseek FILEHANDLE,POSITION,WHENCE X<sysseek> X<lseek> =for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite Sets FILEHANDLE's system position in bytes using lseek(2). FILEHANDLE may be an expression whose value gives the name of the filehandle. The values for WHENCE are C<0> to set the new position to POSITION; C<1> to set the it to the current position plus POSITION; and C<2> to set it to EOF plus POSITION, typically negative. Note the I<in bytes>: even if the filehandle has been set to operate on characters (for example by using the C<:encoding(utf8)> I/O layer), tell() will return byte offsets, not character offsets (because implementing that would render sysseek() unacceptably slow). sysseek() bypasses normal buffered IO, so mixing it with reads other than C<sysread> (for example C<< <> >> or read()) C<print>, C<write>, C<seek>, C<tell>, or C<eof> may cause confusion. For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end of the file) from the Fcntl module. Use of the constants is also more portable than relying on 0, 1, and 2. For example to define a "systell" function: use Fcntl 'SEEK_CUR'; sub systell { sysseek($_[0], 0, SEEK_CUR) } Returns the new position, or the undefined value on failure. A position of zero is returned as the string C<"0 but true">; thus C<sysseek> returns true on success and false on failure, yet you can still easily determine the new position. =item system LIST X<system> X<shell> =item system PROGRAM LIST =for Pod::Functions run a separate program Does exactly the same thing as C<exec LIST>, except that a fork is done first and the parent process waits for the child process to exit. Note that argument processing varies depending on the number of arguments. If there is more than one argument in LIST, or if LIST is an array with more than one value, starts the program given by the first element of the list with arguments given by the rest of the list. If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is C</bin/sh -c> on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to C<execvp>, which is more efficient. Beginning with v5.6.0, Perl will attempt to flush all files opened for output before any operation that may do a fork, but this may not be supported on some platforms (see L<perlport>). To be safe, you may need to set C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of C<IO::Handle> on any open handles. The return value is the exit status of the program as returned by the C<wait> call. To get the actual exit value, shift right by eight (see below). See also L</exec>. This is I<not> what you want to use to capture the output from a command; for that you should use merely backticks or C<qx//>, as described in L<perlop/"`STRING`">. Return value of -1 indicates a failure to start the program or an error of the wait(2) system call (inspect $! for the reason). If you'd like to make C<system> (and many other bits of Perl) die on error, have a look at the L<autodie> pragma. Like C<exec>, C<system> allows you to lie to a program about its name if you use the C<system PROGRAM LIST> syntax. Again, see L</exec>. Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of C<system>, if you expect your program to terminate on receipt of these signals you will need to arrange to do so yourself based on the return value. @args = ("command", "arg1", "arg2"); system(@args) == 0 or die "system @args failed: $?" If you'd like to manually inspect C<system>'s failure, you can check all possible failure modes by inspecting C<$?> like this: if ($? == -1) { print "failed to execute: $!\n"; } elsif ($? & 127) { printf "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n", $? >> 8; } Alternatively, you may inspect the value of C<${^CHILD_ERROR_NATIVE}> with the C<W*()> calls from the POSIX module. When C<system>'s arguments are executed indirectly by the shell, results and return codes are subject to its quirks. See L<perlop/"`STRING`"> and L</exec> for details. Since C<system> does a C<fork> and C<wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for details. Portability issues: L<perlport/system>. =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET X<syswrite> =item syswrite FILEHANDLE,SCALAR,LENGTH =item syswrite FILEHANDLE,SCALAR =for Pod::Functions fixed-length unbuffered output to a filehandle Attempts to write LENGTH bytes of data from variable SCALAR to the specified FILEHANDLE, using write(2). If LENGTH is not specified, writes whole SCALAR. It bypasses buffered IO, so mixing this with reads (other than C<sysread())>, C<print>, C<write>, C<seek>, C<tell>, or C<eof> may cause confusion because the perlio and stdio layers usually buffer data. Returns the number of bytes actually written, or C<undef> if there was an error (in this case the errno variable C<$!> is also set). If the LENGTH is greater than the data available in the SCALAR after the OFFSET, only as much data as is available will be written. An OFFSET may be specified to write the data from some part of the string other than the beginning. A negative OFFSET specifies writing that many characters counting backwards from the end of the string. If SCALAR is of length zero, you can only use an OFFSET of 0. B<WARNING>: If the filehandle is marked C<:utf8>, Unicode characters encoded in UTF-8 are written instead of bytes, and the LENGTH, OFFSET, and return value of syswrite() are in (UTF8-encoded Unicode) characters. The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. Alternately, if the handle is not marked with an encoding but you attempt to write characters with code points over 255, raises an exception. See L</binmode>, L</open>, and the C<open> pragma, L<open>. =item tell FILEHANDLE X<tell> =item tell =for Pod::Functions get current seekpointer on a filehandle Returns the current position I<in bytes> for FILEHANDLE, or -1 on error. FILEHANDLE may be an expression whose value gives the name of the actual filehandle. If FILEHANDLE is omitted, assumes the file last read. Note the I<in bytes>: even if the filehandle has been set to operate on characters (for example by using the C<:encoding(utf8)> open layer), tell() will return byte offsets, not character offsets (because that would render seek() and tell() rather slow). The return value of tell() for the standard streams like the STDIN depends on the operating system: it may return -1 or something else. tell() on pipes, fifos, and sockets usually returns -1. There is no C<systell> function. Use C<sysseek(FH, 0, 1)> for that. Do not use tell() (or other buffered I/O operations) on a filehandle that has been manipulated by sysread(), syswrite(), or sysseek(). Those functions ignore the buffering, while tell() does not. =item telldir DIRHANDLE X<telldir> =for Pod::Functions get current seekpointer on a directory handle Returns the current position of the C<readdir> routines on DIRHANDLE. Value may be given to C<seekdir> to access a particular location in a directory. C<telldir> has the same caveats about possible directory compaction as the corresponding system library routine. =item tie VARIABLE,CLASSNAME,LIST X<tie> =for Pod::Functions +5.002 bind a variable to an object class This function binds a variable to a package class that will provide the implementation for the variable. VARIABLE is the name of the variable to be enchanted. CLASSNAME is the name of a class implementing objects of correct type. Any additional arguments are passed to the C<new> method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>, or C<TIEHASH>). Typically these are arguments such as might be passed to the C<dbm_open()> function of C. The object returned by the C<new> method is also returned by the C<tie> function, which would be useful if you want to access other methods in CLASSNAME. Note that functions such as C<keys> and C<values> may return huge lists when used on large objects, like DBM files. You may prefer to use the C<each> function to iterate over such. Example: # print out history file offsets use NDBM_File; tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } untie(%HIST); A class implementing a hash should have the following methods: TIEHASH classname, LIST FETCH this, key STORE this, key, value DELETE this, key CLEAR this EXISTS this, key FIRSTKEY this NEXTKEY this, lastkey SCALAR this DESTROY this UNTIE this A class implementing an ordinary array should have the following methods: TIEARRAY classname, LIST FETCH this, key STORE this, key, value FETCHSIZE this STORESIZE this, count CLEAR this PUSH this, LIST POP this SHIFT this UNSHIFT this, LIST SPLICE this, offset, length, LIST EXTEND this, count DESTROY this UNTIE this A class implementing a filehandle should have the following methods: TIEHANDLE classname, LIST READ this, scalar, length, offset READLINE this GETC this WRITE this, scalar, length, offset PRINT this, LIST PRINTF this, format, LIST BINMODE this EOF this FILENO this SEEK this, position, whence TELL this OPEN this, mode, LIST CLOSE this DESTROY this UNTIE this A class implementing a scalar should have the following methods: TIESCALAR classname, LIST FETCH this, STORE this, value DESTROY this UNTIE this Not all methods indicated above need be implemented. See L<perltie>, L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>. Unlike C<dbmopen>, the C<tie> function will not C<use> or C<require> a module for you; you need to do that explicitly yourself. See L<DB_File> or the F<Config> module for interesting C<tie> implementations. For further details see L<perltie>, L<"tied VARIABLE">. =item tied VARIABLE X<tied> =for Pod::Functions get a reference to the object underlying a tied variable Returns a reference to the object underlying VARIABLE (the same value that was originally returned by the C<tie> call that bound the variable to a package.) Returns the undefined value if VARIABLE isn't tied to a package. =item time X<time> X<epoch> =for Pod::Functions return number of seconds since 1970 Returns the number of non-leap seconds since whatever time the system considers to be the epoch, suitable for feeding to C<gmtime> and C<localtime>. On most systems the epoch is 00:00:00 UTC, January 1, 1970; a prominent exception being Mac OS Classic which uses 00:00:00, January 1, 1904 in the current local time zone for its epoch. For measuring time in better granularity than one second, use the L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or, if you have gettimeofday(2), you may be able to use the C<syscall> interface of Perl. See L<perlfaq8> for details. For date and time processing look at the many related modules on CPAN. For a comprehensive date and time representation look at the L<DateTime> module. =item times X<times> =for Pod::Functions return elapsed time for self and child processes Returns a four-element list giving the user and system times in seconds for this process and any exited children of this process. ($user,$system,$cuser,$csystem) = times; In scalar context, C<times> returns C<$user>. Children's times are only included for terminated children. Portability issues: L<perlport/times>. =item tr/// =for Pod::Functions transliterate a string The transliteration operator. Same as C<y///>. See L<perlop/"Quote and Quote-like Operators">. =item truncate FILEHANDLE,LENGTH X<truncate> =item truncate EXPR,LENGTH =for Pod::Functions shorten a file Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified length. Raises an exception if truncate isn't implemented on your system. Returns true if successful, C<undef> on error. The behavior is undefined if LENGTH is greater than the length of the file. The position in the file of FILEHANDLE is left unchanged. You may want to call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the file. Portability issues: L<perlport/truncate>. =item uc EXPR X<uc> X<uppercase> X<toupper> =item uc =for Pod::Functions return upper-case version of a string Returns an uppercased version of EXPR. This is the internal function implementing the C<\U> escape in double-quoted strings. It does not attempt to do titlecase mapping on initial letters. See L</ucfirst> for that. If EXPR is omitted, uses C<$_>. This function behaves the same way under various pragma, such as in a locale, as L</lc> does. =item ucfirst EXPR X<ucfirst> X<uppercase> =item ucfirst =for Pod::Functions return a string with just the next letter in upper case Returns the value of EXPR with the first character in uppercase (titlecase in Unicode). This is the internal function implementing the C<\u> escape in double-quoted strings. If EXPR is omitted, uses C<$_>. This function behaves the same way under various pragma, such as in a locale, as L</lc> does. =item umask EXPR X<umask> =item umask =for Pod::Functions set file creation mode mask Sets the umask for the process to EXPR and returns the previous value. If EXPR is omitted, merely returns the current umask. The Unix permission C<rwxr-x---> is represented as three sets of three bits, or three octal digits: C<0750> (the leading 0 indicates octal and isn't one of the digits). The C<umask> value is such a number representing disabled permissions bits. The permission (or "mode") values you pass C<mkdir> or C<sysopen> are modified by your umask, so even if you tell C<sysopen> to create a file with permissions C<0777>, if your umask is C<0022>, then the file will actually be created with permissions C<0755>. If your C<umask> were C<0027> (group can't write; others can't read, write, or execute), then passing C<sysopen> C<0666> would create a file with mode C<0640> (because C<0666 &~ 027> is C<0640>). Here's some advice: supply a creation mode of C<0666> for regular files (in C<sysopen>) and one of C<0777> for directories (in C<mkdir>) and executable files. This gives users the freedom of choice: if they want protected files, they might choose process umasks of C<022>, C<027>, or even the particularly antisocial mask of C<077>. Programs should rarely if ever make policy decisions better left to the user. The exception to this is when writing files that should be kept private: mail files, web browser cookies, I<.rhosts> files, and so on. If umask(2) is not implemented on your system and you are trying to restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>), raises an exception. If umask(2) is not implemented and you are not trying to restrict access for yourself, returns C<undef>. Remember that a umask is a number, usually given in octal; it is I<not> a string of octal digits. See also L</oct>, if all you have is a string. Portability issues: L<perlport/umask>. =item undef EXPR X<undef> X<undefine> =item undef =for Pod::Functions remove a variable or function definition Undefines the value of EXPR, which must be an lvalue. Use only on a scalar value, an array (using C<@>), a hash (using C<%>), a subroutine (using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}> will probably not do what you expect on most predefined variables or DBM list values, so don't do that; see L</delete>. Always returns the undefined value. You can omit the EXPR, in which case nothing is undefined, but you still get an undefined value that you could, for instance, return from a subroutine, assign to a variable, or pass as a parameter. Examples: undef $foo; undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; undef @ary; undef %hash; undef &mysub; undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; select undef, undef, undef, 0.25; ($a, $b, undef, $c) = &foo; # Ignore third value returned Note that this is a unary operator, not a list operator. =item unlink LIST X<unlink> X<delete> X<remove> X<rm> X<del> =item unlink =for Pod::Functions remove one link to a file Deletes a list of files. On success, it returns the number of files it successfully deleted. On failure, it returns false and sets C<$!> (errno): my $unlinked = unlink 'a', 'b', 'c'; unlink @goners; unlink glob "*.bak"; On error, C<unlink> will not tell you which files it could not remove. If you want to know which files you could not remove, try them one at a time: foreach my $file ( @goners ) { unlink $file or warn "Could not unlink $file: $!"; } Note: C<unlink> will not attempt to delete directories unless you are superuser and the B<-U> flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Finally, using C<unlink> on directories is not supported on many operating systems. Use C<rmdir> instead. If LIST is omitted, C<unlink> uses C<$_>. =item unpack TEMPLATE,EXPR X<unpack> =item unpack TEMPLATE =for Pod::Functions convert binary structure into normal perl variables C<unpack> does the reverse of C<pack>: it takes a string and expands it out into a list of values. (In scalar context, it returns merely the first value produced.) If EXPR is omitted, unpacks the C<$_> string. See L<perlpacktut> for an introduction to this function. The string is broken into chunks described by the TEMPLATE. Each chunk is converted separately to a value. Typically, either the string is a result of C<pack>, or the characters of the string represent a C structure of some kind. The TEMPLATE has the same format as in the C<pack> function. Here's a subroutine that does substring: sub substr { my($what,$where,$howmuch) = @_; unpack("x$where a$howmuch", $what); } and then there's sub ordinal { unpack("W",$_[0]); } # same as ord() In addition to fields allowed in pack(), you may prefix a field with a %<number> to indicate that you want a <number>-bit checksum of the items instead of the items themselves. Default is a 16-bit checksum. Checksum is calculated by summing numeric values of expanded values (for string fields the sum of C<ord($char)> is taken; for bit fields the sum of zeroes and ones). For example, the following computes the same number as the System V sum program: $checksum = do { local $/; # slurp! unpack("%32W*",<>) % 65535; }; The following efficiently counts the number of set bits in a bit vector: $setbits = unpack("%32b*", $selectmask); The C<p> and C<P> formats should be used with care. Since Perl has no way of checking whether the value passed to C<unpack()> corresponds to a valid memory location, passing a pointer value that's not known to be valid is likely to have disastrous consequences. If there are more pack codes or if the repeat count of a field or a group is larger than what the remainder of the input string allows, the result is not well defined: the repeat count may be decreased, or C<unpack()> may produce empty strings or zeros, or it may raise an exception. If the input string is longer than one described by the TEMPLATE, the remainder of that input string is ignored. See L</pack> for more examples and notes. =item unshift ARRAY,LIST X<unshift> =item unshift EXPR,LIST =for Pod::Functions prepend more elements to the beginning of a list Does the opposite of a C<shift>. Or the opposite of a C<push>, depending on how you look at it. Prepends list to the front of the array and returns the new number of elements in the array. unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/; Note the LIST is prepended whole, not one element at a time, so the prepended elements stay in the same order. Use C<reverse> to do the reverse. Starting with Perl 5.14, C<unshift> can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<unshift> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) =item untie VARIABLE X<untie> =for Pod::Functions break a tie binding to a variable Breaks the binding between a variable and a package. (See L<tie|/tie VARIABLE,CLASSNAME,LIST>.) Has no effect if the variable is not tied. =item use Module VERSION LIST X<use> X<module> X<import> =item use Module VERSION =item use Module LIST =item use Module =item use VERSION =for Pod::Functions load in a module at compile time and import its namespace Imports 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 BEGIN { require Module; Module->import( LIST ); } except that Module I<must> be a bareword. The importation can be made conditional; see L<if>. In the peculiar C<use VERSION> form, VERSION may be either a positive decimal fraction such as 5.006, which will be compared to C<$]>, or a v-string of the form v5.6.1, which will be compared to C<$^V> (aka $PERL_VERSION). An exception is raised if VERSION is greater than the version of the current Perl interpreter; Perl will not attempt to parse the rest of the file. Compare with L</require>, which can do a similar check at run time. Symmetrically, C<no VERSION> allows you to specify that you want a version of Perl older than the specified one. Specifying VERSION as a literal of the form v5.6.1 should generally be avoided, because it leads to misleading error messages under earlier versions of Perl (that is, prior to 5.6.0) that do not support this syntax. The equivalent numeric version should be used instead. use v5.6.1; # compile time version check use 5.6.1; # ditto use 5.006_001; # ditto; preferred for backwards compatibility This is often useful if you need to check the current Perl version before C<use>ing library modules that won't work with older versions of Perl. (We try not to do this more than we have to.) C<use VERSION> also enables all features available in the requested version as defined by the C<feature> pragma, disabling any features not in the requested version's feature bundle. See L<feature>. Similarly, if the specified Perl version is greater than or equal to 5.11.0, strictures are enabled lexically as with C<use strict>. Any explicit use of C<use strict> or C<no strict> overrides C<use VERSION>, even if it comes before it. In both cases, the F<feature.pm> and F<strict.pm> files are not actually loaded. The C<BEGIN> forces the C<require> and C<import> to happen at compile time. The C<require> makes sure the module is loaded into memory if it hasn't been yet. The C<import> is not a builtin; it's just an ordinary static method call into the C<Module> package to tell the module to import the list of features back into the current package. The module can implement its C<import> method any way it likes, though most modules just choose to derive their C<import> method via inheritance from the C<Exporter> class that is defined in the C<Exporter> module. See L<Exporter>. If no C<import> method can be found then the call is skipped, even if there is an AUTOLOAD method. If you do not want to call the package's C<import> method (for instance, to stop your namespace from being altered), explicitly supply the empty list: use Module (); That is exactly equivalent to BEGIN { require Module } If the VERSION argument is present between Module and LIST, then the C<use> will call the VERSION method in class Module with the given version as an argument. The default VERSION method, inherited from the UNIVERSAL class, croaks if the given version is larger than the value of the variable C<$Module::VERSION>. Again, there is a distinction between omitting LIST (C<import> called with no arguments) and an explicit empty LIST C<()> (C<import> not called). Note that there is no comma after VERSION! Because this is a wide-open interface, pragmas (compiler directives) are also implemented this way. Currently implemented pragmas are: use constant; use diagnostics; use integer; use sigtrap qw(SEGV BUS); use strict qw(subs vars refs); use subs qw(afunc blurfl); use warnings qw(all); use sort qw(stable _quicksort _mergesort); Some of these pseudo-modules import semantics into the current block scope (like C<strict> or C<integer>, unlike ordinary modules, which import symbols into the current package (which are effective through the end of the file). Because C<use> takes effect at compile time, it doesn't respect the ordinary flow control of the code being compiled. In particular, putting a C<use> inside the false branch of a conditional doesn't prevent it from being processed. If a module or pragma only needs to be loaded conditionally, this can be done using the L<if> pragma: use if $] < 5.008, "utf8"; use if WANT_WARNINGS, warnings => qw(all); There's a corresponding C<no> declaration that unimports meanings imported by C<use>, i.e., it calls C<unimport Module LIST> instead of C<import>. It behaves just as C<import> does with VERSION, an omitted or empty LIST, or no unimport method being found. no integer; no strict 'refs'; no warnings; Care should be taken when using the C<no VERSION> form of C<no>. It is I<only> meant to be used to assert that the running Perl is of a earlier version than its argument and I<not> to undo the feature-enabling side effects of C<use VERSION>. See L<perlmodlib> for a list of standard modules and pragmas. See L<perlrun> for the C<-M> and C<-m> command-line options to Perl that give C<use> functionality from the command-line. =item utime LIST X<utime> =for Pod::Functions set a file's last access and modify times Changes the access and modification times on each file of a list of files. The first two elements of the list must be the NUMERIC access and modification times, in that order. Returns the number of files successfully changed. The inode change time of each file is set to the current time. For example, this code has the same effect as the Unix touch(1) command when the files I<already exist> and belong to the user running the program: #!/usr/bin/perl $atime = $mtime = time; utime $atime, $mtime, @ARGV; Since Perl 5.7.2, if the first two elements of the list are C<undef>, the utime(2) syscall from your C library is called with a null second argument. On most systems, this will set the file's access and modification times to the current time (i.e., equivalent to the example above) and will work even on files you don't own provided you have write permission: for $file (@ARGV) { utime(undef, undef, $file) || warn "couldn't touch $file: $!"; } Under NFS this will use the time of the NFS server, not the time of the local machine. If there is a time synchronization problem, the NFS server and local machine will have different times. The Unix touch(1) command will in fact normally use this form instead of the one shown in the first example. Passing only one of the first two elements as C<undef> is equivalent to passing a 0 and will not have the effect described when both are C<undef>. This also triggers an uninitialized warning. On systems that support futimes(2), you may pass filehandles among the files. On systems that don't support futimes(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames. Portability issues: L<perlport/utime>. =item values HASH X<values> =item values ARRAY =item values EXPR =for Pod::Functions return a list of the values in a hash In list context, returns a list consisting of all the values of the named hash. In Perl 5.12 or later only, will also return a list of the values of an array; prior to that release, attempting to use an array argument will produce a syntax error. In scalar context, returns the number of values. When called on a hash, the values are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be the same order as either the C<keys> or C<each> function would produce on the same (unmodified) hash. Since Perl 5.8.1 the ordering is different even between different runs of Perl for security reasons (see L<perlsec/"Algorithmic Complexity Attacks">). As a side effect, calling values() resets the HASH or ARRAY's internal iterator, see L</each>. (In particular, calling values() in void context resets the iterator with no other overhead. Apart from resetting the iterator, C<values @array> in list context is the same as plain C<@array>. (We recommend that you use void context C<keys @array> for this, but reasoned that taking C<values @array> out would require more documentation than leaving it in.) Note that the values are not copied, which means modifying them will modify the contents of the hash: for (values %hash) { s/foo/bar/g } # modifies %hash values for (@hash{keys %hash}) { s/foo/bar/g } # same Starting with Perl 5.14, C<values> can take a scalar EXPR, which must hold a reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of C<values> is considered highly experimental. The exact behaviour may change in a future version of Perl. for (values $hashref) { ... } for (values $obj->get_arrayref) { ... } To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.012; # so keys/values/each work on arrays use 5.014; # so keys/values/each work on scalars (experimental) See also C<keys>, C<each>, and C<sort>. =item vec EXPR,OFFSET,BITS X<vec> X<bit> X<bit vector> =for Pod::Functions test or set particular bits in a string Treats the string in EXPR as a bit vector made up of elements of width BITS and returns the value of the element specified by OFFSET as an unsigned integer. BITS therefore specifies the number of bits that are reserved for each element in the bit vector. This must be a power of two from 1 to 32 (or 64, if your platform supports that). If BITS is 8, "elements" coincide with bytes of the input string. If BITS is 16 or more, bytes of the input string are grouped into chunks of size BITS/8, and each group is converted to a number as with pack()/unpack() with big-endian formats C<n>/C<N> (and analogously for BITS==64). See L<"pack"> for details. If bits is 4 or less, the string is broken into bytes, then the bits of each byte are broken into 8/BITS groups. Bits of a byte are numbered in a little-endian-ish way, as in C<0x01>, C<0x02>, C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example, breaking the single input byte C<chr(0x36)> into two groups gives a list C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>. C<vec> may also be assigned to, in which case parentheses are needed to give the expression the correct precedence as in vec($image, $max_x * $x + $y, 8) = 3; If the selected element is outside the string, the value 0 is returned. If an element off the end of the string is written to, Perl will first extend the string with sufficiently many zero bytes. It is an error to try to write off the beginning of the string (i.e., negative OFFSET). If the string happens to be encoded as UTF-8 internally (and thus has the UTF8 flag set), this is ignored by C<vec>, and it operates on the internal byte string, not the conceptual character string, even if you only have characters with values less than 256. Strings created with C<vec> can also be manipulated with the logical operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit vector operation is desired when both operands are strings. See L<perlop/"Bitwise String Operators">. The following code will build up an ASCII string saying C<'PerlPerlPerl'>. The comments show the string after each step. Note that this code works in the same way on big-endian or little-endian machines. my $foo = ''; vec($foo, 0, 32) = 0x5065726C; # 'Perl' # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P') vec($foo, 2, 16) = 0x5065; # 'PerlPe' vec($foo, 3, 16) = 0x726C; # 'PerlPerl' vec($foo, 8, 8) = 0x50; # 'PerlPerlP' vec($foo, 9, 8) = 0x65; # 'PerlPerlPe' vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02" vec($foo, 21, 4) = 7; # 'PerlPerlPer' # 'r' is "\x72" vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c" vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c" vec($foo, 94, 1) = 1; # 'PerlPerlPerl' # 'l' is "\x6c" To transform a bit vector into a string or list of 0's and 1's, use these: $bits = unpack("b*", $vector); @bits = split(//, unpack("b*", $vector)); If you know the exact length in bits, it can be used in place of the C<*>. Here is an example to illustrate how the bits actually fall in place: #!/usr/bin/perl -wl print <<'EOT'; 0 1 2 3 unpack("V",$_) 01234567890123456789012345678901 ------------------------------------------------------------------ EOT for $w (0..3) { $width = 2**$w; for ($shift=0; $shift < $width; ++$shift) { for ($off=0; $off < 32/$width; ++$off) { $str = pack("B*", "0"x32); $bits = (1<<$shift); vec($str, $off, $width) = $bits; $res = unpack("b*",$str); $val = unpack("V", $str); write; } } } format STDOUT = vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> $off, $width, $bits, $val, $res . __END__ Regardless of the machine architecture on which it runs, the example above should print the following table: 0 1 2 3 unpack("V",$_) 01234567890123456789012345678901 ------------------------------------------------------------------ vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000 vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000 vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000 vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000 vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000 vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000 vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000 vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000 vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000 vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000 vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000 vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000 vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000 vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000 vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000 vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000 vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000 vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000 vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000 vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000 vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000 vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000 vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000 vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000 vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000 vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000 vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000 vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000 vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000 vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100 vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010 vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001 vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000 vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000 vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000 vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000 vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000 vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000 vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000 vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000 vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000 vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000 vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000 vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000 vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000 vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000 vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000 vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010 vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000 vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000 vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000 vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000 vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000 vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000 vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000 vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000 vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000 vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000 vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000 vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000 vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000 vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000 vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100 vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001 vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000 vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000 vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000 vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000 vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000 vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000 vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000 vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000 vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000 vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000 vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000 vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000 vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000 vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000 vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000 vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100 vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000 vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000 vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000 vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000 vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000 vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000 vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000 vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010 vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000 vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000 vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000 vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000 vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000 vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000 vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000 vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001 vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000 vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000 vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000 vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000 vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000 vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000 vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000 vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000 vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000 vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000 vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000 vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000 vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000 vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000 vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000 vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000 vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000 vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000 vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000 vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000 vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000 vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000 vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000 vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100 vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000 vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000 vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000 vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010 vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000 vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000 vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000 vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001 =item wait X<wait> =for Pod::Functions wait for any child process to die Behaves like wait(2) on your system: it waits for a child process to terminate and returns the pid of the deceased process, or C<-1> if there are no child processes. The status is returned in C<$?> and C<${^CHILD_ERROR_NATIVE}>. Note that a return value of C<-1> could mean that child processes are being automatically reaped, as described in L<perlipc>. If you use wait in your handler for $SIG{CHLD} it may accidentally for the child created by qx() or system(). See L<perlipc> for details. Portability issues: L<perlport/wait>. =item waitpid PID,FLAGS X<waitpid> =for Pod::Functions wait for a particular child process to die Waits for a particular child process to terminate and returns the pid of the deceased process, or C<-1> if there is no such child process. On some systems, a value of 0 indicates that there are processes still running. The status is returned in C<$?> and C<${^CHILD_ERROR_NATIVE}>. If you say use POSIX ":sys_wait_h"; #... do { $kid = waitpid(-1, WNOHANG); } while $kid > 0; then you can do a non-blocking wait for all pending zombie processes. Non-blocking wait is available on machines supporting either the waitpid(2) or wait4(2) syscalls. However, waiting for a particular pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the system call by remembering the status values of processes that have exited but have not been harvested by the Perl script yet.) Note that on some systems, a return value of C<-1> could mean that child processes are being automatically reaped. See L<perlipc> for details, and for other examples. Portability issues: L<perlport/waitpid>. =item wantarray X<wantarray> X<context> =for Pod::Functions get void vs scalar vs list context of current subroutine call Returns true if the context of the currently executing subroutine or C<eval> is looking for a list value. Returns false if the context is looking for a scalar. Returns the undefined value if the context is looking for no value (void context). return unless defined wantarray; # don't bother doing more my @a = complex_calculation(); return wantarray ? @a : "@a"; C<wantarray()>'s result is unspecified in the top level of a file, in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or in a C<DESTROY> method. This function should have been named wantlist() instead. =item warn LIST X<warn> X<warning> X<STDERR> =for Pod::Functions print debugging info Prints the value of LIST to STDERR. If the last element of LIST does not end in a newline, it appends the same file/line number text as C<die> does. If the output is empty and C<$@> already contains a value (typically from a previous eval) that value is used after appending C<"\t...caught"> to C<$@>. This is useful for staying almost, but not entirely similar to C<die>. If C<$@> is empty then the string C<"Warning: Something's wrong"> is used. No message is printed if there is a C<$SIG{__WARN__}> handler installed. It is the handler's responsibility to deal with the message as it sees fit (like, for instance, converting it into a C<die>). Most handlers must therefore arrange to actually display the warnings that they are not prepared to deal with, by calling C<warn> again in the handler. Note that this is quite safe and will not produce an endless loop, since C<__WARN__> hooks are not called from inside one. You will find this behavior is slightly different from that of C<$SIG{__DIE__}> handlers (which don't suppress the error text, but can instead call C<die> again to change it). Using a C<__WARN__> handler provides a powerful way to silence all warnings (even the so-called mandatory ones). An example: # wipe out *all* compile-time warnings BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } } my $foo = 10; my $foo = 20; # no warning about duplicate my $foo, # but hey, you asked for it! # no compile-time or run-time warnings before here $DOWARN = 1; # run-time warnings enabled after here warn "\$foo is alive and $foo!"; # does show up See L<perlvar> for details on setting C<%SIG> entries and for more examples. See the Carp module for other kinds of warnings using its carp() and cluck() functions. =item write FILEHANDLE X<write> =item write EXPR =item write =for Pod::Functions print a picture record Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, using the format associated with that file. By default the format for a file is the one having the same name as the filehandle, but the format for the current output channel (see the C<select> function) may be set explicitly by assigning the name of the format to the C<$~> variable. Top of form processing is handled automatically: if there is insufficient room on the current page for the formatted record, the page is advanced by writing a form feed, a special top-of-page format is used to format the new page header before the record is written. By default, the top-of-page format is the name of the filehandle with "_TOP" appended. This would be a problem with autovivified filehandles, but it may be dynamically set to the format of your choice by assigning the name to the C<$^> variable while that filehandle is selected. The number of lines remaining on the current page is in variable C<$->, which can be set to C<0> to force a new page. If FILEHANDLE is unspecified, output goes to the current default output channel, which starts out as STDOUT but may be changed by the C<select> operator. If the FILEHANDLE is an EXPR, then the expression is evaluated and the resulting string is used to look up the name of the FILEHANDLE at run time. For more on formats, see L<perlform>. Note that write is I<not> the opposite of C<read>. Unfortunately. =item y/// =for Pod::Functions transliterate a string The transliteration operator. Same as C<tr///>. See L<perlop/"Quote and Quote-like Operators">. =back =head2 Non-function Keywords by Cross-reference =head3 perldata =over =item __DATA__ =item __END__ These keywords are documented in L<perldata/"Special Literals">. =back =head3 perlmod =over =item BEGIN =item CHECK =item END =item INIT =item UNITCHECK These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">. =back =head3 perlobj =over =item DESTROY This method keyword is documented in L<perlobj/"Destructors">. =back =head3 perlop =over =item and =item cmp =item eq =item ge =item gt =item if =item le =item lt =item ne =item not =item or =item x =item xor These operators are documented in L<perlop>. =back =head3 perlsub =over =item AUTOLOAD This keyword is documented in L<perlsub/"Autoloading">. =back =head3 perlsyn =over =item else =item elseif =item elsif =item for =item foreach =item unless =item until =item while These flow-control keywords are documented in L<perlsyn/"Compound Statements">. =back =over =item default =item given =item when These flow-control keywords related to the experimental switch feature are documented in L<perlsyn/"Switch Statements"> . =back =cut PK PU�\�ex'U� U� perlvms.podnu �[��� =head1 NAME perlvms - VMS-specific documentation for Perl =head1 DESCRIPTION Gathered below are notes describing details of Perl 5's behavior on VMS. They are a supplement to the regular Perl 5 documentation, so we have focussed on the ways in which Perl 5 functions differently under VMS than it does under Unix, and on the interactions between Perl and the rest of the operating system. We haven't tried to duplicate complete descriptions of Perl features from the main Perl documentation, which can be found in the F<[.pod]> subdirectory of the Perl distribution. We hope these notes will save you from confusion and lost sleep when writing Perl scripts on VMS. If you find we've missed something you think should appear here, please don't hesitate to drop a line to vmsperl@perl.org. =head1 Installation Directions for building and installing Perl 5 can be found in the file F<README.vms> in the main source directory of the Perl distribution.. =head1 Organization of Perl Images =head2 Core Images During the installation process, three Perl images are produced. F<Miniperl.Exe> is an executable image which contains all of the basic functionality of Perl, but cannot take advantage of Perl extensions. It is used to generate several files needed to build the complete Perl and various extensions. Once you've finished installing Perl, you can delete this image. Most of the complete Perl resides in the shareable image F<PerlShr.Exe>, which provides a core to which the Perl executable image and all Perl extensions are linked. You should place this image in F<Sys$Share>, or define the logical name F<PerlShr> to translate to the full file specification of this image. It should be world readable. (Remember that if a user has execute only access to F<PerlShr>, VMS will treat it as if it were a privileged shareable image, and will therefore require all downstream shareable images to be INSTALLed, etc.) Finally, F<Perl.Exe> is an executable image containing the main entry point for Perl, as well as some initialization code. It should be placed in a public directory, and made world executable. In order to run Perl with command line arguments, you should define a foreign command to invoke this image. =head2 Perl Extensions Perl extensions are packages which provide both XS and Perl code to add new functionality to perl. (XS is a meta-language which simplifies writing C code which interacts with Perl, see L<perlxs> for more details.) The Perl code for an extension is treated like any other library module - it's made available in your script through the appropriate C<use> or C<require> statement, and usually defines a Perl package containing the extension. The portion of the extension provided by the XS code may be connected to the rest of Perl in either of two ways. In the B<static> configuration, the object code for the extension is linked directly into F<PerlShr.Exe>, and is initialized whenever Perl is invoked. In the B<dynamic> configuration, the extension's machine code is placed into a separate shareable image, which is mapped by Perl's DynaLoader when the extension is C<use>d or C<require>d in your script. This allows you to maintain the extension as a separate entity, at the cost of keeping track of the additional shareable image. Most extensions can be set up as either static or dynamic. The source code for an extension usually resides in its own directory. At least three files are generally provided: I<Extshortname>F<.xs> (where I<Extshortname> is the portion of the extension's name following the last C<::>), containing the XS code, I<Extshortname>F<.pm>, the Perl library module for the extension, and F<Makefile.PL>, a Perl script which uses the C<MakeMaker> library modules supplied with Perl to generate a F<Descrip.MMS> file for the extension. =head2 Installing static extensions Since static extensions are incorporated directly into F<PerlShr.Exe>, you'll have to rebuild Perl to incorporate a new extension. You should edit the main F<Descrip.MMS> or F<Makefile> you use to build Perl, adding the extension's name to the C<ext> macro, and the extension's object file to the C<extobj> macro. You'll also need to build the extension's object file, either by adding dependencies to the main F<Descrip.MMS>, or using a separate F<Descrip.MMS> for the extension. Then, rebuild F<PerlShr.Exe> to incorporate the new code. Finally, you'll need to copy the extension's Perl library module to the F<[.>I<Extname>F<]> subdirectory under one of the directories in C<@INC>, where I<Extname> is the name of the extension, with all C<::> replaced by C<.> (e.g. the library module for extension Foo::Bar would be copied to a F<[.Foo.Bar]> subdirectory). =head2 Installing dynamic extensions In general, the distributed kit for a Perl extension includes a file named Makefile.PL, which is a Perl program which is used to create a F<Descrip.MMS> file which can be used to build and install the files required by the extension. The kit should be unpacked into a directory tree B<not> under the main Perl source directory, and the procedure for building the extension is simply $ perl Makefile.PL ! Create Descrip.MMS $ mmk ! Build necessary files $ mmk test ! Run test code, if supplied $ mmk install ! Install into public Perl tree I<N.B.> The procedure by which extensions are built and tested creates several levels (at least 4) under the directory in which the extension's source files live. For this reason if you are running a version of VMS prior to V7.1 you shouldn't nest the source directory too deeply in your directory structure lest you exceed RMS' maximum of 8 levels of subdirectory in a filespec. (You can use rooted logical names to get another 8 levels of nesting, if you can't place the files near the top of the physical directory structure.) VMS support for this process in the current release of Perl is sufficient to handle most extensions. However, it does not yet recognize extra libraries required to build shareable images which are part of an extension, so these must be added to the linker options file for the extension by hand. For instance, if the F<PGPLOT> extension to Perl requires the F<PGPLOTSHR.EXE> shareable image in order to properly link the Perl extension, then the line C<PGPLOTSHR/Share> must be added to the linker options file F<PGPLOT.Opt> produced during the build process for the Perl extension. By default, the shareable image for an extension is placed in the F<[.lib.site_perl.auto>I<Arch>.I<Extname>F<]> directory of the installed Perl directory tree (where I<Arch> is F<VMS_VAX> or F<VMS_AXP>, and I<Extname> is the name of the extension, with each C<::> translated to C<.>). (See the MakeMaker documentation for more details on installation options for extensions.) However, it can be manually placed in any of several locations: =over 4 =item * the F<[.Lib.Auto.>I<Arch>I<$PVers>I<Extname>F<]> subdirectory of one of the directories in C<@INC> (where I<PVers> is the version of Perl you're using, as supplied in C<$]>, with '.' converted to '_'), or =item * one of the directories in C<@INC>, or =item * a directory which the extensions Perl library module passes to the DynaLoader when asking it to map the shareable image, or =item * F<Sys$Share> or F<Sys$Library>. =back If the shareable image isn't in any of these places, you'll need to define a logical name I<Extshortname>, where I<Extshortname> is the portion of the extension's name after the last C<::>, which translates to the full file specification of the shareable image. =head1 File specifications =head2 Syntax We have tried to make Perl aware of both VMS-style and Unix-style file specifications wherever possible. You may use either style, or both, on the command line and in scripts, but you may not combine the two styles within a single file specification. VMS Perl interprets Unix pathnames in much the same way as the CRTL (I<e.g.> the first component of an absolute path is read as the device name for the VMS file specification). There are a set of functions provided in the C<VMS::Filespec> package for explicit interconversion between VMS and Unix syntax; its documentation provides more details. We've tried to minimize the dependence of Perl library modules on Unix syntax, but you may find that some of these, as well as some scripts written for Unix systems, will require that you use Unix syntax, since they will assume that '/' is the directory separator, I<etc.> If you find instances of this in the Perl distribution itself, please let us know, so we can try to work around them. Also when working on Perl programs on VMS, if you need a syntax in a specific operating system format, then you need either to check the appropriate DECC$ feature logical, or call a conversion routine to force it to that format. The feature logical name DECC$FILENAME_UNIX_REPORT modifies traditional Perl behavior in the conversion of file specifications from Unix to VMS format in order to follow the extended character handling rules now expected by the CRTL. Specifically, when this feature is in effect, the C<./.../> in a Unix path is now translated to C<[.^.^.^.]> instead of the traditional VMS C<[...]>. To be compatible with what MakeMaker expects, if a VMS path cannot be translated to a Unix path, it is passed through unchanged, so C<unixify("[...]")> will return C<[...]>. The handling of extended characters is largely complete in the VMS-specific C infrastructure of Perl, but more work is still needed to fully support extended syntax filenames in several core modules. In particular, at this writing PathTools has only partial support for directories containing some extended characters. There are several ambiguous cases where a conversion routine cannot determine whether an input filename is in Unix format or in VMS format, since now both VMS and Unix file specifications may have characters in them that could be mistaken for syntax delimiters of the other type. So some pathnames simply cannot be used in a mode that allows either type of pathname to be present. Perl will tend to assume that an ambiguous filename is in Unix format. Allowing "." as a version delimiter is simply incompatible with determining whether a pathname is in VMS format or in Unix format with extended file syntax. There is no way to know whether "perl-5.8.6" is a Unix "perl-5.8.6" or a VMS "perl-5.8;6" when passing it to unixify() or vmsify(). The DECC$FILENAME_UNIX_REPORT logical name controls how Perl interprets filenames to the extent that Perl uses the CRTL internally for many purposes, and attempts to follow CRTL conventions for reporting filenames. The DECC$FILENAME_UNIX_ONLY feature differs in that it expects all filenames passed to the C run-time to be already in Unix format. This feature is not yet supported in Perl since Perl uses traditional OpenVMS file specifications internally and in the test harness, and it is not yet clear whether this mode will be useful or useable. The feature logical name DECC$POSIX_COMPLIANT_PATHNAMES is new with the RMS Symbolic Link SDK and included with OpenVMS v8.3, but is not yet supported in Perl. =head2 Filename Case Perl follows VMS defaults and override settings in preserving (or not preserving) filename case. Case is not preserved on ODS-2 formatted volumes on any architecture. On ODS-5 volumes, filenames may be case preserved depending on process and feature settings. Perl now honors DECC$EFS_CASE_PRESERVE and DECC$ARGV_PARSE_STYLE on those systems where the CRTL supports these features. When these features are not enabled or the CRTL does not support them, Perl follows the traditional CRTL behavior of downcasing command-line arguments and returning file specifications in lower case only. I<N. B.> It is very easy to get tripped up using a mixture of other programs, external utilities, and Perl scripts that are in varying states of being able to handle case preservation. For example, a file created by an older version of an archive utility or a build utility such as MMK or MMS may generate a filename in all upper case even on an ODS-5 volume. If this filename is later retrieved by a Perl script or module in a case preserving environment, that upper case name may not match the mixed-case or lower-case exceptions of the Perl code. Your best bet is to follow an all-or-nothing approach to case preservation: either don't use it at all, or make sure your entire toolchain and application environment support and use it. OpenVMS Alpha v7.3-1 and later and all version of OpenVMS I64 support case sensitivity as a process setting (see C<SET PROCESS /CASE_LOOKUP=SENSITIVE>). Perl does not currently support case sensitivity on VMS, but it may in the future, so Perl programs should use the C<< File::Spec->case_tolerant >> method to determine the state, and not the C<$^O> variable. =head2 Symbolic Links When built on an ODS-5 volume with symbolic links enabled, Perl by default supports symbolic links when the requisite support is available in the filesystem and CRTL (generally 64-bit OpenVMS v8.3 and later). There are a number of limitations and caveats to be aware of when working with symbolic links on VMS. Most notably, the target of a valid symbolic link must be expressed as a Unix-style path and it must exist on a volume visible from your POSIX root (see the C<SHOW ROOT> command in DCL help). For further details on symbolic link capabilities and requirements, see chapter 12 of the CRTL manual that ships with OpenVMS v8.3 or later. =head2 Wildcard expansion File specifications containing wildcards are allowed both on the command line and within Perl globs (e.g. C<E<lt>*.cE<gt>>). If the wildcard filespec uses VMS syntax, the resultant filespecs will follow VMS syntax; if a Unix-style filespec is passed in, Unix-style filespecs will be returned. Similar to the behavior of wildcard globbing for a Unix shell, one can escape command line wildcards with double quotation marks C<"> around a perl program command line argument. However, owing to the stripping of C<"> characters carried out by the C handling of argv you will need to escape a construct such as this one (in a directory containing the files F<PERL.C>, F<PERL.EXE>, F<PERL.H>, and F<PERL.OBJ>): $ perl -e "print join(' ',@ARGV)" perl.* perl.c perl.exe perl.h perl.obj in the following triple quoted manner: $ perl -e "print join(' ',@ARGV)" """perl.*""" perl.* In both the case of unquoted command line arguments or in calls to C<glob()> VMS wildcard expansion is performed. (csh-style wildcard expansion is available if you use C<File::Glob::glob>.) If the wildcard filespec contains a device or directory specification, then the resultant filespecs will also contain a device and directory; otherwise, device and directory information are removed. VMS-style resultant filespecs will contain a full device and directory, while Unix-style resultant filespecs will contain only as much of a directory path as was present in the input filespec. For example, if your default directory is Perl_Root:[000000], the expansion of C<[.t]*.*> will yield filespecs like "perl_root:[t]base.dir", while the expansion of C<t/*/*> will yield filespecs like "t/base.dir". (This is done to match the behavior of glob expansion performed by Unix shells.) Similarly, the resultant filespec will contain the file version only if one was present in the input filespec. =head2 Pipes Input and output pipes to Perl filehandles are supported; the "file name" is passed to lib$spawn() for asynchronous execution. You should be careful to close any pipes you have opened in a Perl script, lest you leave any "orphaned" subprocesses around when Perl exits. You may also use backticks to invoke a DCL subprocess, whose output is used as the return value of the expression. The string between the backticks is handled as if it were the argument to the C<system> operator (see below). In this case, Perl will wait for the subprocess to complete before continuing. The mailbox (MBX) that perl can create to communicate with a pipe defaults to a buffer size of 8192 on 64-bit systems, 512 on VAX. The default buffer size is adjustable via the logical name PERL_MBX_SIZE provided that the value falls between 128 and the SYSGEN parameter MAXBUF inclusive. For example, to set the mailbox size to 32767 use C<$ENV{'PERL_MBX_SIZE'} = 32767;> and then open and use pipe constructs. An alternative would be to issue the command: $ Define PERL_MBX_SIZE 32767 before running your wide record pipe program. A larger value may improve performance at the expense of the BYTLM UAF quota. =head1 PERL5LIB and PERLLIB The PERL5LIB and PERLLIB logical names work as documented in L<perl>, except that the element separator is '|' instead of ':'. The directory specifications may use either VMS or Unix syntax. =head1 The Perl Forked Debugger The Perl forked debugger places the debugger commands and output in a separate X-11 terminal window so that commands and output from multiple processes are not mixed together. Perl on VMS supports an emulation of the forked debugger when Perl is run on a VMS system that has X11 support installed. To use the forked debugger, you need to have the default display set to an X-11 Server and some environment variables set that Unix expects. The forked debugger requires the environment variable C<TERM> to be C<xterm>, and the environment variable C<DISPLAY> to exist. C<xterm> must be in lower case. $define TERM "xterm" $define DISPLAY "hostname:0.0" Currently the value of C<DISPLAY> is ignored. It is recommended that it be set to be the hostname of the display, the server and screen in Unix notation. In the future the value of DISPLAY may be honored by Perl instead of using the default display. It may be helpful to always use the forked debugger so that script I/O is separated from debugger I/O. You can force the debugger to be forked by assigning a value to the logical name <PERLDB_PIDS> that is not a process identification number. $define PERLDB_PIDS XXXX =head1 PERL_VMS_EXCEPTION_DEBUG The PERL_VMS_EXCEPTION_DEBUG being defined as "ENABLE" will cause the VMS debugger to be invoked if a fatal exception that is not otherwise handled is raised. The purpose of this is to allow debugging of internal Perl problems that would cause such a condition. This allows the programmer to look at the execution stack and variables to find out the cause of the exception. As the debugger is being invoked as the Perl interpreter is about to do a fatal exit, continuing the execution in debug mode is usually not practical. Starting Perl in the VMS debugger may change the program execution profile in a way that such problems are not reproduced. The C<kill> function can be used to test this functionality from within a program. In typical VMS style, only the first letter of the value of this logical name is actually checked in a case insensitive mode, and it is considered enabled if it is the value "T","1" or "E". This logical name must be defined before Perl is started. =head1 Command line =head2 I/O redirection and backgrounding Perl for VMS supports redirection of input and output on the command line, using a subset of Bourne shell syntax: =over 4 =item * C<E<lt>file> reads stdin from C<file>, =item * C<E<gt>file> writes stdout to C<file>, =item * C<E<gt>E<gt>file> appends stdout to C<file>, =item * C<2E<gt>file> writes stderr to C<file>, =item * C<2E<gt>E<gt>file> appends stderr to C<file>, and =item * C<< 2>&1 >> redirects stderr to stdout. =back In addition, output may be piped to a subprocess, using the character '|'. Anything after this character on the command line is passed to a subprocess for execution; the subprocess takes the output of Perl as its input. Finally, if the command line ends with '&', the entire command is run in the background as an asynchronous subprocess. =head2 Command line switches The following command line switches behave differently under VMS than described in L<perlrun>. Note also that in order to pass uppercase switches to Perl, you need to enclose them in double-quotes on the command line, since the CRTL downcases all unquoted strings. On newer 64 bit versions of OpenVMS, a process setting now controls if the quoting is needed to preserve the case of command line arguments. =over 4 =item -i If the C<-i> switch is present but no extension for a backup copy is given, then inplace editing creates a new version of a file; the existing copy is not deleted. (Note that if an extension is given, an existing file is renamed to the backup file, as is the case under other operating systems, so it does not remain as a previous version under the original filename.) =item -S If the C<"-S"> or C<-"S"> switch is present I<and> the script name does not contain a directory, then Perl translates the logical name DCL$PATH as a searchlist, using each translation as a directory in which to look for the script. In addition, if no file type is specified, Perl looks in each directory for a file matching the name specified, with a blank type, a type of F<.pl>, and a type of F<.com>, in that order. =item -u The C<-u> switch causes the VMS debugger to be invoked after the Perl program is compiled, but before it has run. It does not create a core dump file. =back =head1 Perl functions As of the time this document was last revised, the following Perl functions were implemented in the VMS port of Perl (functions marked with * are discussed in more detail below): file tests*, abs, alarm, atan, backticks*, binmode*, bless, caller, chdir, chmod, chown, chomp, chop, chr, close, closedir, cos, crypt*, defined, delete, die, do, dump*, each, endgrent, endpwent, eof, eval, exec*, exists, exit, exp, fileno, flock getc, getgrent*, getgrgid*, getgrnam, getlogin, getppid, getpwent*, getpwnam*, getpwuid*, glob, gmtime*, goto, grep, hex, ioctl, import, index, int, join, keys, kill*, last, lc, lcfirst, lchown*, length, link*, local, localtime, log, lstat, m//, map, mkdir, my, next, no, oct, open, opendir, ord, pack, pipe, pop, pos, print, printf, push, q//, qq//, qw//, qx//*, quotemeta, rand, read, readdir, readlink*, redo, ref, rename, require, reset, return, reverse, rewinddir, rindex, rmdir, s///, scalar, seek, seekdir, select(internal), select (system call)*, setgrent, setpwent, shift, sin, sleep, socketpair, sort, splice, split, sprintf, sqrt, srand, stat, study, substr, symlink*, sysread, system*, syswrite, tell, telldir, tie, time, times*, tr///, uc, ucfirst, umask, undef, unlink*, unpack, untie, unshift, use, utime*, values, vec, wait, waitpid*, wantarray, warn, write, y/// The following functions were not implemented in the VMS port, and calling them produces a fatal error (usually) or undefined behavior (rarely, we hope): chroot, dbmclose, dbmopen, fork*, getpgrp, getpriority, msgctl, msgget, msgsend, msgrcv, semctl, semget, semop, setpgrp, setpriority, shmctl, shmget, shmread, shmwrite, syscall The following functions are available on Perls compiled with Dec C 5.2 or greater and running VMS 7.0 or greater: truncate The following functions are available on Perls built on VMS 7.2 or greater: fcntl (without locking) The following functions may or may not be implemented, depending on what type of socket support you've built into your copy of Perl: accept, bind, connect, getpeername, gethostbyname, getnetbyname, getprotobyname, getservbyname, gethostbyaddr, getnetbyaddr, getprotobynumber, getservbyport, gethostent, getnetent, getprotoent, getservent, sethostent, setnetent, setprotoent, setservent, endhostent, endnetent, endprotoent, endservent, getsockname, getsockopt, listen, recv, select(system call)*, send, setsockopt, shutdown, socket The following function is available on Perls built on 64 bit OpenVMS v8.2 with hard links enabled on an ODS-5 formatted build disk. CRTL support is in principle available as of OpenVMS v7.3-1, and better configuration support could detect this. link The following functions are available on Perls built on 64 bit OpenVMS v8.2 and later. CRTL support is in principle available as of OpenVMS v7.3-2, and better configuration support could detect this. getgrgid, getgrnam, getpwnam, getpwuid, setgrent, ttyname The following functions are available on Perls built on 64 bit OpenVMS v8.2 and later. statvfs, socketpair =over 4 =item File tests The tests C<-b>, C<-B>, C<-c>, C<-C>, C<-d>, C<-e>, C<-f>, C<-o>, C<-M>, C<-s>, C<-S>, C<-t>, C<-T>, and C<-z> work as advertised. The return values for C<-r>, C<-w>, and C<-x> tell you whether you can actually access the file; this may not reflect the UIC-based file protections. Since real and effective UIC don't differ under VMS, C<-O>, C<-R>, C<-W>, and C<-X> are equivalent to C<-o>, C<-r>, C<-w>, and C<-x>. Similarly, several other tests, including C<-A>, C<-g>, C<-k>, C<-l>, C<-p>, and C<-u>, aren't particularly meaningful under VMS, and the values returned by these tests reflect whatever your CRTL C<stat()> routine does to the equivalent bits in the st_mode field. Finally, C<-d> returns true if passed a device specification without an explicit directory (e.g. C<DUA1:>), as well as if passed a directory. There are DECC feature logical names AND ODS-5 volume attributes that also control what values are returned for the date fields. Note: Some sites have reported problems when using the file-access tests (C<-r>, C<-w>, and C<-x>) on files accessed via DEC's DFS. Specifically, since DFS does not currently provide access to the extended file header of files on remote volumes, attempts to examine the ACL fail, and the file tests will return false, with C<$!> indicating that the file does not exist. You can use C<stat> on these files, since that checks UIC-based protection only, and then manually check the appropriate bits, as defined by your C compiler's F<stat.h>, in the mode value it returns, if you need an approximation of the file's protections. =item backticks Backticks create a subprocess, and pass the enclosed string to it for execution as a DCL command. Since the subprocess is created directly via C<lib$spawn()>, any valid DCL command string may be specified. =item binmode FILEHANDLE The C<binmode> operator will attempt to insure that no translation of carriage control occurs on input from or output to this filehandle. Since this involves reopening the file and then restoring its file position indicator, if this function returns FALSE, the underlying filehandle may no longer point to an open file, or may point to a different position in the file than before C<binmode> was called. Note that C<binmode> is generally not necessary when using normal filehandles; it is provided so that you can control I/O to existing record-structured files when necessary. You can also use the C<vmsfopen> function in the VMS::Stdio extension to gain finer control of I/O to files and devices with different record structures. =item crypt PLAINTEXT, USER The C<crypt> operator uses the C<sys$hash_password> system service to generate the hashed representation of PLAINTEXT. If USER is a valid username, the algorithm and salt values are taken from that user's UAF record. If it is not, then the preferred algorithm and a salt of 0 are used. The quadword encrypted value is returned as an 8-character string. The value returned by C<crypt> may be compared against the encrypted password from the UAF returned by the C<getpw*> functions, in order to authenticate users. If you're going to do this, remember that the encrypted password in the UAF was generated using uppercase username and password strings; you'll have to upcase the arguments to C<crypt> to insure that you'll get the proper value: sub validate_passwd { my($user,$passwd) = @_; my($pwdhash); if ( !($pwdhash = (getpwnam($user))[1]) || $pwdhash ne crypt("\U$passwd","\U$name") ) { intruder_alert($name); } return 1; } =item die C<die> will force the native VMS exit status to be an SS$_ABORT code if neither of the $! or $? status values are ones that would cause the native status to be interpreted as being what VMS classifies as SEVERE_ERROR severity for DCL error handling. When C<PERL_VMS_POSIX_EXIT> is active (see L</"$?"> below), the native VMS exit status value will have either one of the C<$!> or C<$?> or C<$^E> or the Unix value 255 encoded into it in a way that the effective original value can be decoded by other programs written in C, including Perl and the GNV package. As per the normal non-VMS behavior of C<die> if either C<$!> or C<$?> are non-zero, one of those values will be encoded into a native VMS status value. If both of the Unix status values are 0, and the C<$^E> value is set one of ERROR or SEVERE_ERROR severity, then the C<$^E> value will be used as the exit code as is. If none of the above apply, the Unix value of 255 will be encoded into a native VMS exit status value. Please note a significant difference in the behavior of C<die> in the C<PERL_VMS_POSIX_EXIT> mode is that it does not force a VMS SEVERE_ERROR status on exit. The Unix exit values of 2 through 255 will be encoded in VMS status values with severity levels of SUCCESS. The Unix exit value of 1 will be encoded in a VMS status value with a severity level of ERROR. This is to be compatible with how the VMS C library encodes these values. The minimum severity level set by C<die> in C<PERL_VMS_POSIX_EXIT> mode may be changed to be ERROR or higher in the future depending on the results of testing and further review. See L</"$?"> for a description of the encoding of the Unix value to produce a native VMS status containing it. =item dump Rather than causing Perl to abort and dump core, the C<dump> operator invokes the VMS debugger. If you continue to execute the Perl program under the debugger, control will be transferred to the label specified as the argument to C<dump>, or, if no label was specified, back to the beginning of the program. All other state of the program (I<e.g.> values of variables, open file handles) are not affected by calling C<dump>. =item exec LIST A call to C<exec> will cause Perl to exit, and to invoke the command given as an argument to C<exec> via C<lib$do_command>. If the argument begins with '@' or '$' (other than as part of a filespec), then it is executed as a DCL command. Otherwise, the first token on the command line is treated as the filespec of an image to run, and an attempt is made to invoke it (using F<.Exe> and the process defaults to expand the filespec) and pass the rest of C<exec>'s argument to it as parameters. If the token has no file type, and matches a file with null type, then an attempt is made to determine whether the file is an executable image which should be invoked using C<MCR> or a text file which should be passed to DCL as a command procedure. =item fork While in principle the C<fork> operator could be implemented via (and with the same rather severe limitations as) the CRTL C<vfork()> routine, and while some internal support to do just that is in place, the implementation has never been completed, making C<fork> currently unavailable. A true kernel C<fork()> is expected in a future version of VMS, and the pseudo-fork based on interpreter threads may be available in a future version of Perl on VMS (see L<perlfork>). In the meantime, use C<system>, backticks, or piped filehandles to create subprocesses. =item getpwent =item getpwnam =item getpwuid These operators obtain the information described in L<perlfunc>, if you have the privileges necessary to retrieve the named user's UAF information via C<sys$getuai>. If not, then only the C<$name>, C<$uid>, and C<$gid> items are returned. The C<$dir> item contains the login directory in VMS syntax, while the C<$comment> item contains the login directory in Unix syntax. The C<$gcos> item contains the owner field from the UAF record. The C<$quota> item is not used. =item gmtime The C<gmtime> operator will function properly if you have a working CRTL C<gmtime()> routine, or if the logical name SYS$TIMEZONE_DIFFERENTIAL is defined as the number of seconds which must be added to UTC to yield local time. (This logical name is defined automatically if you are running a version of VMS with built-in UTC support.) If neither of these cases is true, a warning message is printed, and C<undef> is returned. =item kill In most cases, C<kill> is implemented via the undocumented system service C<$SIGPRC>, which has the same calling sequence as C<$FORCEX>, but throws an exception in the target process rather than forcing it to call C<$EXIT>. Generally speaking, C<kill> follows the behavior of the CRTL's C<kill()> function, but unlike that function can be called from within a signal handler. Also, unlike the C<kill> in some versions of the CRTL, Perl's C<kill> checks the validity of the signal passed in and returns an error rather than attempting to send an unrecognized signal. Also, negative signal values don't do anything special under VMS; they're just converted to the corresponding positive value. =item qx// See the entry on C<backticks> above. =item select (system call) If Perl was not built with socket support, the system call version of C<select> is not available at all. If socket support is present, then the system call version of C<select> functions only for file descriptors attached to sockets. It will not provide information about regular files or pipes, since the CRTL C<select()> routine does not provide this functionality. =item stat EXPR Since VMS keeps track of files according to a different scheme than Unix, it's not really possible to represent the file's ID in the C<st_dev> and C<st_ino> fields of a C<struct stat>. Perl tries its best, though, and the values it uses are pretty unlikely to be the same for two different files. We can't guarantee this, though, so caveat scriptor. =item system LIST The C<system> operator creates a subprocess, and passes its arguments to the subprocess for execution as a DCL command. Since the subprocess is created directly via C<lib$spawn()>, any valid DCL command string may be specified. If the string begins with '@', it is treated as a DCL command unconditionally. Otherwise, if the first token contains a character used as a delimiter in file specification (e.g. C<:> or C<]>), an attempt is made to expand it using a default type of F<.Exe> and the process defaults, and if successful, the resulting file is invoked via C<MCR>. This allows you to invoke an image directly simply by passing the file specification to C<system>, a common Unixish idiom. If the token has no file type, and matches a file with null type, then an attempt is made to determine whether the file is an executable image which should be invoked using C<MCR> or a text file which should be passed to DCL as a command procedure. If LIST consists of the empty string, C<system> spawns an interactive DCL subprocess, in the same fashion as typing B<SPAWN> at the DCL prompt. Perl waits for the subprocess to complete before continuing execution in the current process. As described in L<perlfunc>, the return value of C<system> is a fake "status" which follows POSIX semantics unless the pragma C<use vmsish 'status'> is in effect; see the description of C<$?> in this document for more detail. =item time The value returned by C<time> is the offset in seconds from 01-JAN-1970 00:00:00 (just like the CRTL's times() routine), in order to make life easier for code coming in from the POSIX/Unix world. =item times The array returned by the C<times> operator is divided up according to the same rules the CRTL C<times()> routine. Therefore, the "system time" elements will always be 0, since there is no difference between "user time" and "system" time under VMS, and the time accumulated by a subprocess may or may not appear separately in the "child time" field, depending on whether C<times()> keeps track of subprocesses separately. Note especially that the VAXCRTL (at least) keeps track only of subprocesses spawned using C<fork()> and C<exec()>; it will not accumulate the times of subprocesses spawned via pipes, C<system()>, or backticks. =item unlink LIST C<unlink> will delete the highest version of a file only; in order to delete all versions, you need to say 1 while unlink LIST; You may need to make this change to scripts written for a Unix system which expect that after a call to C<unlink>, no files with the names passed to C<unlink> will exist. (Note: This can be changed at compile time; if you C<use Config> and C<$Config{'d_unlink_all_versions'}> is C<define>, then C<unlink> will delete all versions of a file on the first call.) C<unlink> will delete a file if at all possible, even if it requires changing file protection (though it won't try to change the protection of the parent directory). You can tell whether you've got explicit delete access to a file by using the C<VMS::Filespec::candelete> operator. For instance, in order to delete only files to which you have delete access, you could say something like sub safe_unlink { my($file,$num); foreach $file (@_) { next unless VMS::Filespec::candelete($file); $num += unlink $file; } $num; } (or you could just use C<VMS::Stdio::remove>, if you've installed the VMS::Stdio extension distributed with Perl). If C<unlink> has to change the file protection to delete the file, and you interrupt it in midstream, the file may be left intact, but with a changed ACL allowing you delete access. This behavior of C<unlink> is to be compatible with POSIX behavior and not traditional VMS behavior. =item utime LIST This operator changes only the modification time of the file (VMS revision date) on ODS-2 volumes and ODS-5 volumes without access dates enabled. On ODS-5 volumes with access dates enabled, the true access time is modified. =item waitpid PID,FLAGS If PID is a subprocess started by a piped C<open()> (see L<open>), C<waitpid> will wait for that subprocess, and return its final status value in C<$?>. If PID is a subprocess created in some other way (e.g. SPAWNed before Perl was invoked), C<waitpid> will simply check once per second whether the process has completed, and return when it has. (If PID specifies a process that isn't a subprocess of the current process, and you invoked Perl with the C<-w> switch, a warning will be issued.) Returns PID on success, -1 on error. The FLAGS argument is ignored in all cases. =back =head1 Perl variables The following VMS-specific information applies to the indicated "special" Perl variables, in addition to the general information in L<perlvar>. Where there is a conflict, this information takes precedence. =over 4 =item %ENV The operation of the C<%ENV> array depends on the translation of the logical name F<PERL_ENV_TABLES>. If defined, it should be a search list, each element of which specifies a location for C<%ENV> elements. If you tell Perl to read or set the element C<$ENV{>I<name>C<}>, then Perl uses the translations of F<PERL_ENV_TABLES> as follows: =over 4 =item CRTL_ENV This string tells Perl to consult the CRTL's internal C<environ> array of key-value pairs, using I<name> as the key. In most cases, this contains only a few keys, but if Perl was invoked via the C C<exec[lv]e()> function, as is the case for CGI processing by some HTTP servers, then the C<environ> array may have been populated by the calling program. =item CLISYM_[LOCAL] A string beginning with C<CLISYM_>tells Perl to consult the CLI's symbol tables, using I<name> as the name of the symbol. When reading an element of C<%ENV>, the local symbol table is scanned first, followed by the global symbol table.. The characters following C<CLISYM_> are significant when an element of C<%ENV> is set or deleted: if the complete string is C<CLISYM_LOCAL>, the change is made in the local symbol table; otherwise the global symbol table is changed. =item Any other string If an element of F<PERL_ENV_TABLES> translates to any other string, that string is used as the name of a logical name table, which is consulted using I<name> as the logical name. The normal search order of access modes is used. =back F<PERL_ENV_TABLES> is translated once when Perl starts up; any changes you make while Perl is running do not affect the behavior of C<%ENV>. If F<PERL_ENV_TABLES> is not defined, then Perl defaults to consulting first the logical name tables specified by F<LNM$FILE_DEV>, and then the CRTL C<environ> array. In all operations on %ENV, the key string is treated as if it were entirely uppercase, regardless of the case actually specified in the Perl expression. When an element of C<%ENV> is read, the locations to which F<PERL_ENV_TABLES> points are checked in order, and the value obtained from the first successful lookup is returned. If the name of the C<%ENV> element contains a semi-colon, it and any characters after it are removed. These are ignored when the CRTL C<environ> array or a CLI symbol table is consulted. However, the name is looked up in a logical name table, the suffix after the semi-colon is treated as the translation index to be used for the lookup. This lets you look up successive values for search list logical names. For instance, if you say $ Define STORY once,upon,a,time,there,was $ perl -e "for ($i = 0; $i <= 6; $i++) " - _$ -e "{ print $ENV{'story;'.$i},' '}" Perl will print C<ONCE UPON A TIME THERE WAS>, assuming, of course, that F<PERL_ENV_TABLES> is set up so that the logical name C<story> is found, rather than a CLI symbol or CRTL C<environ> element with the same name. When an element of C<%ENV> is set to a defined string, the corresponding definition is made in the location to which the first translation of F<PERL_ENV_TABLES> points. If this causes a logical name to be created, it is defined in supervisor mode. (The same is done if an existing logical name was defined in executive or kernel mode; an existing user or supervisor mode logical name is reset to the new value.) If the value is an empty string, the logical name's translation is defined as a single NUL (ASCII 00) character, since a logical name cannot translate to a zero-length string. (This restriction does not apply to CLI symbols or CRTL C<environ> values; they are set to the empty string.) An element of the CRTL C<environ> array can be set only if your copy of Perl knows about the CRTL's C<setenv()> function. (This is present only in some versions of the DECCRTL; check C<$Config{d_setenv}> to see whether your copy of Perl was built with a CRTL that has this function.) When an element of C<%ENV> is set to C<undef>, the element is looked up as if it were being read, and if it is found, it is deleted. (An item "deleted" from the CRTL C<environ> array is set to the empty string; this can only be done if your copy of Perl knows about the CRTL C<setenv()> function.) Using C<delete> to remove an element from C<%ENV> has a similar effect, but after the element is deleted, another attempt is made to look up the element, so an inner-mode logical name or a name in another location will replace the logical name just deleted. In either case, only the first value found searching PERL_ENV_TABLES is altered. It is not possible at present to define a search list logical name via %ENV. The element C<$ENV{DEFAULT}> is special: when read, it returns Perl's current default device and directory, and when set, it resets them, regardless of the definition of F<PERL_ENV_TABLES>. It cannot be cleared or deleted; attempts to do so are silently ignored. Note that if you want to pass on any elements of the C-local environ array to a subprocess which isn't started by fork/exec, or isn't running a C program, you can "promote" them to logical names in the current process, which will then be inherited by all subprocesses, by saying foreach my $key (qw[C-local keys you want promoted]) { my $temp = $ENV{$key}; # read from C-local array $ENV{$key} = $temp; # and define as logical name } (You can't just say C<$ENV{$key} = $ENV{$key}>, since the Perl optimizer is smart enough to elide the expression.) Don't try to clear C<%ENV> by saying C<%ENV = ();>, it will throw a fatal error. This is equivalent to doing the following from DCL: DELETE/LOGICAL * You can imagine how bad things would be if, for example, the SYS$MANAGER or SYS$SYSTEM logical names were deleted. At present, the first time you iterate over %ENV using C<keys>, or C<values>, you will incur a time penalty as all logical names are read, in order to fully populate %ENV. Subsequent iterations will not reread logical names, so they won't be as slow, but they also won't reflect any changes to logical name tables caused by other programs. You do need to be careful with the logical names representing process-permanent files, such as C<SYS$INPUT> and C<SYS$OUTPUT>. The translations for these logical names are prepended with a two-byte binary value (0x1B 0x00) that needs to be stripped off if you wantto use it. (In previous versions of Perl it wasn't possible to get the values of these logical names, as the null byte acted as an end-of-string marker) =item $! The string value of C<$!> is that returned by the CRTL's strerror() function, so it will include the VMS message for VMS-specific errors. The numeric value of C<$!> is the value of C<errno>, except if errno is EVMSERR, in which case C<$!> contains the value of vaxc$errno. Setting C<$!> always sets errno to the value specified. If this value is EVMSERR, it also sets vaxc$errno to 4 (NONAME-F-NOMSG), so that the string value of C<$!> won't reflect the VMS error message from before C<$!> was set. =item $^E This variable provides direct access to VMS status values in vaxc$errno, which are often more specific than the generic Unix-style error messages in C<$!>. Its numeric value is the value of vaxc$errno, and its string value is the corresponding VMS message string, as retrieved by sys$getmsg(). Setting C<$^E> sets vaxc$errno to the value specified. While Perl attempts to keep the vaxc$errno value to be current, if errno is not EVMSERR, it may not be from the current operation. =item $? The "status value" returned in C<$?> is synthesized from the actual exit status of the subprocess in a way that approximates POSIX wait(5) semantics, in order to allow Perl programs to portably test for successful completion of subprocesses. The low order 8 bits of C<$?> are always 0 under VMS, since the termination status of a process may or may not have been generated by an exception. The next 8 bits contain the termination status of the program. If the child process follows the convention of C programs compiled with the _POSIX_EXIT macro set, the status value will contain the actual value of 0 to 255 returned by that program on a normal exit. With the _POSIX_EXIT macro set, the Unix exit value of zero is represented as a VMS native status of 1, and the Unix values from 2 to 255 are encoded by the equation: VMS_status = 0x35a000 + (unix_value * 8) + 1. And in the special case of Unix value 1 the encoding is: VMS_status = 0x35a000 + 8 + 2 + 0x10000000. For other termination statuses, the severity portion of the subprocess's exit status is used: if the severity was success or informational, these bits are all 0; if the severity was warning, they contain a value of 1; if the severity was error or fatal error, they contain the actual severity bits, which turns out to be a value of 2 for error and 4 for severe_error. Fatal is another term for the severe_error status. As a result, C<$?> will always be zero if the subprocess's exit status indicated successful completion, and non-zero if a warning or error occurred or a program compliant with encoding _POSIX_EXIT values was run and set a status. How can you tell the difference between a non-zero status that is the result of a VMS native error status or an encoded Unix status? You can not unless you look at the ${^CHILD_ERROR_NATIVE} value. The ${^CHILD_ERROR_NATIVE} value returns the actual VMS status value and check the severity bits. If the severity bits are equal to 1, then if the numeric value for C<$?> is between 2 and 255 or 0, then C<$?> accurately reflects a value passed back from a Unix application. If C<$?> is 1, and the severity bits indicate a VMS error (2), then C<$?> is from a Unix application exit value. In practice, Perl scripts that call programs that return _POSIX_EXIT type status values will be expecting those values, and programs that call traditional VMS programs will either be expecting the previous behavior or just checking for a non-zero status. And success is always the value 0 in all behaviors. When the actual VMS termination status of the child is an error, internally the C<$!> value will be set to the closest Unix errno value to that error so that Perl scripts that test for error messages will see the expected Unix style error message instead of a VMS message. Conversely, when setting C<$?> in an END block, an attempt is made to convert the POSIX value into a native status intelligible to the operating system upon exiting Perl. What this boils down to is that setting C<$?> to zero results in the generic success value SS$_NORMAL, and setting C<$?> to a non-zero value results in the generic failure status SS$_ABORT. See also L<perlport/exit>. With the C<PERL_VMS_POSIX_EXIT> logical name defined as "ENABLE", setting C<$?> will cause the new value to be encoded into C<$^E> so that either the original parent or child exit status values 0 to 255 can be automatically recovered by C programs expecting _POSIX_EXIT behavior. If both a parent and a child exit value are non-zero, then it will be assumed that this is actually a VMS native status value to be passed through. The special value of 0xFFFF is almost a NOOP as it will cause the current native VMS status in the C library to become the current native Perl VMS status, and is handled this way as it is known to not be a valid native VMS status value. It is recommend that only values in the range of normal Unix parent or child status numbers, 0 to 255 are used. The pragma C<use vmsish 'status'> makes C<$?> reflect the actual VMS exit status instead of the default emulation of POSIX status described above. This pragma also disables the conversion of non-zero values to SS$_ABORT when setting C<$?> in an END block (but zero will still be converted to SS$_NORMAL). Do not use the pragma C<use vmsish 'status'> with C<PERL_VMS_POSIX_EXIT> enabled, as they are at times requesting conflicting actions and the consequence of ignoring this advice will be undefined to allow future improvements in the POSIX exit handling. In general, with C<PERL_VMS_POSIX_EXIT> enabled, more detailed information will be available in the exit status for DCL scripts or other native VMS tools, and will give the expected information for Posix programs. It has not been made the default in order to preserve backward compatibility. N.B. Setting C<DECC$FILENAME_UNIX_REPORT> implicitly enables C<PERL_VMS_POSIX_EXIT>. =item $| Setting C<$|> for an I/O stream causes data to be flushed all the way to disk on each write (I<i.e.> not just to the underlying RMS buffers for a file). In other words, it's equivalent to calling fflush() and fsync() from C. =back =head1 Standard modules with VMS-specific differences =head2 SDBM_File SDBM_File works properly on VMS. It has, however, one minor difference. The database directory file created has a F<.sdbm_dir> extension rather than a F<.dir> extension. F<.dir> files are VMS filesystem directory files, and using them for other purposes could cause unacceptable problems. =head1 Revision date Please see the git repository for revision history. =head1 AUTHOR Charles Bailey bailey@cor.newman.upenn.edu Craig Berry craigberry@mac.com Dan Sugalski dan@sidhe.org John Malmberg wb8tyw@qsl.net PK PU�\V�18V� V� perlpacktut.podnu �[��� =head1 NAME perlpacktut - tutorial on C<pack> and C<unpack> =head1 DESCRIPTION C<pack> and C<unpack> are two functions for transforming data according to a user-defined template, between the guarded way Perl stores values and some well-defined representation as might be required in the environment of a Perl program. Unfortunately, they're also two of the most misunderstood and most often overlooked functions that Perl provides. This tutorial will demystify them for you. =head1 The Basic Principle Most programming languages don't shelter the memory where variables are stored. In C, for instance, you can take the address of some variable, and the C<sizeof> operator tells you how many bytes are allocated to the variable. Using the address and the size, you may access the storage to your heart's content. In Perl, you just can't access memory at random, but the structural and representational conversion provided by C<pack> and C<unpack> is an excellent alternative. The C<pack> function converts values to a byte sequence containing representations according to a given specification, the so-called "template" argument. C<unpack> is the reverse process, deriving some values from the contents of a string of bytes. (Be cautioned, however, that not all that has been packed together can be neatly unpacked - a very common experience as seasoned travellers are likely to confirm.) Why, you may ask, would you need a chunk of memory containing some values in binary representation? One good reason is input and output accessing some file, a device, or a network connection, whereby this binary representation is either forced on you or will give you some benefit in processing. Another cause is passing data to some system call that is not available as a Perl function: C<syscall> requires you to provide parameters stored in the way it happens in a C program. Even text processing (as shown in the next section) may be simplified with judicious usage of these two functions. To see how (un)packing works, we'll start with a simple template code where the conversion is in low gear: between the contents of a byte sequence and a string of hexadecimal digits. Let's use C<unpack>, since this is likely to remind you of a dump program, or some desperate last message unfortunate programs are wont to throw at you before they expire into the wild blue yonder. Assuming that the variable C<$mem> holds a sequence of bytes that we'd like to inspect without assuming anything about its meaning, we can write my( $hex ) = unpack( 'H*', $mem ); print "$hex\n"; whereupon we might see something like this, with each pair of hex digits corresponding to a byte: 41204d414e204120504c414e20412043414e414c2050414e414d41 What was in this chunk of memory? Numbers, characters, or a mixture of both? Assuming that we're on a computer where ASCII (or some similar) encoding is used: hexadecimal values in the range C<0x40> - C<0x5A> indicate an uppercase letter, and C<0x20> encodes a space. So we might assume it is a piece of text, which some are able to read like a tabloid; but others will have to get hold of an ASCII table and relive that firstgrader feeling. Not caring too much about which way to read this, we note that C<unpack> with the template code C<H> converts the contents of a sequence of bytes into the customary hexadecimal notation. Since "a sequence of" is a pretty vague indication of quantity, C<H> has been defined to convert just a single hexadecimal digit unless it is followed by a repeat count. An asterisk for the repeat count means to use whatever remains. The inverse operation - packing byte contents from a string of hexadecimal digits - is just as easily written. For instance: my $s = pack( 'H2' x 10, 30..39 ); print "$s\n"; Since we feed a list of ten 2-digit hexadecimal strings to C<pack>, the pack template should contain ten pack codes. If this is run on a computer with ASCII character coding, it will print C<0123456789>. =head1 Packing Text Let's suppose you've got to read in a data file like this: Date |Description | Income|Expenditure 01/24/2001 Ahmed's Camel Emporium 1147.99 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 235.00 How do we do it? You might think first to use C<split>; however, since C<split> collapses blank fields, you'll never know whether a record was income or expenditure. Oops. Well, you could always use C<substr>: while (<>) { my $date = substr($_, 0, 11); my $desc = substr($_, 12, 27); my $income = substr($_, 40, 7); my $expend = substr($_, 52, 7); ... } It's not really a barrel of laughs, is it? In fact, it's worse than it may seem; the eagle-eyed may notice that the first field should only be 10 characters wide, and the error has propagated right through the other numbers - which we've had to count by hand. So it's error-prone as well as horribly unfriendly. Or maybe we could use regular expressions: while (<>) { my($date, $desc, $income, $expend) = m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|; ... } Urgh. Well, it's a bit better, but - well, would you want to maintain that? Hey, isn't Perl supposed to make this sort of thing easy? Well, it does, if you use the right tools. C<pack> and C<unpack> are designed to help you out when dealing with fixed-width data like the above. Let's have a look at a solution with C<unpack>: while (<>) { my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_); ... } That looks a bit nicer; but we've got to take apart that weird template. Where did I pull that out of? OK, let's have a look at some of our data again; in fact, we'll include the headers, and a handy ruler so we can keep track of where we are. 1 2 3 4 5 1234567890123456789012345678901234567890123456789012345678 Date |Description | Income|Expenditure 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 235.00 From this, we can see that the date column stretches from column 1 to column 10 - ten characters wide. The C<pack>-ese for "character" is C<A>, and ten of them are C<A10>. So if we just wanted to extract the dates, we could say this: my($date) = unpack("A10", $_); OK, what's next? Between the date and the description is a blank column; we want to skip over that. The C<x> template means "skip forward", so we want one of those. Next, we have another batch of characters, from 12 to 38. That's 27 more characters, hence C<A27>. (Don't make the fencepost error - there are 27 characters between 12 and 38, not 26. Count 'em!) Now we skip another character and pick up the next 7 characters: my($date,$description,$income) = unpack("A10xA27xA7", $_); Now comes the clever bit. Lines in our ledger which are just income and not expenditure might end at column 46. Hence, we don't want to tell our C<unpack> pattern that we B<need> to find another 12 characters; we'll just say "if there's anything left, take it". As you might guess from regular expressions, that's what the C<*> means: "use everything remaining". =over 3 =item * Be warned, though, that unlike regular expressions, if the C<unpack> template doesn't match the incoming data, Perl will scream and die. =back Hence, putting it all together: my($date,$description,$income,$expend) = unpack("A10xA27xA7xA*", $_); Now, that's our data parsed. I suppose what we might want to do now is total up our income and expenditure, and add another line to the end of our ledger - in the same format - saying how much we've brought in and how much we've spent: while (<>) { my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_); $tot_income += $income; $tot_expend += $expend; } $tot_income = sprintf("%.2f", $tot_income); # Get them into $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format $date = POSIX::strftime("%m/%d/%Y", localtime); # OK, let's go: print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend); Oh, hmm. That didn't quite work. Let's see what happened: 01/24/2001 Ahmed's Camel Emporium 1147.99 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 1235.00 03/23/2001Totals 1235.001172.98 OK, it's a start, but what happened to the spaces? We put C<x>, didn't we? Shouldn't it skip forward? Let's look at what L<perlfunc/pack> says: x A null byte. Urgh. No wonder. There's a big difference between "a null byte", character zero, and "a space", character 32. Perl's put something between the date and the description - but unfortunately, we can't see it! What we actually need to do is expand the width of the fields. The C<A> format pads any non-existent characters with spaces, so we can use the additional spaces to line up our fields, like this: print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend); (Note that you can put spaces in the template to make it more readable, but they don't translate to spaces in the output.) Here's what we got this time: 01/24/2001 Ahmed's Camel Emporium 1147.99 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 1235.00 03/23/2001 Totals 1235.00 1172.98 That's a bit better, but we still have that last column which needs to be moved further over. There's an easy way to fix this up: unfortunately, we can't get C<pack> to right-justify our fields, but we can get C<sprintf> to do it: $tot_income = sprintf("%.2f", $tot_income); $tot_expend = sprintf("%12.2f", $tot_expend); $date = POSIX::strftime("%m/%d/%Y", localtime); print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend); This time we get the right answer: 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 1235.00 03/23/2001 Totals 1235.00 1172.98 So that's how we consume and produce fixed-width data. Let's recap what we've seen of C<pack> and C<unpack> so far: =over 3 =item * Use C<pack> to go from several pieces of data to one fixed-width version; use C<unpack> to turn a fixed-width-format string into several pieces of data. =item * The pack format C<A> means "any character"; if you're C<pack>ing and you've run out of things to pack, C<pack> will fill the rest up with spaces. =item * C<x> means "skip a byte" when C<unpack>ing; when C<pack>ing, it means "introduce a null byte" - that's probably not what you mean if you're dealing with plain text. =item * You can follow the formats with numbers to say how many characters should be affected by that format: C<A12> means "take 12 characters"; C<x6> means "skip 6 bytes" or "character 0, 6 times". =item * Instead of a number, you can use C<*> to mean "consume everything else left". B<Warning>: when packing multiple pieces of data, C<*> only means "consume all of the current piece of data". That's to say pack("A*A*", $one, $two) packs all of C<$one> into the first C<A*> and then all of C<$two> into the second. This is a general principle: each format character corresponds to one piece of data to be C<pack>ed. =back =head1 Packing Numbers So much for textual data. Let's get onto the meaty stuff that C<pack> and C<unpack> are best at: handling binary formats for numbers. There is, of course, not just one binary format - life would be too simple - but Perl will do all the finicky labor for you. =head2 Integers Packing and unpacking numbers implies conversion to and from some I<specific> binary representation. Leaving floating point numbers aside for the moment, the salient properties of any such representation are: =over 4 =item * the number of bytes used for storing the integer, =item * whether the contents are interpreted as a signed or unsigned number, =item * the byte ordering: whether the first byte is the least or most significant byte (or: little-endian or big-endian, respectively). =back So, for instance, to pack 20302 to a signed 16 bit integer in your computer's representation you write my $ps = pack( 's', 20302 ); Again, the result is a string, now containing 2 bytes. If you print this string (which is, generally, not recommended) you might see C<ON> or C<NO> (depending on your system's byte ordering) - or something entirely different if your computer doesn't use ASCII character encoding. Unpacking C<$ps> with the same template returns the original integer value: my( $s ) = unpack( 's', $ps ); This is true for all numeric template codes. But don't expect miracles: if the packed value exceeds the allotted byte capacity, high order bits are silently discarded, and unpack certainly won't be able to pull them back out of some magic hat. And, when you pack using a signed template code such as C<s>, an excess value may result in the sign bit getting set, and unpacking this will smartly return a negative value. 16 bits won't get you too far with integers, but there is C<l> and C<L> for signed and unsigned 32-bit integers. And if this is not enough and your system supports 64 bit integers you can push the limits much closer to infinity with pack codes C<q> and C<Q>. A notable exception is provided by pack codes C<i> and C<I> for signed and unsigned integers of the "local custom" variety: Such an integer will take up as many bytes as a local C compiler returns for C<sizeof(int)>, but it'll use I<at least> 32 bits. Each of the integer pack codes C<sSlLqQ> results in a fixed number of bytes, no matter where you execute your program. This may be useful for some applications, but it does not provide for a portable way to pass data structures between Perl and C programs (bound to happen when you call XS extensions or the Perl function C<syscall>), or when you read or write binary files. What you'll need in this case are template codes that depend on what your local C compiler compiles when you code C<short> or C<unsigned long>, for instance. These codes and their corresponding byte lengths are shown in the table below. Since the C standard leaves much leeway with respect to the relative sizes of these data types, actual values may vary, and that's why the values are given as expressions in C and Perl. (If you'd like to use values from C<%Config> in your program you have to import it with C<use Config>.) signed unsigned byte length in C byte length in Perl s! S! sizeof(short) $Config{shortsize} i! I! sizeof(int) $Config{intsize} l! L! sizeof(long) $Config{longsize} q! Q! sizeof(long long) $Config{longlongsize} The C<i!> and C<I!> codes aren't different from C<i> and C<I>; they are tolerated for completeness' sake. =head2 Unpacking a Stack Frame Requesting a particular byte ordering may be necessary when you work with binary data coming from some specific architecture whereas your program could run on a totally different system. As an example, assume you have 24 bytes containing a stack frame as it happens on an Intel 8086: +---------+ +----+----+ +---------+ TOS: | IP | TOS+4:| FL | FH | FLAGS TOS+14:| SI | +---------+ +----+----+ +---------+ | CS | | AL | AH | AX | DI | +---------+ +----+----+ +---------+ | BL | BH | BX | BP | +----+----+ +---------+ | CL | CH | CX | DS | +----+----+ +---------+ | DL | DH | DX | ES | +----+----+ +---------+ First, we note that this time-honored 16-bit CPU uses little-endian order, and that's why the low order byte is stored at the lower address. To unpack such a (unsigned) short we'll have to use code C<v>. A repeat count unpacks all 12 shorts: my( $ip, $cs, $flags, $ax, $bx, $cd, $dx, $si, $di, $bp, $ds, $es ) = unpack( 'v12', $frame ); Alternatively, we could have used C<C> to unpack the individually accessible byte registers FL, FH, AL, AH, etc.: my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) = unpack( 'C10', substr( $frame, 4, 10 ) ); It would be nice if we could do this in one fell swoop: unpack a short, back up a little, and then unpack 2 bytes. Since Perl I<is> nice, it proffers the template code C<X> to back up one byte. Putting this all together, we may now write: my( $ip, $cs, $flags,$fl,$fh, $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh, $si, $di, $bp, $ds, $es ) = unpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame ); (The clumsy construction of the template can be avoided - just read on!) We've taken some pains to construct the template so that it matches the contents of our frame buffer. Otherwise we'd either get undefined values, or C<unpack> could not unpack all. If C<pack> runs out of items, it will supply null strings (which are coerced into zeroes whenever the pack code says so). =head2 How to Eat an Egg on a Net The pack code for big-endian (high order byte at the lowest address) is C<n> for 16 bit and C<N> for 32 bit integers. You use these codes if you know that your data comes from a compliant architecture, but, surprisingly enough, you should also use these pack codes if you exchange binary data, across the network, with some system that you know next to nothing about. The simple reason is that this order has been chosen as the I<network order>, and all standard-fearing programs ought to follow this convention. (This is, of course, a stern backing for one of the Lilliputian parties and may well influence the political development there.) So, if the protocol expects you to send a message by sending the length first, followed by just so many bytes, you could write: my $buf = pack( 'N', length( $msg ) ) . $msg; or even: my $buf = pack( 'NA*', length( $msg ), $msg ); and pass C<$buf> to your send routine. Some protocols demand that the count should include the length of the count itself: then just add 4 to the data length. (But make sure to read L<"Lengths and Widths"> before you really code this!) =head2 Byte-order modifiers In the previous sections we've learned how to use C<n>, C<N>, C<v> and C<V> to pack and unpack integers with big- or little-endian byte-order. While this is nice, it's still rather limited because it leaves out all kinds of signed integers as well as 64-bit integers. For example, if you wanted to unpack a sequence of signed big-endian 16-bit integers in a platform-independent way, you would have to write: my @data = unpack 's*', pack 'S*', unpack 'n*', $buf; This is ugly. As of Perl 5.9.2, there's a much nicer way to express your desire for a certain byte-order: the C<E<gt>> and C<E<lt>> modifiers. C<E<gt>> is the big-endian modifier, while C<E<lt>> is the little-endian modifier. Using them, we could rewrite the above code as: my @data = unpack 's>*', $buf; As you can see, the "big end" of the arrow touches the C<s>, which is a nice way to remember that C<E<gt>> is the big-endian modifier. The same obviously works for C<E<lt>>, where the "little end" touches the code. You will probably find these modifiers even more useful if you have to deal with big- or little-endian C structures. Be sure to read L<"Packing and Unpacking C Structures"> for more on that. =head2 Floating point Numbers For packing floating point numbers you have the choice between the pack codes C<f>, C<d>, C<F> and C<D>. C<f> and C<d> pack into (or unpack from) single-precision or double-precision representation as it is provided by your system. If your systems supports it, C<D> can be used to pack and unpack extended-precision floating point values (C<long double>), which can offer even more resolution than C<f> or C<d>. C<F> packs an C<NV>, which is the floating point type used by Perl internally. (There is no such thing as a network representation for reals, so if you want to send your real numbers across computer boundaries, you'd better stick to ASCII representation, unless you're absolutely sure what's on the other end of the line. For the even more adventuresome, you can use the byte-order modifiers from the previous section also on floating point codes.) =head1 Exotic Templates =head2 Bit Strings Bits are the atoms in the memory world. Access to individual bits may have to be used either as a last resort or because it is the most convenient way to handle your data. Bit string (un)packing converts between strings containing a series of C<0> and C<1> characters and a sequence of bytes each containing a group of 8 bits. This is almost as simple as it sounds, except that there are two ways the contents of a byte may be written as a bit string. Let's have a look at an annotated byte: 7 6 5 4 3 2 1 0 +-----------------+ | 1 0 0 0 1 1 0 0 | +-----------------+ MSB LSB It's egg-eating all over again: Some think that as a bit string this should be written "10001100" i.e. beginning with the most significant bit, others insist on "00110001". Well, Perl isn't biased, so that's why we have two bit string codes: $byte = pack( 'B8', '10001100' ); # start with MSB $byte = pack( 'b8', '00110001' ); # start with LSB It is not possible to pack or unpack bit fields - just integral bytes. C<pack> always starts at the next byte boundary and "rounds up" to the next multiple of 8 by adding zero bits as required. (If you do want bit fields, there is L<perlfunc/vec>. Or you could implement bit field handling at the character string level, using split, substr, and concatenation on unpacked bit strings.) To illustrate unpacking for bit strings, we'll decompose a simple status register (a "-" stands for a "reserved" bit): +-----------------+-----------------+ | S Z - A - P - C | - - - - O D I T | +-----------------+-----------------+ MSB LSB MSB LSB Converting these two bytes to a string can be done with the unpack template C<'b16'>. To obtain the individual bit values from the bit string we use C<split> with the "empty" separator pattern which dissects into individual characters. Bit values from the "reserved" positions are simply assigned to C<undef>, a convenient notation for "I don't care where this goes". ($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign, $trace, $interrupt, $direction, $overflow) = split( //, unpack( 'b16', $status ) ); We could have used an unpack template C<'b12'> just as well, since the last 4 bits can be ignored anyway. =head2 Uuencoding Another odd-man-out in the template alphabet is C<u>, which packs an "uuencoded string". ("uu" is short for Unix-to-Unix.) Chances are that you won't ever need this encoding technique which was invented to overcome the shortcomings of old-fashioned transmission mediums that do not support other than simple ASCII data. The essential recipe is simple: Take three bytes, or 24 bits. Split them into 4 six-packs, adding a space (0x20) to each. Repeat until all of the data is blended. Fold groups of 4 bytes into lines no longer than 60 and garnish them in front with the original byte count (incremented by 0x20) and a C<"\n"> at the end. - The C<pack> chef will prepare this for you, a la minute, when you select pack code C<u> on the menu: my $uubuf = pack( 'u', $bindat ); A repeat count after C<u> sets the number of bytes to put into an uuencoded line, which is the maximum of 45 by default, but could be set to some (smaller) integer multiple of three. C<unpack> simply ignores the repeat count. =head2 Doing Sums An even stranger template code is C<%>E<lt>I<number>E<gt>. First, because it's used as a prefix to some other template code. Second, because it cannot be used in C<pack> at all, and third, in C<unpack>, doesn't return the data as defined by the template code it precedes. Instead it'll give you an integer of I<number> bits that is computed from the data value by doing sums. For numeric unpack codes, no big feat is achieved: my $buf = pack( 'iii', 100, 20, 3 ); print unpack( '%32i3', $buf ), "\n"; # prints 123 For string values, C<%> returns the sum of the byte values saving you the trouble of a sum loop with C<substr> and C<ord>: print unpack( '%32A*', "\x01\x10" ), "\n"; # prints 17 Although the C<%> code is documented as returning a "checksum": don't put your trust in such values! Even when applied to a small number of bytes, they won't guarantee a noticeable Hamming distance. In connection with C<b> or C<B>, C<%> simply adds bits, and this can be put to good use to count set bits efficiently: my $bitcount = unpack( '%32b*', $mask ); And an even parity bit can be determined like this: my $evenparity = unpack( '%1b*', $mask ); =head2 Unicode Unicode is a character set that can represent most characters in most of the world's languages, providing room for over one million different characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin characters are assigned to the numbers 0 - 127. The Latin-1 Supplement with characters that are used in several European languages is in the next range, up to 255. After some more Latin extensions we find the character sets from languages using non-Roman alphabets, interspersed with a variety of symbol sets such as currency symbols, Zapf Dingbats or Braille. (You might want to visit L<http://www.unicode.org/> for a look at some of them - my personal favourites are Telugu and Kannada.) The Unicode character sets associates characters with integers. Encoding these numbers in an equal number of bytes would more than double the requirements for storing texts written in Latin alphabets. The UTF-8 encoding avoids this by storing the most common (from a western point of view) characters in a single byte while encoding the rarer ones in three or more bytes. Perl uses UTF-8, internally, for most Unicode strings. So what has this got to do with C<pack>? Well, if you want to compose a Unicode string (that is internally encoded as UTF-8), you can do so by using template code C<U>. As an example, let's produce the Euro currency symbol (code number 0x20AC): $UTF8{Euro} = pack( 'U', 0x20AC ); # Equivalent to: $UTF8{Euro} = "\x{20ac}"; Inspecting C<$UTF8{Euro}> shows that it contains 3 bytes: "\xe2\x82\xac". However, it contains only 1 character, number 0x20AC. The round trip can be completed with C<unpack>: $Unicode{Euro} = unpack( 'U', $UTF8{Euro} ); Unpacking using the C<U> template code also works on UTF-8 encoded byte strings. Usually you'll want to pack or unpack UTF-8 strings: # pack and unpack the Hebrew alphabet my $alefbet = pack( 'U*', 0x05d0..0x05ea ); my @hebrew = unpack( 'U*', $utf ); Please note: in the general case, you're better off using Encode::decode_utf8 to decode a UTF-8 encoded byte string to a Perl Unicode string, and Encode::encode_utf8 to encode a Perl Unicode string to UTF-8 bytes. These functions provide means of handling invalid byte sequences and generally have a friendlier interface. =head2 Another Portable Binary Encoding The pack code C<w> has been added to support a portable binary data encoding scheme that goes way beyond simple integers. (Details can be found at L<http://Casbah.org/>, the Scarab project.) A BER (Binary Encoded Representation) compressed unsigned integer stores base 128 digits, most significant digit first, with as few digits as possible. Bit eight (the high bit) is set on each byte except the last. There is no size limit to BER encoding, but Perl won't go to extremes. my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 ); A hex dump of C<$berbuf>, with spaces inserted at the right places, shows 01 8100 8101 81807F. Since the last byte is always less than 128, C<unpack> knows where to stop. =head1 Template Grouping Prior to Perl 5.8, repetitions of templates had to be made by C<x>-multiplication of template strings. Now there is a better way as we may use the pack codes C<(> and C<)> combined with a repeat count. The C<unpack> template from the Stack Frame example can simply be written like this: unpack( 'v2 (vXXCC)5 v5', $frame ) Let's explore this feature a little more. We'll begin with the equivalent of join( '', map( substr( $_, 0, 1 ), @str ) ) which returns a string consisting of the first character from each string. Using pack, we can write pack( '(A)'.@str, @str ) or, because a repeat count C<*> means "repeat as often as required", simply pack( '(A)*', @str ) (Note that the template C<A*> would only have packed C<$str[0]> in full length.) To pack dates stored as triplets ( day, month, year ) in an array C<@dates> into a sequence of byte, byte, short integer we can write $pd = pack( '(CCS)*', map( @$_, @dates ) ); To swap pairs of characters in a string (with even length) one could use several techniques. First, let's use C<x> and C<X> to skip forward and back: $s = pack( '(A)*', unpack( '(xAXXAx)*', $s ) ); We can also use C<@> to jump to an offset, with 0 being the position where we were when the last C<(> was encountered: $s = pack( '(A)*', unpack( '(@1A @0A @2)*', $s ) ); Finally, there is also an entirely different approach by unpacking big endian shorts and packing them in the reverse byte order: $s = pack( '(v)*', unpack( '(n)*', $s ); =head1 Lengths and Widths =head2 String Lengths In the previous section we've seen a network message that was constructed by prefixing the binary message length to the actual message. You'll find that packing a length followed by so many bytes of data is a frequently used recipe since appending a null byte won't work if a null byte may be part of the data. Here is an example where both techniques are used: after two null terminated strings with source and destination address, a Short Message (to a mobile phone) is sent after a length byte: my $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm ); Unpacking this message can be done with the same template: ( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg ); There's a subtle trap lurking in the offing: Adding another field after the Short Message (in variable C<$sm>) is all right when packing, but this cannot be unpacked naively: # pack a message my $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio ); # unpack fails - $prio remains undefined! ( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg ); The pack code C<A*> gobbles up all remaining bytes, and C<$prio> remains undefined! Before we let disappointment dampen the morale: Perl's got the trump card to make this trick too, just a little further up the sleeve. Watch this: # pack a message: ASCIIZ, ASCIIZ, length/string, byte my $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio ); # unpack ( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg ); Combining two pack codes with a slash (C</>) associates them with a single value from the argument list. In C<pack>, the length of the argument is taken and packed according to the first code while the argument itself is added after being converted with the template code after the slash. This saves us the trouble of inserting the C<length> call, but it is in C<unpack> where we really score: The value of the length byte marks the end of the string to be taken from the buffer. Since this combination doesn't make sense except when the second pack code isn't C<a*>, C<A*> or C<Z*>, Perl won't let you. The pack code preceding C</> may be anything that's fit to represent a number: All the numeric binary pack codes, and even text codes such as C<A4> or C<Z*>: # pack/unpack a string preceded by its length in ASCII my $buf = pack( 'A4/A*', "Humpty-Dumpty" ); # unpack $buf: '13 Humpty-Dumpty' my $txt = unpack( 'A4/A*', $buf ); C</> is not implemented in Perls before 5.6, so if your code is required to work on older Perls you'll need to C<unpack( 'Z* Z* C')> to get the length, then use it to make a new unpack string. For example # pack a message: ASCIIZ, ASCIIZ, length, string, byte (5.005 compatible) my $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio ); # unpack ( undef, undef, $len) = unpack( 'Z* Z* C', $msg ); ($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg ); But that second C<unpack> is rushing ahead. It isn't using a simple literal string for the template. So maybe we should introduce... =head2 Dynamic Templates So far, we've seen literals used as templates. If the list of pack items doesn't have fixed length, an expression constructing the template is required (whenever, for some reason, C<()*> cannot be used). Here's an example: To store named string values in a way that can be conveniently parsed by a C program, we create a sequence of names and null terminated ASCII strings, with C<=> between the name and the value, followed by an additional delimiting null byte. Here's how: my $env = pack( '(A*A*Z*)' . keys( %Env ) . 'C', map( { ( $_, '=', $Env{$_} ) } keys( %Env ) ), 0 ); Let's examine the cogs of this byte mill, one by one. There's the C<map> call, creating the items we intend to stuff into the C<$env> buffer: to each key (in C<$_>) it adds the C<=> separator and the hash entry value. Each triplet is packed with the template code sequence C<A*A*Z*> that is repeated according to the number of keys. (Yes, that's what the C<keys> function returns in scalar context.) To get the very last null byte, we add a C<0> at the end of the C<pack> list, to be packed with C<C>. (Attentive readers may have noticed that we could have omitted the 0.) For the reverse operation, we'll have to determine the number of items in the buffer before we can let C<unpack> rip it apart: my $n = $env =~ tr/\0// - 1; my %env = map( split( /=/, $_ ), unpack( "(Z*)$n", $env ) ); The C<tr> counts the null bytes. The C<unpack> call returns a list of name-value pairs each of which is taken apart in the C<map> block. =head2 Counting Repetitions Rather than storing a sentinel at the end of a data item (or a list of items), we could precede the data with a count. Again, we pack keys and values of a hash, preceding each with an unsigned short length count, and up front we store the number of pairs: my $env = pack( 'S(S/A* S/A*)*', scalar keys( %Env ), %Env ); This simplifies the reverse operation as the number of repetitions can be unpacked with the C</> code: my %env = unpack( 'S/(S/A* S/A*)', $env ); Note that this is one of the rare cases where you cannot use the same template for C<pack> and C<unpack> because C<pack> can't determine a repeat count for a C<()>-group. =head2 Intel HEX Intel HEX is a file format for representing binary data, mostly for programming various chips, as a text file. (See L<http://en.wikipedia.org/wiki/.hex> for a detailed description, and L<http://en.wikipedia.org/wiki/SREC_(file_format)> for the Motorola S-record format, which can be unravelled using the same technique.) Each line begins with a colon (':') and is followed by a sequence of hexadecimal characters, specifying a byte count I<n> (8 bit), an address (16 bit, big endian), a record type (8 bit), I<n> data bytes and a checksum (8 bit) computed as the least significant byte of the two's complement sum of the preceding bytes. Example: C<:0300300002337A1E>. The first step of processing such a line is the conversion, to binary, of the hexadecimal data, to obtain the four fields, while checking the checksum. No surprise here: we'll start with a simple C<pack> call to convert everything to binary: my $binrec = pack( 'H*', substr( $hexrec, 1 ) ); The resulting byte sequence is most convenient for checking the checksum. Don't slow your program down with a for loop adding the C<ord> values of this string's bytes - the C<unpack> code C<%> is the thing to use for computing the 8-bit sum of all bytes, which must be equal to zero: die unless unpack( "%8C*", $binrec ) == 0; Finally, let's get those four fields. By now, you shouldn't have any problems with the first three fields - but how can we use the byte count of the data in the first field as a length for the data field? Here the codes C<x> and C<X> come to the rescue, as they permit jumping back and forth in the string to unpack. my( $addr, $type, $data ) = unpack( "x n C X4 C x3 /a", $bin ); Code C<x> skips a byte, since we don't need the count yet. Code C<n> takes care of the 16-bit big-endian integer address, and C<C> unpacks the record type. Being at offset 4, where the data begins, we need the count. C<X4> brings us back to square one, which is the byte at offset 0. Now we pick up the count, and zoom forth to offset 4, where we are now fully furnished to extract the exact number of data bytes, leaving the trailing checksum byte alone. =head1 Packing and Unpacking C Structures In previous sections we have seen how to pack numbers and character strings. If it were not for a couple of snags we could conclude this section right away with the terse remark that C structures don't contain anything else, and therefore you already know all there is to it. Sorry, no: read on, please. If you have to deal with a lot of C structures, and don't want to hack all your template strings manually, you'll probably want to have a look at the CPAN module C<Convert::Binary::C>. Not only can it parse your C source directly, but it also has built-in support for all the odds and ends described further on in this section. =head2 The Alignment Pit In the consideration of speed against memory requirements the balance has been tilted in favor of faster execution. This has influenced the way C compilers allocate memory for structures: On architectures where a 16-bit or 32-bit operand can be moved faster between places in memory, or to or from a CPU register, if it is aligned at an even or multiple-of-four or even at a multiple-of eight address, a C compiler will give you this speed benefit by stuffing extra bytes into structures. If you don't cross the C shoreline this is not likely to cause you any grief (although you should care when you design large data structures, or you want your code to be portable between architectures (you do want that, don't you?)). To see how this affects C<pack> and C<unpack>, we'll compare these two C structures: typedef struct { char c1; short s; char c2; long l; } gappy_t; typedef struct { long l; short s; char c1; char c2; } dense_t; Typically, a C compiler allocates 12 bytes to a C<gappy_t> variable, but requires only 8 bytes for a C<dense_t>. After investigating this further, we can draw memory maps, showing where the extra 4 bytes are hidden: 0 +4 +8 +12 +--+--+--+--+--+--+--+--+--+--+--+--+ |c1|xx| s |c2|xx|xx|xx| l | xx = fill byte +--+--+--+--+--+--+--+--+--+--+--+--+ gappy_t 0 +4 +8 +--+--+--+--+--+--+--+--+ | l | h |c1|c2| +--+--+--+--+--+--+--+--+ dense_t And that's where the first quirk strikes: C<pack> and C<unpack> templates have to be stuffed with C<x> codes to get those extra fill bytes. The natural question: "Why can't Perl compensate for the gaps?" warrants an answer. One good reason is that C compilers might provide (non-ANSI) extensions permitting all sorts of fancy control over the way structures are aligned, even at the level of an individual structure field. And, if this were not enough, there is an insidious thing called C<union> where the amount of fill bytes cannot be derived from the alignment of the next item alone. OK, so let's bite the bullet. Here's one way to get the alignment right by inserting template codes C<x>, which don't take a corresponding item from the list: my $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l ); Note the C<!> after C<l>: We want to make sure that we pack a long integer as it is compiled by our C compiler. And even now, it will only work for the platforms where the compiler aligns things as above. And somebody somewhere has a platform where it doesn't. [Probably a Cray, where C<short>s, C<int>s and C<long>s are all 8 bytes. :-)] Counting bytes and watching alignments in lengthy structures is bound to be a drag. Isn't there a way we can create the template with a simple program? Here's a C program that does the trick: #include <stdio.h> #include <stddef.h> typedef struct { char fc1; short fs; char fc2; long fl; } gappy_t; #define Pt(struct,field,tchar) \ printf( "@%d%s ", offsetof(struct,field), # tchar ); int main() { Pt( gappy_t, fc1, c ); Pt( gappy_t, fs, s! ); Pt( gappy_t, fc2, c ); Pt( gappy_t, fl, l! ); printf( "\n" ); } The output line can be used as a template in a C<pack> or C<unpack> call: my $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l ); Gee, yet another template code - as if we hadn't plenty. But C<@> saves our day by enabling us to specify the offset from the beginning of the pack buffer to the next item: This is just the value the C<offsetof> macro (defined in C<E<lt>stddef.hE<gt>>) returns when given a C<struct> type and one of its field names ("member-designator" in C standardese). Neither using offsets nor adding C<x>'s to bridge the gaps is satisfactory. (Just imagine what happens if the structure changes.) What we really need is a way of saying "skip as many bytes as required to the next multiple of N". In fluent Templatese, you say this with C<x!N> where N is replaced by the appropriate value. Here's the next version of our struct packaging: my $gappy = pack( 'c x!2 s c x!4 l!', $c1, $s, $c2, $l ); That's certainly better, but we still have to know how long all the integers are, and portability is far away. Rather than C<2>, for instance, we want to say "however long a short is". But this can be done by enclosing the appropriate pack code in brackets: C<[s]>. So, here's the very best we can do: my $gappy = pack( 'c x![s] s c x![l!] l!', $c1, $s, $c2, $l ); =head2 Dealing with Endian-ness Now, imagine that we want to pack the data for a machine with a different byte-order. First, we'll have to figure out how big the data types on the target machine really are. Let's assume that the longs are 32 bits wide and the shorts are 16 bits wide. You can then rewrite the template as: my $gappy = pack( 'c x![s] s c x![l] l', $c1, $s, $c2, $l ); If the target machine is little-endian, we could write: my $gappy = pack( 'c x![s] s< c x![l] l<', $c1, $s, $c2, $l ); This forces the short and the long members to be little-endian, and is just fine if you don't have too many struct members. But we could also use the byte-order modifier on a group and write the following: my $gappy = pack( '( c x![s] s c x![l] l )<', $c1, $s, $c2, $l ); This is not as short as before, but it makes it more obvious that we intend to have little-endian byte-order for a whole group, not only for individual template codes. It can also be more readable and easier to maintain. =head2 Alignment, Take 2 I'm afraid that we're not quite through with the alignment catch yet. The hydra raises another ugly head when you pack arrays of structures: typedef struct { short count; char glyph; } cell_t; typedef cell_t buffer_t[BUFLEN]; Where's the catch? Padding is neither required before the first field C<count>, nor between this and the next field C<glyph>, so why can't we simply pack like this: # something goes wrong here: pack( 's!a' x @buffer, map{ ( $_->{count}, $_->{glyph} ) } @buffer ); This packs C<3*@buffer> bytes, but it turns out that the size of C<buffer_t> is four times C<BUFLEN>! The moral of the story is that the required alignment of a structure or array is propagated to the next higher level where we have to consider padding I<at the end> of each component as well. Thus the correct template is: pack( 's!ax' x @buffer, map{ ( $_->{count}, $_->{glyph} ) } @buffer ); =head2 Alignment, Take 3 And even if you take all the above into account, ANSI still lets this: typedef struct { char foo[2]; } foo_t; vary in size. The alignment constraint of the structure can be greater than any of its elements. [And if you think that this doesn't affect anything common, dismember the next cellphone that you see. Many have ARM cores, and the ARM structure rules make C<sizeof (foo_t)> == 4] =head2 Pointers for How to Use Them The title of this section indicates the second problem you may run into sooner or later when you pack C structures. If the function you intend to call expects a, say, C<void *> value, you I<cannot> simply take a reference to a Perl variable. (Although that value certainly is a memory address, it's not the address where the variable's contents are stored.) Template code C<P> promises to pack a "pointer to a fixed length string". Isn't this what we want? Let's try: # allocate some storage and pack a pointer to it my $memory = "\x00" x $size; my $memptr = pack( 'P', $memory ); But wait: doesn't C<pack> just return a sequence of bytes? How can we pass this string of bytes to some C code expecting a pointer which is, after all, nothing but a number? The answer is simple: We have to obtain the numeric address from the bytes returned by C<pack>. my $ptr = unpack( 'L!', $memptr ); Obviously this assumes that it is possible to typecast a pointer to an unsigned long and vice versa, which frequently works but should not be taken as a universal law. - Now that we have this pointer the next question is: How can we put it to good use? We need a call to some C function where a pointer is expected. The read(2) system call comes to mind: ssize_t read(int fd, void *buf, size_t count); After reading L<perlfunc> explaining how to use C<syscall> we can write this Perl function copying a file to standard output: require 'syscall.ph'; sub cat($){ my $path = shift(); my $size = -s $path; my $memory = "\x00" x $size; # allocate some memory my $ptr = unpack( 'L', pack( 'P', $memory ) ); open( F, $path ) || die( "$path: cannot open ($!)\n" ); my $fd = fileno(F); my $res = syscall( &SYS_read, fileno(F), $ptr, $size ); print $memory; close( F ); } This is neither a specimen of simplicity nor a paragon of portability but it illustrates the point: We are able to sneak behind the scenes and access Perl's otherwise well-guarded memory! (Important note: Perl's C<syscall> does I<not> require you to construct pointers in this roundabout way. You simply pass a string variable, and Perl forwards the address.) How does C<unpack> with C<P> work? Imagine some pointer in the buffer about to be unpacked: If it isn't the null pointer (which will smartly produce the C<undef> value) we have a start address - but then what? Perl has no way of knowing how long this "fixed length string" is, so it's up to you to specify the actual size as an explicit length after C<P>. my $mem = "abcdefghijklmn"; print unpack( 'P5', pack( 'P', $mem ) ); # prints "abcde" As a consequence, C<pack> ignores any number or C<*> after C<P>. Now that we have seen C<P> at work, we might as well give C<p> a whirl. Why do we need a second template code for packing pointers at all? The answer lies behind the simple fact that an C<unpack> with C<p> promises a null-terminated string starting at the address taken from the buffer, and that implies a length for the data item to be returned: my $buf = pack( 'p', "abc\x00efhijklmn" ); print unpack( 'p', $buf ); # prints "abc" Albeit this is apt to be confusing: As a consequence of the length being implied by the string's length, a number after pack code C<p> is a repeat count, not a length as after C<P>. Using C<pack(..., $x)> with C<P> or C<p> to get the address where C<$x> is actually stored must be used with circumspection. Perl's internal machinery considers the relation between a variable and that address as its very own private matter and doesn't really care that we have obtained a copy. Therefore: =over 4 =item * Do not use C<pack> with C<p> or C<P> to obtain the address of variable that's bound to go out of scope (and thereby freeing its memory) before you are done with using the memory at that address. =item * Be very careful with Perl operations that change the value of the variable. Appending something to the variable, for instance, might require reallocation of its storage, leaving you with a pointer into no-man's land. =item * Don't think that you can get the address of a Perl variable when it is stored as an integer or double number! C<pack('P', $x)> will force the variable's internal representation to string, just as if you had written something like C<$x .= ''>. =back It's safe, however, to P- or p-pack a string literal, because Perl simply allocates an anonymous variable. =head1 Pack Recipes Here are a collection of (possibly) useful canned recipes for C<pack> and C<unpack>: # Convert IP address for socket functions pack( "C4", split /\./, "123.4.5.6" ); # Count the bits in a chunk of memory (e.g. a select vector) unpack( '%32b*', $mask ); # Determine the endianness of your system $is_little_endian = unpack( 'c', pack( 's', 1 ) ); $is_big_endian = unpack( 'xc', pack( 's', 1 ) ); # Determine the number of bits in a native integer $bits = unpack( '%32I!', ~0 ); # Prepare argument for the nanosleep system call my $timespec = pack( 'L!L!', $secs, $nanosecs ); For a simple memory dump we unpack some bytes into just as many pairs of hex digits, and use C<map> to handle the traditional spacing - 16 bytes to a line: my $i; print map( ++$i % 16 ? "$_ " : "$_\n", unpack( 'H2' x length( $mem ), $mem ) ), length( $mem ) % 16 ? "\n" : ''; =head1 Funnies Section # Pulling digits out of nowhere... print unpack( 'C', pack( 'x' ) ), unpack( '%B*', pack( 'A' ) ), unpack( 'H', pack( 'A' ) ), unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n"; # One for the road ;-) my $advice = pack( 'all u can in a van' ); =head1 Authors Simon Cozens and Wolfgang Laun. PK PU�\Ha�j� � perlxstut.podnu �[��� =head1 NAME perlxstut - Tutorial for writing XSUBs =head1 DESCRIPTION This tutorial will educate the reader on the steps involved in creating a Perl extension. The reader is assumed to have access to L<perlguts>, L<perlapi> and L<perlxs>. This tutorial starts with very simple examples and becomes more complex, with each new example adding new features. Certain concepts may not be completely explained until later in the tutorial in order to slowly ease the reader into building extensions. This tutorial was written from a Unix point of view. Where I know them to be otherwise different for other platforms (e.g. Win32), I will list them. If you find something that was missed, please let me know. =head1 SPECIAL NOTES =head2 make This tutorial assumes that the make program that Perl is configured to use is called C<make>. Instead of running "make" in the examples that follow, you may have to substitute whatever make program Perl has been configured to use. Running B<perl -V:make> should tell you what it is. =head2 Version caveat When writing a Perl extension for general consumption, one should expect that the extension will be used with versions of Perl different from the version available on your machine. Since you are reading this document, the version of Perl on your machine is probably 5.005 or later, but the users of your extension may have more ancient versions. To understand what kinds of incompatibilities one may expect, and in the rare case that the version of Perl on your machine is older than this document, see the section on "Troubleshooting these Examples" for more information. If your extension uses some features of Perl which are not available on older releases of Perl, your users would appreciate an early meaningful warning. You would probably put this information into the F<README> file, but nowadays installation of extensions may be performed automatically, guided by F<CPAN.pm> module or other tools. In MakeMaker-based installations, F<Makefile.PL> provides the earliest opportunity to perform version checks. One can put something like this in F<Makefile.PL> for this purpose: eval { require 5.007 } or die <<EOD; ############ ### This module uses frobnication framework which is not available before ### version 5.007 of Perl. Upgrade your Perl before installing Kara::Mba. ############ EOD =head2 Dynamic Loading versus Static Loading It is commonly thought that if a system does not have the capability to dynamically load a library, you cannot build XSUBs. This is incorrect. You I<can> build them, but you must link the XSUBs subroutines with the rest of Perl, creating a new executable. This situation is similar to Perl 4. This tutorial can still be used on such a system. The XSUB build mechanism will check the system and build a dynamically-loadable library if possible, or else a static library and then, optionally, a new statically-linked executable with that static library linked in. Should you wish to build a statically-linked executable on a system which can dynamically load libraries, you may, in all the following examples, where the command "C<make>" with no arguments is executed, run the command "C<make perl>" instead. If you have generated such a statically-linked executable by choice, then instead of saying "C<make test>", you should say "C<make test_static>". On systems that cannot build dynamically-loadable libraries at all, simply saying "C<make test>" is sufficient. =head1 TUTORIAL Now let's go on with the show! =head2 EXAMPLE 1 Our first extension will be very simple. When we call the routine in the extension, it will print out a well-known message and return. Run "C<h2xs -A -n Mytest>". This creates a directory named Mytest, possibly under ext/ if that directory exists in the current working directory. Several files will be created under the Mytest dir, including MANIFEST, Makefile.PL, lib/Mytest.pm, Mytest.xs, t/Mytest.t, and Changes. The MANIFEST file contains the names of all the files just created in the Mytest directory. The file Makefile.PL should look something like this: use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'Mytest', VERSION_FROM => 'Mytest.pm', # finds $VERSION LIBS => [''], # e.g., '-lm' DEFINE => '', # e.g., '-DHAVE_SOMETHING' INC => '', # e.g., '-I/usr/include/other' ); The file Mytest.pm should start with something like this: package Mytest; use 5.008008; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.01'; require XSLoader; XSLoader::load('Mytest', $VERSION); # Preloaded methods go here. 1; __END__ # Below is the stub of documentation for your module. You better edit it! The rest of the .pm file contains sample code for providing documentation for the extension. Finally, the Mytest.xs file should look something like this: #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" MODULE = Mytest PACKAGE = Mytest Let's edit the .xs file by adding this to the end of the file: void hello() CODE: printf("Hello, world!\n"); It is okay for the lines starting at the "CODE:" line to not be indented. However, for readability purposes, it is suggested that you indent CODE: one level and the lines following one more level. Now we'll run "C<perl Makefile.PL>". This will create a real Makefile, which make needs. Its output looks something like: % perl Makefile.PL Checking if your kit is complete... Looks good Writing Makefile for Mytest % Now, running make will produce output that looks something like this (some long lines have been shortened for clarity and some extraneous lines have been deleted): % make cp lib/Mytest.pm blib/lib/Mytest.pm perl xsubpp -typemap typemap Mytest.xs > Mytest.xsc && mv Mytest.xsc Mytest.c Please specify prototyping behavior for Mytest.xs (see perlxs manual) cc -c Mytest.c Running Mkbootstrap for Mytest () chmod 644 Mytest.bs rm -f blib/arch/auto/Mytest/Mytest.so cc -shared -L/usr/local/lib Mytest.o -o blib/arch/auto/Mytest/Mytest.so \ \ chmod 755 blib/arch/auto/Mytest/Mytest.so cp Mytest.bs blib/arch/auto/Mytest/Mytest.bs chmod 644 blib/arch/auto/Mytest/Mytest.bs Manifying blib/man3/Mytest.3pm % You can safely ignore the line about "prototyping behavior" - it is explained in L<perlxs/"The PROTOTYPES: Keyword">. Perl has its own special way of easily writing test scripts, but for this example only, we'll create our own test script. Create a file called hello that looks like this: #! /opt/perl5/bin/perl use ExtUtils::testlib; use Mytest; Mytest::hello(); Now we make the script executable (C<chmod +x hello>), run the script and we should see the following output: % ./hello Hello, world! % =head2 EXAMPLE 2 Now let's add to our extension a subroutine that will take a single numeric argument as input and return 1 if the number is even or 0 if the number is odd. Add the following to the end of Mytest.xs: int is_even(input) int input CODE: RETVAL = (input % 2 == 0); OUTPUT: RETVAL There does not need to be whitespace at the start of the "C<int input>" line, but it is useful for improving readability. Placing a semi-colon at the end of that line is also optional. Any amount and kind of whitespace may be placed between the "C<int>" and "C<input>". Now re-run make to rebuild our new shared library. Now perform the same steps as before, generating a Makefile from the Makefile.PL file, and running make. In order to test that our extension works, we now need to look at the file Mytest.t. This file is set up to imitate the same kind of testing structure that Perl itself has. Within the test script, you perform a number of tests to confirm the behavior of the extension, printing "ok" when the test is correct, "not ok" when it is not. use Test::More tests => 4; BEGIN { use_ok('Mytest') }; ######################### # Insert your test code below, the Test::More module is use()ed here so read # its man page ( perldoc Test::More ) for help writing this test script. is(&Mytest::is_even(0), 1); is(&Mytest::is_even(1), 0); is(&Mytest::is_even(2), 1); We will be calling the test script through the command "C<make test>". You should see output that looks something like this: %make test PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t t/Mytest....ok All tests successful. Files=1, Tests=4, 0 wallclock secs ( 0.03 cusr + 0.00 csys = 0.03 CPU) % =head2 What has gone on? The program h2xs is the starting point for creating extensions. In later examples we'll see how we can use h2xs to read header files and generate templates to connect to C routines. h2xs creates a number of files in the extension directory. The file Makefile.PL is a perl script which will generate a true Makefile to build the extension. We'll take a closer look at it later. The .pm and .xs files contain the meat of the extension. The .xs file holds the C routines that make up the extension. The .pm file contains routines that tell Perl how to load your extension. Generating the Makefile and running C<make> created a directory called blib (which stands for "build library") in the current working directory. This directory will contain the shared library that we will build. Once we have tested it, we can install it into its final location. Invoking the test script via "C<make test>" did something very important. It invoked perl with all those C<-I> arguments so that it could find the various files that are part of the extension. It is I<very> important that while you are still testing extensions that you use "C<make test>". If you try to run the test script all by itself, you will get a fatal error. Another reason it is important to use "C<make test>" to run your test script is that if you are testing an upgrade to an already-existing version, using "C<make test>" ensures that you will test your new extension, not the already-existing version. When Perl sees a C<use extension;>, it searches for a file with the same name as the C<use>'d extension that has a .pm suffix. If that file cannot be found, Perl dies with a fatal error. The default search path is contained in the C<@INC> array. In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic Loader extensions. It then sets the C<@ISA> and C<@EXPORT> arrays and the C<$VERSION> scalar; finally it tells perl to bootstrap the module. Perl will call its dynamic loader routine (if there is one) and load the shared library. The two arrays C<@ISA> and C<@EXPORT> are very important. The C<@ISA> array contains a list of other packages in which to search for methods (or subroutines) that do not exist in the current package. This is usually only important for object-oriented extensions (which we will talk about much later), and so usually doesn't need to be modified. The C<@EXPORT> array tells Perl which of the extension's variables and subroutines should be placed into the calling package's namespace. Because you don't know if the user has already used your variable and subroutine names, it's vitally important to carefully select what to export. Do I<not> export method or variable names I<by default> without a good reason. As a general rule, if the module is trying to be object-oriented then don't export anything. If it's just a collection of functions and variables, then you can export them via another array, called C<@EXPORT_OK>. This array does not automatically place its subroutine and variable names into the namespace unless the user specifically requests that this be done. See L<perlmod> for more information. The C<$VERSION> variable is used to ensure that the .pm file and the shared library are "in sync" with each other. Any time you make changes to the .pm or .xs files, you should increment the value of this variable. =head2 Writing good test scripts The importance of writing good test scripts cannot be over-emphasized. You should closely follow the "ok/not ok" style that Perl itself uses, so that it is very easy and unambiguous to determine the outcome of each test case. When you find and fix a bug, make sure you add a test case for it. By running "C<make test>", you ensure that your Mytest.t script runs and uses the correct version of your extension. If you have many test cases, save your test files in the "t" directory and use the suffix ".t". When you run "C<make test>", all of these test files will be executed. =head2 EXAMPLE 3 Our third extension will take one argument as its input, round off that value, and set the I<argument> to the rounded value. Add the following to the end of Mytest.xs: void round(arg) double arg CODE: if (arg > 0.0) { arg = floor(arg + 0.5); } else if (arg < 0.0) { arg = ceil(arg - 0.5); } else { arg = 0.0; } OUTPUT: arg Edit the Makefile.PL file so that the corresponding line looks like this: 'LIBS' => ['-lm'], # e.g., '-lm' Generate the Makefile and run make. Change the test number in Mytest.t to "9" and add the following tests: $i = -1.5; &Mytest::round($i); is( $i, -2.0 ); $i = -1.1; &Mytest::round($i); is( $i, -1.0 ); $i = 0.0; &Mytest::round($i); is( $i, 0.0 ); $i = 0.5; &Mytest::round($i); is( $i, 1.0 ); $i = 1.2; &Mytest::round($i); is( $i, 1.0 ); Running "C<make test>" should now print out that all nine tests are okay. Notice that in these new test cases, the argument passed to round was a scalar variable. You might be wondering if you can round a constant or literal. To see what happens, temporarily add the following line to Mytest.t: &Mytest::round(3); Run "C<make test>" and notice that Perl dies with a fatal error. Perl won't let you change the value of constants! =head2 What's new here? =over 4 =item * We've made some changes to Makefile.PL. In this case, we've specified an extra library to be linked into the extension's shared library, the math library libm in this case. We'll talk later about how to write XSUBs that can call every routine in a library. =item * The value of the function is not being passed back as the function's return value, but by changing the value of the variable that was passed into the function. You might have guessed that when you saw that the return value of round is of type "void". =back =head2 Input and Output Parameters You specify the parameters that will be passed into the XSUB on the line(s) after you declare the function's return value and name. Each input parameter line starts with optional whitespace, and may have an optional terminating semicolon. The list of output parameters occurs at the very end of the function, just after the OUTPUT: directive. The use of RETVAL tells Perl that you wish to send this value back as the return value of the XSUB function. In Example 3, we wanted the "return value" placed in the original variable which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section. =head2 The XSUBPP Program The B<xsubpp> program takes the XS code in the .xs file and translates it into C code, placing it in a file whose suffix is .c. The C code created makes heavy use of the C functions within Perl. =head2 The TYPEMAP file The B<xsubpp> program uses rules to convert from Perl's data types (scalar, array, etc.) to C's data types (int, char, etc.). These rules are stored in the typemap file ($PERLLIB/ExtUtils/typemap). There's a brief discussion below, but all the nitty-gritty details can be found in L<perlxstypemap>. If you have a new-enough version of perl (5.16 and up) or an upgraded XS compiler (C<ExtUtils::ParseXS> 3.13_01 or better), then you can inline typemaps in your XS instead of writing separate files. Either way, this typemap thing is split into three parts: The first section maps various C data types to a name, which corresponds somewhat with the various Perl types. The second section contains C code which B<xsubpp> uses to handle input parameters. The third section contains C code which B<xsubpp> uses to handle output parameters. Let's take a look at a portion of the .c file created for our extension. The file name is Mytest.c: XS(XS_Mytest_round) { dXSARGS; if (items != 1) Perl_croak(aTHX_ "Usage: Mytest::round(arg)"); PERL_UNUSED_VAR(cv); /* -W */ { double arg = (double)SvNV(ST(0)); /* XXXXX */ if (arg > 0.0) { arg = floor(arg + 0.5); } else if (arg < 0.0) { arg = ceil(arg - 0.5); } else { arg = 0.0; } sv_setnv(ST(0), (double)arg); /* XXXXX */ SvSETMAGIC(ST(0)); } XSRETURN_EMPTY; } Notice the two lines commented with "XXXXX". If you check the first part of the typemap file (or section), you'll see that doubles are of type T_DOUBLE. In the INPUT part of the typemap, an argument that is T_DOUBLE is assigned to the variable arg by calling the routine SvNV on something, then casting it to double, then assigned to the variable arg. Similarly, in the OUTPUT section, once arg has its final value, it is passed to the sv_setnv function to be passed back to the calling subroutine. These two functions are explained in L<perlguts>; we'll talk more later about what that "ST(0)" means in the section on the argument stack. =head2 Warning about Output Arguments In general, it's not a good idea to write extensions that modify their input parameters, as in Example 3. Instead, you should probably return multiple values in an array and let the caller handle them (we'll do this in a later example). However, in order to better accommodate calling pre-existing C routines, which often do modify their input parameters, this behavior is tolerated. =head2 EXAMPLE 4 In this example, we'll now begin to write XSUBs that will interact with pre-defined C libraries. To begin with, we will build a small library of our own, then let h2xs write our .pm and .xs files for us. Create a new directory called Mytest2 at the same level as the directory Mytest. In the Mytest2 directory, create another directory called mylib, and cd into that directory. Here we'll create some files that will generate a test library. These will include a C source file and a header file. We'll also create a Makefile.PL in this directory. Then we'll make sure that running make at the Mytest2 level will automatically run this Makefile.PL file and the resulting Makefile. In the mylib directory, create a file mylib.h that looks like this: #define TESTVAL 4 extern double foo(int, long, const char*); Also create a file mylib.c that looks like this: #include <stdlib.h> #include "./mylib.h" double foo(int a, long b, const char *c) { return (a + b + atof(c) + TESTVAL); } And finally create a file Makefile.PL that looks like this: use ExtUtils::MakeMaker; $Verbose = 1; WriteMakefile( NAME => 'Mytest2::mylib', SKIP => [qw(all static static_lib dynamic dynamic_lib)], clean => {'FILES' => 'libmylib$(LIB_EXT)'}, ); sub MY::top_targets { ' all :: static pure_all :: static static :: libmylib$(LIB_EXT) libmylib$(LIB_EXT): $(O_FILES) $(AR) cr libmylib$(LIB_EXT) $(O_FILES) $(RANLIB) libmylib$(LIB_EXT) '; } Make sure you use a tab and not spaces on the lines beginning with "$(AR)" and "$(RANLIB)". Make will not function properly if you use spaces. It has also been reported that the "cr" argument to $(AR) is unnecessary on Win32 systems. We will now create the main top-level Mytest2 files. Change to the directory above Mytest2 and run the following command: % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h This will print out a warning about overwriting Mytest2, but that's okay. Our files are stored in Mytest2/mylib, and will be untouched. The normal Makefile.PL that h2xs generates doesn't know about the mylib directory. We need to tell it that there is a subdirectory and that we will be generating a library in it. Let's add the argument MYEXTLIB to the WriteMakefile call so that it looks like this: WriteMakefile( 'NAME' => 'Mytest2', 'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION 'LIBS' => [''], # e.g., '-lm' 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING' 'INC' => '', # e.g., '-I/usr/include/other' 'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)', ); and then at the end add a subroutine (which will override the pre-existing subroutine). Remember to use a tab character to indent the line beginning with "cd"! sub MY::postamble { ' $(MYEXTLIB): mylib/Makefile cd mylib && $(MAKE) $(PASSTHRU) '; } Let's also fix the MANIFEST file so that it accurately reflects the contents of our extension. The single line that says "mylib" should be replaced by the following three lines: mylib/Makefile.PL mylib/mylib.c mylib/mylib.h To keep our namespace nice and unpolluted, edit the .pm file and change the variable C<@EXPORT> to C<@EXPORT_OK>. Finally, in the .xs file, edit the #include line to read: #include "mylib/mylib.h" And also add the following function definition to the end of the .xs file: double foo(a,b,c) int a long b const char * c OUTPUT: RETVAL Now we also need to create a typemap because the default Perl doesn't currently support the C<const char *> type. Include a new TYPEMAP section in your XS code before the above function: TYPEMAP: <<END; const char * T_PV END Now run perl on the top-level Makefile.PL. Notice that it also created a Makefile in the mylib directory. Run make and watch that it does cd into the mylib directory and run make in there as well. Now edit the Mytest2.t script and change the number of tests to "4", and add the following lines to the end of the script: is( &Mytest2::foo(1, 2, "Hello, world!"), 7 ); is( &Mytest2::foo(1, 2, "0.0"), 7 ); ok( abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 ); (When dealing with floating-point comparisons, it is best to not check for equality, but rather that the difference between the expected and actual result is below a certain amount (called epsilon) which is 0.01 in this case) Run "C<make test>" and all should be well. There are some warnings on missing tests for the Mytest2::mylib extension, but you can ignore them. =head2 What has happened here? Unlike previous examples, we've now run h2xs on a real include file. This has caused some extra goodies to appear in both the .pm and .xs files. =over 4 =item * In the .xs file, there's now a #include directive with the absolute path to the mylib.h header file. We changed this to a relative path so that we could move the extension directory if we wanted to. =item * There's now some new C code that's been added to the .xs file. The purpose of the C<constant> routine is to make the values that are #define'd in the header file accessible by the Perl script (by calling either C<TESTVAL> or C<&Mytest2::TESTVAL>). There's also some XS code to allow calls to the C<constant> routine. =item * The .pm file originally exported the name C<TESTVAL> in the C<@EXPORT> array. This could lead to name clashes. A good rule of thumb is that if the #define is only going to be used by the C routines themselves, and not by the user, they should be removed from the C<@EXPORT> array. Alternately, if you don't mind using the "fully qualified name" of a variable, you could move most or all of the items from the C<@EXPORT> array into the C<@EXPORT_OK> array. =item * If our include file had contained #include directives, these would not have been processed by h2xs. There is no good solution to this right now. =item * We've also told Perl about the library that we built in the mylib subdirectory. That required only the addition of the C<MYEXTLIB> variable to the WriteMakefile call and the replacement of the postamble subroutine to cd into the subdirectory and run make. The Makefile.PL for the library is a bit more complicated, but not excessively so. Again we replaced the postamble subroutine to insert our own code. This code simply specified that the library to be created here was a static archive library (as opposed to a dynamically loadable library) and provided the commands to build it. =back =head2 Anatomy of .xs file The .xs file of L<"EXAMPLE 4"> contained some new elements. To understand the meaning of these elements, pay attention to the line which reads MODULE = Mytest2 PACKAGE = Mytest2 Anything before this line is plain C code which describes which headers to include, and defines some convenience functions. No translations are performed on this part, apart from having embedded POD documentation skipped over (see L<perlpod>) it goes into the generated output C file as is. Anything after this line is the description of XSUB functions. These descriptions are translated by B<xsubpp> into C code which implements these functions using Perl calling conventions, and which makes these functions visible from Perl interpreter. Pay a special attention to the function C<constant>. This name appears twice in the generated .xs file: once in the first part, as a static C function, then another time in the second part, when an XSUB interface to this static C function is defined. This is quite typical for .xs files: usually the .xs file provides an interface to an existing C function. Then this C function is defined somewhere (either in an external library, or in the first part of .xs file), and a Perl interface to this function (i.e. "Perl glue") is described in the second part of .xs file. The situation in L<"EXAMPLE 1">, L<"EXAMPLE 2">, and L<"EXAMPLE 3">, when all the work is done inside the "Perl glue", is somewhat of an exception rather than the rule. =head2 Getting the fat out of XSUBs In L<"EXAMPLE 4"> the second part of .xs file contained the following description of an XSUB: double foo(a,b,c) int a long b const char * c OUTPUT: RETVAL Note that in contrast with L<"EXAMPLE 1">, L<"EXAMPLE 2"> and L<"EXAMPLE 3">, this description does not contain the actual I<code> for what is done during a call to Perl function foo(). To understand what is going on here, one can add a CODE section to this XSUB: double foo(a,b,c) int a long b const char * c CODE: RETVAL = foo(a,b,c); OUTPUT: RETVAL However, these two XSUBs provide almost identical generated C code: B<xsubpp> compiler is smart enough to figure out the C<CODE:> section from the first two lines of the description of XSUB. What about C<OUTPUT:> section? In fact, that is absolutely the same! The C<OUTPUT:> section can be removed as well, I<as far as C<CODE:> section or C<PPCODE:> section> is not specified: B<xsubpp> can see that it needs to generate a function call section, and will autogenerate the OUTPUT section too. Thus one can shortcut the XSUB to become: double foo(a,b,c) int a long b const char * c Can we do the same with an XSUB int is_even(input) int input CODE: RETVAL = (input % 2 == 0); OUTPUT: RETVAL of L<"EXAMPLE 2">? To do this, one needs to define a C function C<int is_even(int input)>. As we saw in L<Anatomy of .xs file>, a proper place for this definition is in the first part of .xs file. In fact a C function int is_even(int arg) { return (arg % 2 == 0); } is probably overkill for this. Something as simple as a C<#define> will do too: #define is_even(arg) ((arg) % 2 == 0) After having this in the first part of .xs file, the "Perl glue" part becomes as simple as int is_even(input) int input This technique of separation of the glue part from the workhorse part has obvious tradeoffs: if you want to change a Perl interface, you need to change two places in your code. However, it removes a lot of clutter, and makes the workhorse part independent from idiosyncrasies of Perl calling convention. (In fact, there is nothing Perl-specific in the above description, a different version of B<xsubpp> might have translated this to TCL glue or Python glue as well.) =head2 More about XSUB arguments With the completion of Example 4, we now have an easy way to simulate some real-life libraries whose interfaces may not be the cleanest in the world. We shall now continue with a discussion of the arguments passed to the B<xsubpp> compiler. When you specify arguments to routines in the .xs file, you are really passing three pieces of information for each argument listed. The first piece is the order of that argument relative to the others (first, second, etc). The second is the type of argument, and consists of the type declaration of the argument (e.g., int, char*, etc). The third piece is the calling convention for the argument in the call to the library function. While Perl passes arguments to functions by reference, C passes arguments by value; to implement a C function which modifies data of one of the "arguments", the actual argument of this C function would be a pointer to the data. Thus two C functions with declarations int string_length(char *s); int upper_case_char(char *cp); may have completely different semantics: the first one may inspect an array of chars pointed by s, and the second one may immediately dereference C<cp> and manipulate C<*cp> only (using the return value as, say, a success indicator). From Perl one would use these functions in a completely different manner. One conveys this info to B<xsubpp> by replacing C<*> before the argument by C<&>. C<&> means that the argument should be passed to a library function by its address. The above two function may be XSUB-ified as int string_length(s) char * s int upper_case_char(cp) char &cp For example, consider: int foo(a,b) char &a char * b The first Perl argument to this function would be treated as a char and assigned to the variable a, and its address would be passed into the function foo. The second Perl argument would be treated as a string pointer and assigned to the variable b. The I<value> of b would be passed into the function foo. The actual call to the function foo that B<xsubpp> generates would look like this: foo(&a, b); B<xsubpp> will parse the following function argument lists identically: char &a char&a char & a However, to help ease understanding, it is suggested that you place a "&" next to the variable name and away from the variable type), and place a "*" near the variable type, but away from the variable name (as in the call to foo above). By doing so, it is easy to understand exactly what will be passed to the C function; it will be whatever is in the "last column". You should take great pains to try to pass the function the type of variable it wants, when possible. It will save you a lot of trouble in the long run. =head2 The Argument Stack If we look at any of the C code generated by any of the examples except example 1, you will notice a number of references to ST(n), where n is usually 0. "ST" is actually a macro that points to the n'th argument on the argument stack. ST(0) is thus the first argument on the stack and therefore the first argument passed to the XSUB, ST(1) is the second argument, and so on. When you list the arguments to the XSUB in the .xs file, that tells B<xsubpp> which argument corresponds to which of the argument stack (i.e., the first one listed is the first argument, and so on). You invite disaster if you do not list them in the same order as the function expects them. The actual values on the argument stack are pointers to the values passed in. When an argument is listed as being an OUTPUT value, its corresponding value on the stack (i.e., ST(0) if it was the first argument) is changed. You can verify this by looking at the C code generated for Example 3. The code for the round() XSUB routine contains lines that look like this: double arg = (double)SvNV(ST(0)); /* Round the contents of the variable arg */ sv_setnv(ST(0), (double)arg); The arg variable is initially set by taking the value from ST(0), then is stored back into ST(0) at the end of the routine. XSUBs are also allowed to return lists, not just scalars. This must be done by manipulating stack values ST(0), ST(1), etc, in a subtly different way. See L<perlxs> for details. XSUBs are also allowed to avoid automatic conversion of Perl function arguments to C function arguments. See L<perlxs> for details. Some people prefer manual conversion by inspecting C<ST(i)> even in the cases when automatic conversion will do, arguing that this makes the logic of an XSUB call clearer. Compare with L<"Getting the fat out of XSUBs"> for a similar tradeoff of a complete separation of "Perl glue" and "workhorse" parts of an XSUB. While experts may argue about these idioms, a novice to Perl guts may prefer a way which is as little Perl-guts-specific as possible, meaning automatic conversion and automatic call generation, as in L<"Getting the fat out of XSUBs">. This approach has the additional benefit of protecting the XSUB writer from future changes to the Perl API. =head2 Extending your Extension Sometimes you might want to provide some extra methods or subroutines to assist in making the interface between Perl and your extension simpler or easier to understand. These routines should live in the .pm file. Whether they are automatically loaded when the extension itself is loaded or only loaded when called depends on where in the .pm file the subroutine definition is placed. You can also consult L<AutoLoader> for an alternate way to store and load your extra subroutines. =head2 Documenting your Extension There is absolutely no excuse for not documenting your extension. Documentation belongs in the .pm file. This file will be fed to pod2man, and the embedded documentation will be converted to the manpage format, then placed in the blib directory. It will be copied to Perl's manpage directory when the extension is installed. You may intersperse documentation and Perl code within the .pm file. In fact, if you want to use method autoloading, you must do this, as the comment inside the .pm file explains. See L<perlpod> for more information about the pod format. =head2 Installing your Extension Once your extension is complete and passes all its tests, installing it is quite simple: you simply run "make install". You will either need to have write permission into the directories where Perl is installed, or ask your system administrator to run the make for you. Alternately, you can specify the exact directory to place the extension's files by placing a "PREFIX=/destination/directory" after the make install. (or in between the make and install if you have a brain-dead version of make). This can be very useful if you are building an extension that will eventually be distributed to multiple systems. You can then just archive the files in the destination directory and distribute them to your destination systems. =head2 EXAMPLE 5 In this example, we'll do some more work with the argument stack. The previous examples have all returned only a single value. We'll now create an extension that returns an array. This extension is very Unix-oriented (struct statfs and the statfs system call). If you are not running on a Unix system, you can substitute for statfs any other function that returns multiple values, you can hard-code values to be returned to the caller (although this will be a bit harder to test the error case), or you can simply not do this example. If you change the XSUB, be sure to fix the test cases to match the changes. Return to the Mytest directory and add the following code to the end of Mytest.xs: void statfs(path) char * path INIT: int i; struct statfs buf; PPCODE: i = statfs(path, &buf); if (i == 0) { XPUSHs(sv_2mortal(newSVnv(buf.f_bavail))); XPUSHs(sv_2mortal(newSVnv(buf.f_bfree))); XPUSHs(sv_2mortal(newSVnv(buf.f_blocks))); XPUSHs(sv_2mortal(newSVnv(buf.f_bsize))); XPUSHs(sv_2mortal(newSVnv(buf.f_ffree))); XPUSHs(sv_2mortal(newSVnv(buf.f_files))); XPUSHs(sv_2mortal(newSVnv(buf.f_type))); } else { XPUSHs(sv_2mortal(newSVnv(errno))); } You'll also need to add the following code to the top of the .xs file, just after the include of "XSUB.h": #include <sys/vfs.h> Also add the following code segment to Mytest.t while incrementing the "9" tests to "11": @a = &Mytest::statfs("/blech"); ok( scalar(@a) == 1 && $a[0] == 2 ); @a = &Mytest::statfs("/"); is( scalar(@a), 7 ); =head2 New Things in this Example This example added quite a few new concepts. We'll take them one at a time. =over 4 =item * The INIT: directive contains code that will be placed immediately after the argument stack is decoded. C does not allow variable declarations at arbitrary locations inside a function, so this is usually the best way to declare local variables needed by the XSUB. (Alternatively, one could put the whole C<PPCODE:> section into braces, and put these declarations on top.) =item * This routine also returns a different number of arguments depending on the success or failure of the call to statfs. If there is an error, the error number is returned as a single-element array. If the call is successful, then a 7-element array is returned. Since only one argument is passed into this function, we need room on the stack to hold the 7 values which may be returned. We do this by using the PPCODE: directive, rather than the CODE: directive. This tells B<xsubpp> that we will be managing the return values that will be put on the argument stack by ourselves. =item * When we want to place values to be returned to the caller onto the stack, we use the series of macros that begin with "XPUSH". There are five different versions, for placing integers, unsigned integers, doubles, strings, and Perl scalars on the stack. In our example, we placed a Perl scalar onto the stack. (In fact this is the only macro which can be used to return multiple values.) The XPUSH* macros will automatically extend the return stack to prevent it from being overrun. You push values onto the stack in the order you want them seen by the calling program. =item * The values pushed onto the return stack of the XSUB are actually mortal SV's. They are made mortal so that once the values are copied by the calling program, the SV's that held the returned values can be deallocated. If they were not mortal, then they would continue to exist after the XSUB routine returned, but would not be accessible. This is a memory leak. =item * If we were interested in performance, not in code compactness, in the success branch we would not use C<XPUSHs> macros, but C<PUSHs> macros, and would pre-extend the stack before pushing the return values: EXTEND(SP, 7); The tradeoff is that one needs to calculate the number of return values in advance (though overextending the stack will not typically hurt anything but memory consumption). Similarly, in the failure branch we could use C<PUSHs> I<without> extending the stack: the Perl function reference comes to an XSUB on the stack, thus the stack is I<always> large enough to take one return value. =back =head2 EXAMPLE 6 In this example, we will accept a reference to an array as an input parameter, and return a reference to an array of hashes. This will demonstrate manipulation of complex Perl data types from an XSUB. This extension is somewhat contrived. It is based on the code in the previous example. It calls the statfs function multiple times, accepting a reference to an array of filenames as input, and returning a reference to an array of hashes containing the data for each of the filesystems. Return to the Mytest directory and add the following code to the end of Mytest.xs: SV * multi_statfs(paths) SV * paths INIT: AV * results; I32 numpaths = 0; int i, n; struct statfs buf; SvGETMAGIC(paths); if ((!SvROK(paths)) || (SvTYPE(SvRV(paths)) != SVt_PVAV) || ((numpaths = av_len((AV *)SvRV(paths))) < 0)) { XSRETURN_UNDEF; } results = (AV *)sv_2mortal((SV *)newAV()); CODE: for (n = 0; n <= numpaths; n++) { HV * rh; STRLEN l; char * fn = SvPV(*av_fetch((AV *)SvRV(paths), n, 0), l); i = statfs(fn, &buf); if (i != 0) { av_push(results, newSVnv(errno)); continue; } rh = (HV *)sv_2mortal((SV *)newHV()); hv_store(rh, "f_bavail", 8, newSVnv(buf.f_bavail), 0); hv_store(rh, "f_bfree", 7, newSVnv(buf.f_bfree), 0); hv_store(rh, "f_blocks", 8, newSVnv(buf.f_blocks), 0); hv_store(rh, "f_bsize", 7, newSVnv(buf.f_bsize), 0); hv_store(rh, "f_ffree", 7, newSVnv(buf.f_ffree), 0); hv_store(rh, "f_files", 7, newSVnv(buf.f_files), 0); hv_store(rh, "f_type", 6, newSVnv(buf.f_type), 0); av_push(results, newRV((SV *)rh)); } RETVAL = newRV((SV *)results); OUTPUT: RETVAL And add the following code to Mytest.t, while incrementing the "11" tests to "13": $results = Mytest::multi_statfs([ '/', '/blech' ]); ok( ref $results->[0] ); ok( ! ref $results->[1] ); =head2 New Things in this Example There are a number of new concepts introduced here, described below: =over 4 =item * This function does not use a typemap. Instead, we declare it as accepting one SV* (scalar) parameter, and returning an SV* value, and we take care of populating these scalars within the code. Because we are only returning one value, we don't need a C<PPCODE:> directive - instead, we use C<CODE:> and C<OUTPUT:> directives. =item * When dealing with references, it is important to handle them with caution. The C<INIT:> block first calls SvGETMAGIC(paths), in case paths is a tied variable. Then it checks that C<SvROK> returns true, which indicates that paths is a valid reference. (Simply checking C<SvROK> won't trigger FETCH on a tied variable.) It then verifies that the object referenced by paths is an array, using C<SvRV> to dereference paths, and C<SvTYPE> to discover its type. As an added test, it checks that the array referenced by paths is non-empty, using the C<av_len> function (which returns -1 if the array is empty). The XSRETURN_UNDEF macro is used to abort the XSUB and return the undefined value whenever all three of these conditions are not met. =item * We manipulate several arrays in this XSUB. Note that an array is represented internally by an AV* pointer. The functions and macros for manipulating arrays are similar to the functions in Perl: C<av_len> returns the highest index in an AV*, much like $#array; C<av_fetch> fetches a single scalar value from an array, given its index; C<av_push> pushes a scalar value onto the end of the array, automatically extending the array as necessary. Specifically, we read pathnames one at a time from the input array, and store the results in an output array (results) in the same order. If statfs fails, the element pushed onto the return array is the value of errno after the failure. If statfs succeeds, though, the value pushed onto the return array is a reference to a hash containing some of the information in the statfs structure. As with the return stack, it would be possible (and a small performance win) to pre-extend the return array before pushing data into it, since we know how many elements we will return: av_extend(results, numpaths); =item * We are performing only one hash operation in this function, which is storing a new scalar under a key using C<hv_store>. A hash is represented by an HV* pointer. Like arrays, the functions for manipulating hashes from an XSUB mirror the functionality available from Perl. See L<perlguts> and L<perlapi> for details. =item * To create a reference, we use the C<newRV> function. Note that you can cast an AV* or an HV* to type SV* in this case (and many others). This allows you to take references to arrays, hashes and scalars with the same function. Conversely, the C<SvRV> function always returns an SV*, which may need to be cast to the appropriate type if it is something other than a scalar (check with C<SvTYPE>). =item * At this point, xsubpp is doing very little work - the differences between Mytest.xs and Mytest.c are minimal. =back =head2 EXAMPLE 7 (Coming Soon) XPUSH args AND set RETVAL AND assign return value to array =head2 EXAMPLE 8 (Coming Soon) Setting $! =head2 EXAMPLE 9 Passing open files to XSes You would think passing files to an XS is difficult, with all the typeglobs and stuff. Well, it isn't. Suppose that for some strange reason we need a wrapper around the standard C library function C<fputs()>. This is all we need: #define PERLIO_NOT_STDIO 0 #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include <stdio.h> int fputs(s, stream) char * s FILE * stream The real work is done in the standard typemap. B<But> you loose all the fine stuff done by the perlio layers. This calls the stdio function C<fputs()>, which knows nothing about them. The standard typemap offers three variants of PerlIO *: C<InputStream> (T_IN), C<InOutStream> (T_INOUT) and C<OutputStream> (T_OUT). A bare C<PerlIO *> is considered a T_INOUT. If it matters in your code (see below for why it might) #define or typedef one of the specific names and use that as the argument or result type in your XS file. The standard typemap does not contain PerlIO * before perl 5.7, but it has the three stream variants. Using a PerlIO * directly is not backwards compatible unless you provide your own typemap. For streams coming I<from> perl the main difference is that C<OutputStream> will get the output PerlIO * - which may make a difference on a socket. Like in our example... For streams being handed I<to> perl a new file handle is created (i.e. a reference to a new glob) and associated with the PerlIO * provided. If the read/write state of the PerlIO * is not correct then you may get errors or warnings from when the file handle is used. So if you opened the PerlIO * as "w" it should really be an C<OutputStream> if open as "r" it should be an C<InputStream>. Now, suppose you want to use perlio layers in your XS. We'll use the perlio C<PerlIO_puts()> function as an example. In the C part of the XS file (above the first MODULE line) you have #define OutputStream PerlIO * or typedef PerlIO * OutputStream; And this is the XS code: int perlioputs(s, stream) char * s OutputStream stream CODE: RETVAL = PerlIO_puts(stream, s); OUTPUT: RETVAL We have to use a C<CODE> section because C<PerlIO_puts()> has the arguments reversed compared to C<fputs()>, and we want to keep the arguments the same. Wanting to explore this thoroughly, we want to use the stdio C<fputs()> on a PerlIO *. This means we have to ask the perlio system for a stdio C<FILE *>: int perliofputs(s, stream) char * s OutputStream stream PREINIT: FILE *fp = PerlIO_findFILE(stream); CODE: if (fp != (FILE*) 0) { RETVAL = fputs(s, fp); } else { RETVAL = -1; } OUTPUT: RETVAL Note: C<PerlIO_findFILE()> will search the layers for a stdio layer. If it can't find one, it will call C<PerlIO_exportFILE()> to generate a new stdio C<FILE>. Please only call C<PerlIO_exportFILE()> if you want a I<new> C<FILE>. It will generate one on each call and push a new stdio layer. So don't call it repeatedly on the same file. C<PerlIO_findFILE()> will retrieve the stdio layer once it has been generated by C<PerlIO_exportFILE()>. This applies to the perlio system only. For versions before 5.7, C<PerlIO_exportFILE()> is equivalent to C<PerlIO_findFILE()>. =head2 Troubleshooting these Examples As mentioned at the top of this document, if you are having problems with these example extensions, you might see if any of these help you. =over 4 =item * In versions of 5.002 prior to the gamma version, the test script in Example 1 will not function properly. You need to change the "use lib" line to read: use lib './blib'; =item * In versions of 5.002 prior to version 5.002b1h, the test.pl file was not automatically created by h2xs. This means that you cannot say "make test" to run the test script. You will need to add the following line before the "use extension" statement: use lib './blib'; =item * In versions 5.000 and 5.001, instead of using the above line, you will need to use the following line: BEGIN { unshift(@INC, "./blib") } =item * This document assumes that the executable named "perl" is Perl version 5. Some systems may have installed Perl version 5 as "perl5". =back =head1 See also For more information, consult L<perlguts>, L<perlapi>, L<perlxs>, L<perlmod>, and L<perlpod>. =head1 Author Jeff Okamoto <F<okamoto@corp.hp.com>> Reviewed and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, and Tim Bunce. PerlIO material contributed by Lupe Christoph, with some clarification by Nick Ing-Simmons. Changes for h2xs as of Perl 5.8.x by Renee Baecker =head2 Last Changed 2012-01-20 PK PU�\�Ӷ�, , perlcommunity.podnu �[��� =head1 NAME perlcommunity - a brief overview of the Perl community =head1 DESCRIPTION This document aims to provide an overview of the vast perl community, which is far too large and diverse to provide a detailed listing. If any specific niche has been forgotten, it is not meant as an insult but an omission for the sake of brevity. The Perl community is as diverse as Perl, and there is a large amount of evidence that the Perl users apply TMTOWTDI to all endeavors, not just programming. From websites, to IRC, to mailing lists, there is more than one way to get involved in the community. =head2 Where to Find the Community There is a central directory for the Perl community: L<http://perl.org> maintained by the Perl Foundation (L<http://www.perlfoundation.org/>), which tracks and provides services for a variety of other community sites. =head2 Mailing Lists and Newsgroups Perl runs on e-mail; there is no doubt about it. The Camel book was originally written mostly over e-mail and today Perl's development is co-ordinated through mailing lists. The largest repository of Perl mailing lists is located at L<http://lists.perl.org>. Most Perl-related projects set up mailing lists for both users and contributors. If you don't see a certain project listed at L<http://lists.perl.org>, check the particular website for that project. Most mailing lists are archived at L<http://nntp.perl.org/>. There are also plenty of Perl related newsgroups located under C<comp.lang.perl.*>. =head2 IRC The Perl community has a rather large IRC presence. For starters, it has its own IRC network, L<irc://irc.perl.org>. General (not help-oriented) chat can be found at L<irc://irc.perl.org/#perl>. Many other more specific chats are also hosted on the network. Information about irc.perl.org is located on the network's website: L<http://www.irc.perl.org>. For a more help-oriented #perl, check out L<irc://irc.freenode.net/#perl>. Perl 6 development also has a presence in L<irc://irc.freenode.net/#perl6>. Most Perl-related channels will be kind enough to point you in the right direction if you ask nicely. Any large IRC network (Dalnet, EFnet) is also likely to have a #perl channel, with varying activity levels. =head2 Websites Perl websites come in a variety of forms, but they fit into two large categories: forums and news websites. There are many Perl-related websites, so only a few of the community's largest are mentioned here. =head3 News sites =over 4 =item L<http://perl.com/> Run by O'Reilly Media (the publisher of L<the Camel Book|perlbook>, among other Perl-related literature), perl.com provides current Perl news, articles, and resources for Perl developers as well as a directory of other useful websites. =item L<http://use.perl.org/> use Perl; provides a slashdot-style Perl news website covering all things Perl, from minutes of the meetings of the Perl 6 Design team to conference announcements with (ir)relevant discussion. =back =head3 Forums =over 4 =item L<http://www.perlmonks.org/> PerlMonks is one of the largest Perl forums, and describes itself as "A place for individuals to polish, improve, and showcase their Perl skills." and "A community which allows everyone to grow and learn from each other." =back =head2 User Groups Many cities around the world have local Perl Mongers chapters. A Perl Mongers chapter is a local user group which typically holds regular in-person meetings, both social and technical; helps organize local conferences, workshops, and hackathons; and provides a mailing list or other continual contact method for its members to keep in touch. To find your local Perl Mongers (or PM as they're commonly abbreviated) group check the international Perl Mongers directory at L<http://www.pm.org/>. =head2 Workshops Perl workshops are, as the name might suggest, workshops where Perl is taught in a variety of ways. At the workshops, subjects range from a beginner's introduction (such as the Pittsburgh Perl Workshop's "Zero To Perl") to much more advanced subjects. There are several great resources for locating workshops: the L<websites|"Websites"> mentioned above, the L<calendar|"Calendar of Perl Events"> mentioned below, and the YAPC Europe website, L<http://www.yapceurope.org/>, which is probably the best resource for European Perl events. =head2 Hackathons Hackathons are a very different kind of gathering where Perl hackers gather to do just that, hack nonstop for an extended (several day) period on a specific project or projects. Information about hackathons can be located in the same place as information about L<workshops|"Workshops"> as well as in L<irc://irc.perl.org/#perl>. If you have never been to a hackathon, here are a few basic things you need to know before attending: have a working laptop and know how to use it; check out the involved projects beforehand; have the necessary version control client; and bring backup equipment (an extra LAN cable, additional power strips, etc.) because someone will forget. =head2 Conventions Perl has two major annual conventions: The Perl Conference (now part of OSCON), put on by O'Reilly, and Yet Another Perl Conference or YAPC (pronounced yap-see), which is localized into several regional YAPCs (North America, Europe, Asia) in a stunning grassroots display by the Perl community. For more information about either conference, check out their respective web pages: OSCON L<http://conferences.oreillynet.com/>; YAPC L<http://www.yapc.org>. A relatively new conference franchise with a large Perl portion is the Open Source Developers Conference or OSDC. First held in Australia it has recently also spread to Israel and France. More information can be found at: L<http://www.osdc.com.au/> for Australia, L<http://www.osdc.org.il> for Israel, and L<http://www.osdc.fr/> for France. =head2 Calendar of Perl Events The Perl Review, L<http://www.theperlreview.com> maintains a website and Google calendar (L<http://www.theperlreview.com/community_calendar>) for tracking workshops, hackathons, Perl Mongers meetings, and other events. Views of this calendar are at L<http://www.perl.org/events.html> and L<http://www.yapc.org>. Not every event or Perl Mongers group is on that calendar, so don't lose heart if you don't see yours posted. To have your event or group listed, contact brian d foy (brian@theperlreview.com). =head1 AUTHOR Edgar "Trizor" Bering <trizor@gmail.com> =cut PK PU�\�#�Gq Gq perlref.podnu �[��� =head1 NAME X<reference> X<pointer> X<data structure> X<structure> X<struct> perlref - Perl references and nested data structures =head1 NOTE This is complete documentation about all aspects of references. For a shorter, tutorial introduction to just the essential features, see L<perlreftut>. =head1 DESCRIPTION Before release 5 of Perl it was difficult to represent complex data structures, because all references had to be symbolic--and even then it was difficult to refer to a variable instead of a symbol table entry. Perl now not only makes it easier to use symbolic references to variables, but also lets you have "hard" references to any piece of data or code. Any scalar may hold a hard reference. Because arrays and hashes contain scalars, you can now easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays of hashes of functions, and so on. Hard references are smart--they keep track of reference counts for you, automatically freeing the thing referred to when its reference count goes to zero. (Reference counts for values in self-referential or cyclic data structures may not go to zero without a little help; see L</"Circular References"> for a detailed explanation.) If that thing happens to be an object, the object is destructed. See L<perlobj> for more about objects. (In a sense, everything in Perl is an object, but we usually reserve the word for references to objects that have been officially "blessed" into a class package.) Symbolic references are names of variables or other objects, just as a symbolic link in a Unix filesystem contains merely the name of a file. The C<*glob> notation is something of a symbolic reference. (Symbolic references are sometimes called "soft references", but please don't call them that; references are confusing enough without useless synonyms.) X<reference, symbolic> X<reference, soft> X<symbolic reference> X<soft reference> In contrast, hard references are more like hard links in a Unix file system: They are used to access an underlying object without concern for what its (other) name is. When the word "reference" is used without an adjective, as in the following paragraph, it is usually talking about a hard reference. X<reference, hard> X<hard reference> References are easy to use in Perl. There is just one overriding principle: Perl does no implicit referencing or dereferencing. When a scalar is holding a reference, it always behaves as a simple scalar. It doesn't magically start being an array or hash or subroutine; you have to tell it explicitly to do so, by dereferencing it. References are easy to use in Perl. There is just one overriding principle: in general, Perl does no implicit referencing or dereferencing. When a scalar is holding a reference, it always behaves as a simple scalar. It doesn't magically start being an array or hash or subroutine; you have to tell it explicitly to do so, by dereferencing it. That said, be aware that Perl version 5.14 introduces an exception to the rule, for syntactic convenience. Experimental array and hash container function behavior allows array and hash references to be handled by Perl as if they had been explicitly syntactically dereferenced. See L<perl5140delta/"Syntactical Enhancements"> and L<perlfunc> for details. =head2 Making References X<reference, creation> X<referencing> References can be created in several ways. =over 4 =item 1. X<\> X<backslash> By using the backslash operator on a variable, subroutine, or value. (This works much like the & (address-of) operator in C.) This typically creates I<another> reference to a variable, because there's already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned. Here are some examples: $scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&handler; $globref = \*foo; It isn't possible to create a true reference to an IO handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry. But see the explanation of the C<*foo{THING}> syntax below. However, you can still use type globs and globrefs as though they were IO handles. =item 2. X<array, anonymous> X<[> X<[]> X<square bracket> X<bracket, square> X<arrayref> X<array reference> X<reference, array> A reference to an anonymous array can be created using square brackets: $arrayref = [1, 2, ['a', 'b', 'c']]; Here we've created a reference to an anonymous array of three elements whose final element is itself a reference to another anonymous array of three elements. (The multidimensional syntax described later can be used to access this. For example, after the above, C<< $arrayref->[2][1] >> would have the value "b".) Taking a reference to an enumerated list is not the same as using square brackets--instead it's the same as creating a list of references! @list = (\$a, \@b, \%c); @list = \($a, @b, %c); # same thing! As a special case, C<\(@foo)> returns a list of references to the contents of C<@foo>, not a reference to C<@foo> itself. Likewise for C<%foo>, except that the key references are to copies (since the keys are just strings rather than full-fledged scalars). =item 3. X<hash, anonymous> X<{> X<{}> X<curly bracket> X<bracket, curly> X<brace> X<hashref> X<hash reference> X<reference, hash> A reference to an anonymous hash can be created using curly brackets: $hashref = { 'Adam' => 'Eve', 'Clyde' => 'Bonnie', }; Anonymous hash and array composers like these can be intermixed freely to produce as complicated a structure as you want. The multidimensional syntax described below works for these too. The values above are literals, but variables and expressions would work just as well, because assignment operators in Perl (even within local() or my()) are executable statements, not compile-time declarations. Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a C<+> or a C<return> in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle. For example, if you wanted a function to make a new hash and return a reference to it, you have these options: sub hashem { { @_ } } # silently wrong sub hashem { +{ @_ } } # ok sub hashem { return { @_ } } # ok On the other hand, if you want the other meaning, you can do this: sub showem { { @_ } } # ambiguous (currently ok, but may change) sub showem { {; @_ } } # ok sub showem { { return @_ } } # ok The leading C<+{> and C<{;> always serve to disambiguate the expression to mean either the HASH reference, or the BLOCK. =item 4. X<subroutine, anonymous> X<subroutine, reference> X<reference, subroutine> X<scope, lexical> X<closure> X<lexical> X<lexical scope> A reference to an anonymous subroutine can be created by using C<sub> without a subname: $coderef = sub { print "Boink!\n" }; Note the semicolon. Except for the code inside not being immediately executed, a C<sub {}> is not so much a declaration as it is an operator, like C<do{}> or C<eval{}>. (However, no matter how many times you execute that particular line (unless you're in an C<eval("...")>), $coderef will still have a reference to the I<same> anonymous subroutine.) Anonymous subroutines act as closures with respect to my() variables, that is, variables lexically visible within the current scope. Closure is a notion out of the Lisp world that says if you define an anonymous function in a particular lexical context, it pretends to run in that context even when it's called outside the context. In human terms, it's a funny way of passing arguments to a subroutine when you define it as well as when you call it. It's useful for setting up little bits of code to run later, such as callbacks. You can even do object-oriented stuff with it, though Perl already provides a different mechanism to do that--see L<perlobj>. You might also think of closure as a way to write a subroutine template without using eval(). Here's a small example of how closures work: sub newprint { my $x = shift; return sub { my $y = shift; print "$x, $y!\n"; }; } $h = newprint("Howdy"); $g = newprint("Greetings"); # Time passes... &$h("world"); &$g("earthlings"); This prints Howdy, world! Greetings, earthlings! Note particularly that $x continues to refer to the value passed into newprint() I<despite> "my $x" having gone out of scope by the time the anonymous subroutine runs. That's what a closure is all about. This applies only to lexical variables, by the way. Dynamic variables continue to work as they have always worked. Closure is not something that most Perl programmers need trouble themselves about to begin with. =item 5. X<constructor> X<new> References are often returned by special subroutines called constructors. Perl objects are just references to a special type of object that happens to know which package it's associated with. Constructors are just special subroutines that know how to create that association. They do so by starting with an ordinary reference, and it remains an ordinary reference even while it's also being an object. Constructors are often named C<new()>. You I<can> call them indirectly: $objref = new Doggie( Tail => 'short', Ears => 'long' ); But that can produce ambiguous syntax in certain cases, so it's often better to use the direct method invocation approach: $objref = Doggie->new(Tail => 'short', Ears => 'long'); use Term::Cap; $terminal = Term::Cap->Tgetent( { OSPEED => 9600 }); use Tk; $main = MainWindow->new(); $menubar = $main->Frame(-relief => "raised", -borderwidth => 2) =item 6. X<autovivification> References of the appropriate type can spring into existence if you dereference them in a context that assumes they exist. Because we haven't talked about dereferencing yet, we can't show you any examples yet. =item 7. X<*foo{THING}> X<*> A reference can be created by using a special syntax, lovingly known as the *foo{THING} syntax. *foo{THING} returns a reference to the THING slot in *foo (which is the symbol table entry which holds everything known as foo). $scalarref = *foo{SCALAR}; $arrayref = *ARGV{ARRAY}; $hashref = *ENV{HASH}; $coderef = *handler{CODE}; $ioref = *STDIN{IO}; $globref = *foo{GLOB}; $formatref = *foo{FORMAT}; All of these are self-explanatory except for C<*foo{IO}>. It returns the IO handle, used for file handles (L<perlfunc/open>), sockets (L<perlfunc/socket> and L<perlfunc/socketpair>), and directory handles (L<perlfunc/opendir>). For compatibility with previous versions of Perl, C<*foo{FILEHANDLE}> is a synonym for C<*foo{IO}>, though it is deprecated as of 5.8.0. If deprecation warnings are in effect, it will warn of its use. C<*foo{THING}> returns undef if that particular THING hasn't been used yet, except in the case of scalars. C<*foo{SCALAR}> returns a reference to an anonymous scalar if $foo hasn't been used yet. This might change in a future release. C<*foo{IO}> is an alternative to the C<*HANDLE> mechanism given in L<perldata/"Typeglobs and Filehandles"> for passing filehandles into or out of subroutines, or storing into larger data structures. Its disadvantage is that it won't create a new filehandle for you. Its advantage is that you have less risk of clobbering more than you want to with a typeglob assignment. (It still conflates file and directory handles, though.) However, if you assign the incoming value to a scalar instead of a typeglob as we do in the examples below, there's no risk of that happening. splutter(*STDOUT); # pass the whole glob splutter(*STDOUT{IO}); # pass both file and dir handles sub splutter { my $fh = shift; print $fh "her um well a hmmm\n"; } $rec = get_rec(*STDIN); # pass the whole glob $rec = get_rec(*STDIN{IO}); # pass both file and dir handles sub get_rec { my $fh = shift; return scalar <$fh>; } =back =head2 Using References X<reference, use> X<dereferencing> X<dereference> That's it for creating references. By now you're probably dying to know how to use references to get back to your long-lost data. There are several basic methods. =over 4 =item 1. Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type: $bar = $$scalarref; push(@$arrayref, $filename); $$arrayref[0] = "January"; $$hashref{"KEY"} = "VALUE"; &$coderef(1,2,3); print $globref "output\n"; It's important to understand that we are specifically I<not> dereferencing C<$arrayref[0]> or C<$hashref{"KEY"}> there. The dereference of the scalar variable happens I<before> it does any key lookups. Anything more complicated than a simple scalar variable must use methods 2 or 3 below. However, a "simple scalar" includes an identifier that itself uses method 1 recursively. Therefore, the following prints "howdy". $refrefref = \\\"howdy"; print $$$$refrefref; =item 2. Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a BLOCK returning a reference of the correct type. In other words, the previous examples could be written like this: $bar = ${$scalarref}; push(@{$arrayref}, $filename); ${$arrayref}[0] = "January"; ${$hashref}{"KEY"} = "VALUE"; &{$coderef}(1,2,3); $globref->print("output\n"); # iff IO::Handle is loaded Admittedly, it's a little silly to use the curlies in this case, but the BLOCK can contain any arbitrary expression, in particular, subscripted expressions: &{ $dispatch{$index} }(1,2,3); # call correct routine Because of being able to omit the curlies for the simple case of C<$$x>, people often make the mistake of viewing the dereferencing symbols as proper operators, and wonder about their precedence. If they were, though, you could use parentheses instead of braces. That's not the case. Consider the difference below; case 0 is a short-hand version of case 1, I<not> case 2: $$hashref{"KEY"} = "VALUE"; # CASE 0 ${$hashref}{"KEY"} = "VALUE"; # CASE 1 ${$hashref{"KEY"}} = "VALUE"; # CASE 2 ${$hashref->{"KEY"}} = "VALUE"; # CASE 3 Case 2 is also deceptive in that you're accessing a variable called %hashref, not dereferencing through $hashref to the hash it's presumably referencing. That would be case 3. =item 3. Subroutine calls and lookups of individual array elements arise often enough that it gets cumbersome to use method 2. As a form of syntactic sugar, the examples for method 2 may be written: $arrayref->[0] = "January"; # Array element $hashref->{"KEY"} = "VALUE"; # Hash element $coderef->(1,2,3); # Subroutine call The left side of the arrow can be any expression returning a reference, including a previous dereference. Note that C<$array[$x]> is I<not> the same thing as C<< $array->[$x] >> here: $array[$x]->{"foo"}->[0] = "January"; This is one of the cases we mentioned earlier in which references could spring into existence when in an lvalue context. Before this statement, C<$array[$x]> may have been undefined. If so, it's automatically defined with a hash reference so that we can look up C<{"foo"}> in it. Likewise C<< $array[$x]->{"foo"} >> will automatically get defined with an array reference so that we can look up C<[0]> in it. This process is called I<autovivification>. One more thing here. The arrow is optional I<between> brackets subscripts, so you can shrink the above down to $array[$x]{"foo"}[0] = "January"; Which, in the degenerate case of using only ordinary arrays, gives you multidimensional arrays just like C's: $score[$x][$y][$z] += 42; Well, okay, not entirely like C's arrays, actually. C doesn't know how to grow its arrays on demand. Perl does. =item 4. If a reference happens to be a reference to an object, then there are probably methods to access the things referred to, and you should probably stick to those methods unless you're in the class package that defines the object's methods. In other words, be nice, and don't violate the object's encapsulation without a very good reason. Perl does not enforce encapsulation. We are not totalitarians here. We do expect some basic civility though. =back Using a string or number as a reference produces a symbolic reference, as explained above. Using a reference as a number produces an integer representing its storage location in memory. The only useful thing to be done with this is to compare two references numerically to see whether they refer to the same location. X<reference, numeric context> if ($ref1 == $ref2) { # cheap numeric compare of references print "refs 1 and 2 refer to the same thing\n"; } Using a reference as a string produces both its referent's type, including any package blessing as described in L<perlobj>, as well as the numeric address expressed in hex. The ref() operator returns just the type of thing the reference is pointing to, without the address. See L<perlfunc/ref> for details and examples of its use. X<reference, string context> The bless() operator may be used to associate the object a reference points to with a package functioning as an object class. See L<perlobj>. A typeglob may be dereferenced the same way a reference can, because the dereference syntax always indicates the type of reference desired. So C<${*foo}> and C<${\$foo}> both indicate the same scalar variable. Here's a trick for interpolating a subroutine call into a string: print "My sub returned @{[mysub(1,2,3)]} that time.\n"; The way it works is that when the C<@{...}> is seen in the double-quoted string, it's evaluated as a block. The block creates a reference to an anonymous array containing the results of the call to C<mysub(1,2,3)>. So the whole block returns a reference to an array, which is then dereferenced by C<@{...}> and stuck into the double-quoted string. This chicanery is also useful for arbitrary expressions: print "That yields @{[$n + 5]} widgets\n"; Similarly, an expression that returns a reference to a scalar can be dereferenced via C<${...}>. Thus, the above expression may be written as: print "That yields ${\($n + 5)} widgets\n"; =head2 Circular References X<circular reference> X<reference, circular> It is possible to create a "circular reference" in Perl, which can lead to memory leaks. A circular reference occurs when two references contain a reference to each other, like this: my $foo = {}; my $bar = { foo => $foo }; $foo->{bar} = $bar; You can also create a circular reference with a single variable: my $foo; $foo = \$foo; In this case, the reference count for the variables will never reach 0, and the references will never be garbage-collected. This can lead to memory leaks. Because objects in Perl are implemented as references, it's possible to have circular references with objects as well. Imagine a TreeNode class where each node references its parent and child nodes. Any node with a parent will be part of a circular reference. You can break circular references by creating a "weak reference". A weak reference does not increment the reference count for a variable, which means that the object can go out of scope and be destroyed. You can weaken a reference with the C<weaken> function exported by the L<Scalar::Util> module. Here's how we can make the first example safer: use Scalar::Util 'weaken'; my $foo = {}; my $bar = { foo => $foo }; $foo->{bar} = $bar; weaken $foo->{bar}; The reference from C<$foo> to C<$bar> has been weakened. When the C<$bar> variable goes out of scope, it will be garbage-collected. The next time you look at the value of the C<< $foo->{bar} >> key, it will be C<undef>. This action at a distance can be confusing, so you should be careful with your use of weaken. You should weaken the reference in the variable that will go out of scope I<first>. That way, the longer-lived variable will contain the expected reference until it goes out of scope. =head2 Symbolic references X<reference, symbolic> X<reference, soft> X<symbolic reference> X<soft reference> We said that references spring into existence as necessary if they are undefined, but we didn't say what happens if a value used as a reference is already defined, but I<isn't> a hard reference. If you use it as a reference, it'll be treated as a symbolic reference. That is, the value of the scalar is taken to be the I<name> of a variable, rather than a direct link to a (possibly) anonymous value. People frequently expect it to work like this. So it does. $name = "foo"; $$name = 1; # Sets $foo ${$name} = 2; # Sets $foo ${$name x 2} = 3; # Sets $foofoo $name->[0] = 4; # Sets $foo[0] @$name = (); # Clears @foo &$name(); # Calls &foo() (as in Perl 4) $pack = "THAT"; ${"${pack}::$name"} = 5; # Sets $THAT::foo without eval This is powerful, and slightly dangerous, in that it's possible to intend (with the utmost sincerity) to use a hard reference, and accidentally use a symbolic reference instead. To protect against that, you can say use strict 'refs'; and then only hard references will be allowed for the rest of the enclosing block. An inner block may countermand that with no strict 'refs'; Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with my()) aren't in a symbol table, and thus are invisible to this mechanism. For example: local $value = 10; $ref = "value"; { my $value = 20; print $$ref; } This will still print 10, not 20. Remember that local() affects package variables, which are all "global" to the package. =head2 Not-so-symbolic references Since Perl verion 5.001, brackets around a symbolic reference can simply serve to isolate an identifier or variable name from the rest of an expression, just as they always have within a string. For example, $push = "pop on "; print "${push}over"; has always meant to print "pop on over", even though push is a reserved word. In 5.001, this was generalized to work the same without the enclosing double quotes, so that print ${push} . "over"; and even print ${ push } . "over"; will have the same effect. (This would have been a syntax error in Perl 5.000, though Perl 4 allowed it in the spaceless form.) This construct is I<not> considered to be a symbolic reference when you're using strict refs: use strict 'refs'; ${ bareword }; # Okay, means $bareword. ${ "bareword" }; # Error, symbolic reference. Similarly, because of all the subscripting that is done using single words, the same rule applies to any bareword that is used for subscripting a hash. So now, instead of writing $array{ "aaa" }{ "bbb" }{ "ccc" } you can write just $array{ aaa }{ bbb }{ ccc } and not worry about whether the subscripts are reserved words. In the rare event that you do wish to do something like $array{ shift } you can force interpretation as a reserved word by adding anything that makes it more than a bareword: $array{ shift() } $array{ +shift } $array{ shift @_ } The C<use warnings> pragma or the B<-w> switch will warn you if it interprets a reserved word as a string. But it will no longer warn you about using lowercase words, because the string is effectively quoted. =head2 Pseudo-hashes: Using an array as a hash X<pseudo-hash> X<pseudo hash> X<pseudohash> Pseudo-hashes have been removed from Perl. The 'fields' pragma remains available. =head2 Function Templates X<scope, lexical> X<closure> X<lexical> X<lexical scope> X<subroutine, nested> X<sub, nested> X<subroutine, local> X<sub, local> As explained above, an anonymous function with access to the lexical variables visible when that function was compiled, creates a closure. It retains access to those variables even though it doesn't get run until later, such as in a signal handler or a Tk callback. Using a closure as a function template allows us to generate many functions that act similarly. Suppose you wanted functions named after the colors that generated HTML font changes for the various colors: print "Be ", red("careful"), "with that ", green("light"); The red() and green() functions would be similar. To create these, we'll assign a closure to a typeglob of the name of the function we're trying to build. @colors = qw(red blue green yellow orange purple violet); for my $name (@colors) { no strict 'refs'; # allow symbol table manipulation *$name = *{uc $name} = sub { "<FONT COLOR='$name'>@_</FONT>" }; } Now all those different functions appear to exist independently. You can call red(), RED(), blue(), BLUE(), green(), etc. This technique saves on both compile time and memory use, and is less error-prone as well, since syntax checks happen at compile time. It's critical that any variables in the anonymous subroutine be lexicals in order to create a proper closure. That's the reasons for the C<my> on the loop iteration variable. This is one of the only places where giving a prototype to a closure makes much sense. If you wanted to impose scalar context on the arguments of these functions (probably not a wise idea for this particular example), you could have written it this way instead: *$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" }; However, since prototype checking happens at compile time, the assignment above happens too late to be of much use. You could address this by putting the whole loop of assignments within a BEGIN block, forcing it to occur during compilation. Access to lexicals that change over time--like those in the C<for> loop above, basically aliases to elements from the surrounding lexical scopes-- only works with anonymous subs, not with named subroutines. Generally said, named subroutines do not nest properly and should only be declared in the main package scope. This is because named subroutines are created at compile time so their lexical variables get assigned to the parent lexicals from the first execution of the parent block. If a parent scope is entered a second time, its lexicals are created again, while the nested subs still reference the old ones. Anonymous subroutines get to capture each time you execute the C<sub> operator, as they are created on the fly. If you are accustomed to using nested subroutines in other programming languages with their own private variables, you'll have to work at it a bit in Perl. The intuitive coding of this type of thing incurs mysterious warnings about "will not stay shared" due to the reasons explained above. For example, this won't work: sub outer { my $x = $_[0] + 35; sub inner { return $x * 19 } # WRONG return $x + inner(); } A work-around is the following: sub outer { my $x = $_[0] + 35; local *inner = sub { return $x * 19 }; return $x + inner(); } Now inner() can only be called from within outer(), because of the temporary assignments of the anonymous subroutine. But when it does, it has normal access to the lexical variable $x from the scope of outer() at the time outer is invoked. This has the interesting effect of creating a function local to another function, something not normally supported in Perl. =head1 WARNING X<reference, string context> X<reference, use as hash key> You may not (usefully) use a reference as the key to a hash. It will be converted into a string: $x{ \$a } = $a; If you try to dereference the key, it won't do a hard dereference, and you won't accomplish what you're attempting. You might want to do something more like $r = \@a; $x{ $r } = $r; And then at least you can use the values(), which will be real refs, instead of the keys(), which won't. The standard Tie::RefHash module provides a convenient workaround to this. =head1 SEE ALSO Besides the obvious documents, source code can be instructive. Some pathological examples of the use of references can be found in the F<t/op/ref.t> regression test in the Perl source directory. See also L<perldsc> and L<perllol> for how to use references to create complex data structures, and L<perlootut> and L<perlobj> for how to use them to create objects. PK PU�\)�s7 7 perlfreebsd.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see pod/perlpod.pod) which is specifically designed to be readable as is. =head1 NAME perlfreebsd - Perl version 5 on FreeBSD systems =head1 DESCRIPTION This document describes various features of FreeBSD that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs. =head2 FreeBSD core dumps from readdir_r with ithreads When perl is configured to use ithreads, it will use re-entrant library calls in preference to non-re-entrant versions. There is a bug in FreeBSD's C<readdir_r> function in versions 4.5 and earlier that can cause a SEGV when reading large directories. A patch for FreeBSD libc is available (see http://www.freebsd.org/cgi/query-pr.cgi?pr=misc/30631 ) which has been integrated into FreeBSD 4.6. =head2 $^X doesn't always contain a full path in FreeBSD perl sets C<$^X> where possible to a full path by asking the operating system. On FreeBSD the full path of the perl interpreter is found by using C<sysctl> with C<KERN_PROC_PATHNAME> if that is supported, else by reading the symlink F</proc/curproc/file>. FreeBSD 7 and earlier has a bug where either approach sometimes returns an incorrect value (see http://www.freebsd.org/cgi/query-pr.cgi?pr=35703 ). In these cases perl will fall back to the old behaviour of using C's argv[0] value for C<$^X>. =head1 AUTHOR Nicholas Clark <nick@ccl4.org>, collating wisdom supplied by Slaven Rezic and Tim Bunce. Please report any errors, updates, or suggestions to F<perlbug@perl.org>. PK PU�\�Cx perl5123delta.podnu �[��� =encoding utf8 =head1 NAME perl5123delta - what is new for perl v5.12.3 =head1 DESCRIPTION This document describes differences between the 5.12.2 release and the 5.12.3 release. If you are upgrading from an earlier release such as 5.12.1, first read L<perl5122delta>, which describes differences between 5.12.1 and 5.12.2. The major changes made in 5.12.0 are described in L<perl5120delta>. =head1 Incompatible Changes There are no changes intentionally incompatible with 5.12.2. If any exist, they are bugs and reports are welcome. =head1 Core Enhancements =head2 C<keys>, C<values> work on arrays You can now use the C<keys>, C<values>, C<each> builtin functions on arrays (previously you could only use them on hashes). See L<perlfunc> for details. This is actually a change introduced in perl 5.12.0, but it was missed from that release's perldelta. =head1 Bug Fixes "no VERSION" will now correctly deparse with B::Deparse, as will certain constant expressions. Module::Build should be more reliably pass its tests under cygwin. Lvalue subroutines are again able to return copy-on-write scalars. This had been broken since version 5.10.0. =head1 Platform Specific Notes =over 4 =item Solaris A separate DTrace is now build for miniperl, which means that perl can be compiled with -Dusedtrace on Solaris again. =item VMS A number of regressions on VMS have been fixed. In addition to minor cleanup of questionable expressions in F<vms.c>, file permissions should no longer be garbled by the PerlIO layer, and spurious record boundaries should no longer be introduced by the PerlIO layer during output. For more details and discussion on the latter, see: http://www.nntp.perl.org/group/perl.vmsperl/2010/11/msg15419.html =item VOS A few very small changes were made to the build process on VOS to better support the platform. Longer-than-32-character filenames are now supported on OpenVOS, and build properly without IPv6 support. =back =head1 Acknowledgements Perl 5.12.3 represents approximately four months of development since Perl 5.12.2 and contains approximately 2500 lines of changes across 54 files from 16 authors. Perl continues to flourish into its third decade thanks to a vibrant community of users and developers. The following people are known to have contributed the improvements that became Perl 5.12.3: Craig A. Berry, David Golden, David Leadbeater, Father Chrysostomos, Florian Ragwitz, Jesse Vincent, Karl Williamson, Nick Johnston, Nicolas Kaiser, Paul Green, Rafael Garcia-Suarez, Rainer Tammer, Ricardo Signes, Steffen Mueller, Zsbán Ambrus, Ævar Arnfjörð Bjarmason =head1 Reporting Bugs If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup and the perl bug database at http://rt.perl.org/perlbug/ . There may also be information at http://www.perl.org/ , the Perl Home Page. If you believe you have an unreported bug, please run the B<perlbug> program included with your release. Be sure to trim your bug down to a tiny but sufficient test case. Your bug report, along with the output of C<perl -V>, will be sent off to perlbug@perl.org to be analysed by the Perl porting team. If the bug you are reporting has security implications, which make it inappropriate to send to a publicly archived mailing list, then please send it to perl5-security-report@perl.org. This points to a closed subscription unarchived mailing list, which includes all the core committers, who will be able to help assess the impact of issues, figure out a resolution, and help co-ordinate the release of patches to mitigate or fix the problem across all platforms on which Perl is supported. Please only use this address for security issues in the Perl core, not for modules independently distributed on CPAN. =head1 SEE ALSO The F<Changes> file for an explanation of how to view exhaustive details on what changed. The F<INSTALL> file for how to build Perl. The F<README> file for general stuff. The F<Artistic> and F<Copying> files for copyright information. =cut PK PU�\��낿 � perl583delta.podnu �[��� =head1 NAME perl583delta - what is new for perl v5.8.3 =head1 DESCRIPTION This document describes differences between the 5.8.2 release and the 5.8.3 release. If you are upgrading from an earlier release such as 5.6.1, first read the L<perl58delta>, which describes differences between 5.6.0 and 5.8.0, and the L<perl581delta> and L<perl582delta>, which describe differences between 5.8.0, 5.8.1 and 5.8.2 =head1 Incompatible Changes There are no changes incompatible with 5.8.2. =head1 Core Enhancements A C<SCALAR> method is now available for tied hashes. This is called when a tied hash is used in scalar context, such as if (%tied_hash) { ... } The old behaviour was that %tied_hash would return whatever would have been returned for that hash before the hash was tied (so usually 0). The new behaviour in the absence of a SCALAR method is to return TRUE if in the middle of an C<each> iteration, and otherwise call FIRSTKEY to check if the hash is empty (making sure that a subsequent C<each> will also begin by calling FIRSTKEY). Please see L<perltie/SCALAR> for the full details and caveats. =head1 Modules and Pragmata =over 4 =item CGI =item Cwd =item Digest =item Digest::MD5 =item Encode =item File::Spec =item FindBin A function C<again> is provided to resolve problems where modules in different directories wish to use FindBin. =item List::Util You can now weaken references to read only values. =item Math::BigInt =item PodParser =item Pod::Perldoc =item POSIX =item Unicode::Collate =item Unicode::Normalize =item Test::Harness =item threads::shared C<cond_wait> has a new two argument form. C<cond_timedwait> has been added. =back =head1 Utility Changes C<find2perl> now assumes C<-print> as a default action. Previously, it needed to be specified explicitly. A new utility, C<prove>, makes it easy to run an individual regression test at the command line. C<prove> is part of Test::Harness, which users of earlier Perl versions can install from CPAN. =head1 New Documentation The documentation has been revised in places to produce more standard manpages. The documentation for the special code blocks (BEGIN, CHECK, INIT, END) has been improved. =head1 Installation and Configuration Improvements Perl now builds on OpenVMS I64 =head1 Selected Bug Fixes Using substr() on a UTF8 string could cause subsequent accesses on that string to return garbage. This was due to incorrect UTF8 offsets being cached, and is now fixed. join() could return garbage when the same join() statement was used to process 8 bit data having earlier processed UTF8 data, due to the flags on that statement's temporary workspace not being reset correctly. This is now fixed. C<$a .. $b> will now work as expected when either $a or $b is C<undef> Using Unicode keys with tied hashes should now work correctly. Reading $^E now preserves $!. Previously, the C code implementing $^E did not preserve C<errno>, so reading $^E could cause C<errno> and therefore C<$!> to change unexpectedly. Reentrant functions will (once more) work with C++. 5.8.2 introduced a bugfix which accidentally broke the compilation of Perl extensions written in C++ =head1 New or Changed Diagnostics The fatal error "DESTROY created new reference to dead object" is now documented in L<perldiag>. =head1 Changed Internals The hash code has been refactored to reduce source duplication. The external interface is unchanged, and aside from the bug fixes described above, there should be no change in behaviour. C<hv_clear_placeholders> is now part of the perl API Some C macros have been tidied. In particular macros which create temporary local variables now name these variables more defensively, which should avoid bugs where names clash. <signal.h> is now always included. =head1 Configuration and Building C<Configure> now invokes callbacks regardless of the value of the variable they are called for. Previously callbacks were only invoked in the C<case $variable $define)> branch. This change should only affect platform maintainers writing configuration hints files. =head1 Platform Specific Problems The regression test ext/threads/shared/t/wait.t fails on early RedHat 9 and HP-UX 10.20 due to bugs in their threading implementations. RedHat users should see https://rhn.redhat.com/errata/RHBA-2003-136.html and consider upgrading their glibc. =head1 Known Problems Detached threads aren't supported on Windows yet, as they may lead to memory access violation problems. There is a known race condition opening scripts in C<suidperl>. C<suidperl> is neither built nor installed by default, and has been deprecated since perl 5.8.0. You are advised to replace use of suidperl with tools such as sudo ( http://www.courtesan.com/sudo/ ) We have a backlog of unresolved bugs. Dealing with bugs and bug reports is unglamorous work; not something ideally suited to volunteer labour, but that is all that we have. The perl5 development team are implementing changes to help address this problem, which should go live in early 2004. =head1 Future Directions Code freeze for the next maintenance release (5.8.4) is on March 31st 2004, with release expected by mid April. Similarly 5.8.5's freeze will be at the end of June, with release by mid July. =head1 Obituary Iain 'Spoon' Truskett, Perl hacker, author of L<perlreref> and contributor to CPAN, died suddenly on 29th December 2003, aged 24. He will be missed. =head1 Reporting Bugs If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup and the perl bug database at http://bugs.perl.org. There may also be information at http://www.perl.org, the Perl Home Page. If you believe you have an unreported bug, please run the B<perlbug> program included with your release. Be sure to trim your bug down to a tiny but sufficient test case. Your bug report, along with the output of C<perl -V>, will be sent off to perlbug@perl.org to be analysed by the Perl porting team. You can browse and search the Perl 5 bugs at http://bugs.perl.org/ =head1 SEE ALSO The F<Changes> file for exhaustive details on what changed. The F<INSTALL> file for how to build Perl. The F<README> file for general stuff. The F<Artistic> and F<Copying> files for copyright information. =cut PK PU�\���) ) perldos.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see perlpod manpage) which is specially designed to be readable as is. =head1 NAME perldos - Perl under DOS, W31, W95. =head1 SYNOPSIS These are instructions for building Perl under DOS (or w??), using DJGPP v2.03 or later. Under w95 long filenames are supported. =head1 DESCRIPTION Before you start, you should glance through the README file found in the top-level directory where the Perl distribution was extracted. Make sure you read and understand the terms under which this software is being distributed. This port currently supports MakeMaker (the set of modules that is used to build extensions to perl). Therefore, you should be able to build and install most extensions found in the CPAN sites. Detailed instructions on how to build and install perl extension modules, including XS-type modules, is included. See 'BUILDING AND INSTALLING MODULES'. =head2 Prerequisites for Compiling Perl on DOS =over 4 =item DJGPP DJGPP is a port of GNU C/C++ compiler and development tools to 32-bit, protected-mode environment on Intel 32-bit CPUs running MS-DOS and compatible operating systems, by DJ Delorie <dj@delorie.com> and friends. For more details (FAQ), check out the home of DJGPP at: http://www.delorie.com/djgpp/ If you have questions about DJGPP, try posting to the DJGPP newsgroup: comp.os.msdos.djgpp, or use the email gateway djgpp@delorie.com. You can find the full DJGPP distribution on any of the mirrors listed here: http://www.delorie.com/djgpp/getting.html You need the following files to build perl (or add new modules): v2/djdev203.zip v2gnu/bnu2112b.zip v2gnu/gcc2953b.zip v2gnu/bsh204b.zip v2gnu/mak3791b.zip v2gnu/fil40b.zip v2gnu/sed3028b.zip v2gnu/txt20b.zip v2gnu/dif272b.zip v2gnu/grep24b.zip v2gnu/shl20jb.zip v2gnu/gwk306b.zip v2misc/csdpmi5b.zip or possibly any newer version. =item Pthreads Thread support is not tested in this version of the djgpp perl. =back =head2 Shortcomings of Perl under DOS Perl under DOS lacks some features of perl under UNIX because of deficiencies in the UNIX-emulation, most notably: =over 4 =item * fork() and pipe() =item * some features of the UNIX filesystem regarding link count and file dates =item * in-place operation is a little bit broken with short filenames =item * sockets =back =head2 Building Perl on DOS =over 4 =item * Unpack the source package F<perl5.8*.tar.gz> with djtarx. If you want to use long file names under w95 and also to get Perl to pass all its tests, don't forget to use set LFN=y set FNCASE=y before unpacking the archive. =item * Create a "symlink" or copy your bash.exe to sh.exe in your C<($DJDIR)/bin> directory. ln -s bash.exe sh.exe [If you have the recommended version of bash for DJGPP, this is already done for you.] And make the C<SHELL> environment variable point to this F<sh.exe>: set SHELL=c:/djgpp/bin/sh.exe (use full path name!) You can do this in F<djgpp.env> too. Add this line BEFORE any section definition: +SHELL=%DJDIR%/bin/sh.exe =item * If you have F<split.exe> and F<gsplit.exe> in your path, then rename F<split.exe> to F<djsplit.exe>, and F<gsplit.exe> to F<split.exe>. Copy or link F<gecho.exe> to F<echo.exe> if you don't have F<echo.exe>. Copy or link F<gawk.exe> to F<awk.exe> if you don't have F<awk.exe>. [If you have the recommended versions of djdev, shell utilities and gawk, all these are already done for you, and you will not need to do anything.] =item * Chdir to the djgpp subdirectory of perl toplevel and type the following commands: set FNCASE=y configure.bat This will do some preprocessing then run the Configure script for you. The Configure script is interactive, but in most cases you just need to press ENTER. The "set" command ensures that DJGPP preserves the letter case of file names when reading directories. If you already issued this set command when unpacking the archive, and you are in the same DOS session as when you unpacked the archive, you don't have to issue the set command again. This command is necessary *before* you start to (re)configure or (re)build perl in order to ensure both that perl builds correctly and that building XS-type modules can succeed. See the DJGPP info entry for "_preserve_fncase" for more information: info libc alphabetical _preserve_fncase If the script says that your package is incomplete, and asks whether to continue, just answer with Y (this can only happen if you don't use long filenames or forget to issue "set FNCASE=y" first). When Configure asks about the extensions, I suggest IO and Fcntl, and if you want database handling then SDBM_File or GDBM_File (you need to install gdbm for this one). If you want to use the POSIX extension (this is the default), make sure that the stack size of your F<cc1.exe> is at least 512kbyte (you can check this with: C<stubedit cc1.exe>). You can use the Configure script in non-interactive mode too. When I built my F<perl.exe>, I used something like this: configure.bat -des You can find more info about Configure's command line switches in the F<INSTALL> file. When the script ends, and you want to change some values in the generated F<config.sh> file, then run sh Configure -S after you made your modifications. IMPORTANT: if you use this C<-S> switch, be sure to delete the CONFIG environment variable before running the script: set CONFIG= =item * Now you can compile Perl. Type: make =back =head2 Testing Perl on DOS Type: make test If you're lucky you should see "All tests successful". But there can be a few failed subtests (less than 5 hopefully) depending on some external conditions (e.g. some subtests fail under linux/dosemu or plain dos with short filenames only). =head2 Installation of Perl on DOS Type: make install This will copy the newly compiled perl and libraries into your DJGPP directory structure. Perl.exe and the utilities go into C<($DJDIR)/bin>, and the library goes under C<($DJDIR)/lib/perl5>. The pod documentation goes under C<($DJDIR)/lib/perl5/pod>. =head1 BUILDING AND INSTALLING MODULES ON DOS =head2 Building Prerequisites for Perl on DOS For building and installing non-XS modules, all you need is a working perl under DJGPP. Non-XS modules do not require re-linking the perl binary, and so are simpler to build and install. XS-type modules do require re-linking the perl binary, because part of an XS module is written in "C", and has to be linked together with the perl binary to be executed. This is required because perl under DJGPP is built with the "static link" option, due to the lack of "dynamic linking" in the DJGPP environment. Because XS modules require re-linking of the perl binary, you need both the perl binary distribution and the perl source distribution to build an XS extension module. In addition, you will have to have built your perl binary from the source distribution so that all of the components of the perl binary are available for the required link step. =head2 Unpacking CPAN Modules on DOS First, download the module package from CPAN (e.g., the "Comma Separated Value" text package, Text-CSV-0.01.tar.gz). Then expand the contents of the package into some location on your disk. Most CPAN modules are built with an internal directory structure, so it is usually safe to expand it in the root of your DJGPP installation. Some people prefer to locate source trees under /usr/src (i.e., C<($DJDIR)/usr/src>), but you may put it wherever seems most logical to you, *EXCEPT* under the same directory as your perl source code. There are special rules that apply to modules which live in the perl source tree that do not apply to most of the modules in CPAN. Unlike other DJGPP packages, which are normal "zip" files, most CPAN module packages are "gzipped tarballs". Recent versions of WinZip will safely unpack and expand them, *UNLESS* they have zero-length files. It is a known WinZip bug (as of v7.0) that it will not extract zero-length files. From the command line, you can use the djtar utility provided with DJGPP to unpack and expand these files. For example: C:\djgpp>djtarx -v Text-CSV-0.01.tar.gz This will create the new directory C<($DJDIR)/Text-CSV-0.01>, filling it with the source for this module. =head2 Building Non-XS Modules on DOS To build a non-XS module, you can use the standard module-building instructions distributed with perl modules. perl Makefile.PL make make test make install This is sufficient because non-XS modules install only ".pm" files and (sometimes) pod and/or man documentation. No re-linking of the perl binary is needed to build, install or use non-XS modules. =head2 Building XS Modules on DOS To build an XS module, you must use the standard module-building instructions distributed with perl modules *PLUS* three extra instructions specific to the DJGPP "static link" build environment. set FNCASE=y perl Makefile.PL make make perl make test make -f Makefile.aperl inst_perl MAP_TARGET=perl.exe make install The first extra instruction sets DJGPP's FNCASE environment variable so that the new perl binary which you must build for an XS-type module will build correctly. The second extra instruction re-builds the perl binary in your module directory before you run "make test", so that you are testing with the new module code you built with "make". The third extra instruction installs the perl binary from your module directory into the standard DJGPP binary directory, C<($DJDIR)/bin>, replacing your previous perl binary. Note that the MAP_TARGET value *must* have the ".exe" extension or you will not create a "perl.exe" to replace the one in C<($DJDIR)/bin>. When you are done, the XS-module install process will have added information to your "perllocal" information telling that the perl binary has been replaced, and what module was installed. You can view this information at any time by using the command: perl -S perldoc perllocal =head1 AUTHOR Laszlo Molnar, F<laszlo.molnar@eth.ericsson.se> [Installing/building perl] Peter J. Farley III F<pjfarley@banet.net> [Building/installing modules] =head1 SEE ALSO perl(1). =cut PK PU�\LQ�� � perlmroapi.podnu �[��� =head1 NAME perlmroapi - Perl method resolution plugin interface =head1 DESCRIPTION As of Perl 5.10.1 there is a new interface for plugging and using method resolution orders other than the default (linear depth first search). The C3 method resolution order added in 5.10.0 has been re-implemented as a plugin, without changing its Perl-space interface. Each plugin should register itself by providing the following structure struct mro_alg { AV *(*resolve)(pTHX_ HV *stash, U32 level); const char *name; U16 length; U16 kflags; U32 hash; }; and calling C<Perl_mro_register>: Perl_mro_register(aTHX_ &my_mro_alg); =over 4 =item resolve Pointer to the linearisation function, described below. =item name Name of the MRO, either in ISO-8859-1 or UTF-8. =item length Length of the name. =item kflags If the name is given in UTF-8, set this to C<HVhek_UTF8>. The value is passed direct as the parameter I<kflags> to C<hv_common()>. =item hash A precomputed hash value for the MRO's name, or 0. =back =head1 Callbacks The C<resolve> function is called to generate a linearised ISA for the given stash, using this MRO. It is called with a pointer to the stash, and a I<level> of 0. The core always sets I<level> to 0 when it calls your function - the parameter is provided to allow your implementation to track depth if it needs to recurse. The function should return a reference to an array containing the parent classes in order. The names of the classes should be the result of calling C<HvENAME()> on the stash. In those cases where C<HvENAME()> returns null, C<HvNAME()> should be used instead. The caller is responsible for incrementing the reference count of the array returned if it wants to keep the structure. Hence, if you have created a temporary value that you keep no pointer to, C<sv_2mortal()> to ensure that it is disposed of correctly. If you have cached your return value, then return a pointer to it without changing the reference count. =head1 Caching Computing MROs can be expensive. The implementation provides a cache, in which you can store a single C<SV *>, or anything that can be cast to C<SV *>, such as C<AV *>. To read your private value, use the macro C<MRO_GET_PRIVATE_DATA()>, passing it the C<mro_meta> structure from the stash, and a pointer to your C<mro_alg> structure: meta = HvMROMETA(stash); private_sv = MRO_GET_PRIVATE_DATA(meta, &my_mro_alg); To set your private value, call C<Perl_mro_set_private_data()>: Perl_mro_set_private_data(aTHX_ meta, &c3_alg, private_sv); The private data cache will take ownership of a reference to private_sv, much the same way that C<hv_store()> takes ownership of a reference to the value that you pass it. =head1 Examples For examples of MRO implementations, see C<S_mro_get_linear_isa_c3()> and the C<BOOT:> section of F<mro/mro.xs>, and C<S_mro_get_linear_isa_dfs()> in F<mro.c> =head1 AUTHORS The implementation of the C3 MRO and switchable MROs within the perl core was written by Brandon L Black. Nicholas Clark created the pluggable interface, refactored Brandon's implementation to work with it, and wrote this document. =cut PK PU�\e���� � perl5142delta.podnu �[��� =encoding utf8 =head1 NAME perl5142delta - what is new for perl v5.14.2 =head1 DESCRIPTION This document describes differences between the 5.14.1 release and the 5.14.2 release. If you are upgrading from an earlier release such as 5.14.0, first read L<perl5141delta>, which describes differences between 5.14.0 and 5.14.1. =head1 Core Enhancements No changes since 5.14.0. =head1 Security =head2 C<File::Glob::bsd_glob()> memory error with GLOB_ALTDIRFUNC (CVE-2011-2728). Calling C<File::Glob::bsd_glob> with the unsupported flag GLOB_ALTDIRFUNC would cause an access violation / segfault. A Perl program that accepts a flags value from an external source could expose itself to denial of service or arbitrary code execution attacks. There are no known exploits in the wild. The problem has been corrected by explicitly disabling all unsupported flags and setting unused function pointers to null. Bug reported by Clément Lecigne. =head2 C<Encode> decode_xs n-byte heap-overflow (CVE-2011-2939) A bug in C<Encode> could, on certain inputs, cause the heap to overflow. This problem has been corrected. Bug reported by Robert Zacek. =head1 Incompatible Changes There are no changes intentionally incompatible with 5.14.0. If any exist, they are bugs and reports are welcome. =head1 Deprecations There have been no deprecations since 5.14.0. =head1 Modules and Pragmata =head2 New Modules and Pragmata None =head2 Updated Modules and Pragmata =over 4 =item * L<CPAN> has been upgraded from version 1.9600 to version 1.9600_01. L<CPAN::Distribution> has been upgraded from version 1.9602 to 1.9602_01. Backported bugfixes from CPAN version 1.9800. Ensures proper detection of C<configure_requires> prerequisites from CPAN Meta files in the case where C<dynamic_config> is true. [rt.cpan.org #68835] Also ensures that C<configure_requires> is only checked in META files, not MYMETA files, so protect against MYMETA generation that drops C<configure_requires>. =item * L<Encode> has been upgraded from version 2.42 to 2.42_01. See L</Security>. =item * L<File::Glob> has been upgraded from version 1.12 to version 1.13. See L</Security>. =item * L<PerlIO::scalar> has been upgraded from version 0.11 to 0.11_01. It fixes a problem with C<< open my $fh, ">", \$scalar >> not working if C<$scalar> is a copy-on-write scalar. =back =head2 Removed Modules and Pragmata None =head1 Platform Support =head2 New Platforms None =head2 Discontinued Platforms None =head2 Platform-Specific Notes =over 4 =item HP-UX PA-RISC/64 now supports gcc-4.x A fix to correct the socketsize now makes the test suite pass on HP-UX PA-RISC for 64bitall builds. =item Building on OS X 10.7 Lion and Xcode 4 works again The build system has been updated to work with the build tools under Mac OS X 10.7. =back =head1 Bug Fixes =over 4 =item * In @INC filters (subroutines returned by subroutines in @INC), $_ used to misbehave: If returned from a subroutine, it would not be copied, but the variable itself would be returned; and freeing $_ (e.g., with C<undef *_>) would cause perl to crash. This has been fixed [perl #91880]. =item * Perl 5.10.0 introduced some faulty logic that made "U*" in the middle of a pack template equivalent to "U0" if the input string was empty. This has been fixed [perl #90160]. =item * C<caller> no longer leaks memory when called from the DB package if C<@DB::args> was assigned to after the first call to C<caller>. L<Carp> was triggering this bug [perl #97010]. =item * C<utf8::decode> had a nasty bug that would modify copy-on-write scalars' string buffers in place (i.e., skipping the copy). This could result in hashes having two elements with the same key [perl #91834]. =item * Localising a tied variable used to make it read-only if it contained a copy-on-write string. =item * Elements of restricted hashes (see the L<fields> pragma) containing copy-on-write values couldn't be deleted, nor could such hashes be cleared (C<%hash = ()>). =item * Locking a hash element that is a glob copy no longer causes subsequent assignment to it to corrupt the glob. =item * A panic involving the combination of the regular expression modifiers C</aa> introduced in 5.14.0 and the C<\b> escape sequence has been fixed [perl #95964]. =back =head1 Known Problems This is a list of some significant unfixed bugs, which are regressions from 5.12.0. =over 4 =item * C<PERL_GLOBAL_STRUCT> is broken. Since perl 5.14.0, building with C<-DPERL_GLOBAL_STRUCT> hasn't been possible. This means that perl currently doesn't work on any platforms that require it to be built this way, including Symbian. While C<PERL_GLOBAL_STRUCT> now works again on recent development versions of perl, it actually working on Symbian again hasn't been verified. We'd be very interested in hearing from anyone working with Perl on Symbian. =back =head1 Acknowledgements Perl 5.14.2 represents approximately three months of development since Perl 5.14.1 and contains approximately 1200 lines of changes across 61 files from 9 authors. Perl continues to flourish into its third decade thanks to a vibrant community of users and developers. The following people are known to have contributed the improvements that became Perl 5.14.2: Craig A. Berry, David Golden, Father Chrysostomos, Florian Ragwitz, H.Merijn Brand, Karl Williamson, Nicholas Clark, Pau Amma and Ricardo Signes. =head1 Reporting Bugs If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup and the perl bug database at http://rt.perl.org/perlbug/ . There may also be information at http://www.perl.org/ , the Perl Home Page. If you believe you have an unreported bug, please run the L<perlbug> program included with your release. Be sure to trim your bug down to a tiny but sufficient test case. Your bug report, along with the output of C<perl -V>, will be sent off to perlbug@perl.org to be analysed by the Perl porting team. If the bug you are reporting has security implications, which make it inappropriate to send to a publicly archived mailing list, then please send it to perl5-security-report@perl.org. This points to a closed subscription unarchived mailing list, which includes all the core committers, who be able to help assess the impact of issues, figure out a resolution, and help co-ordinate the release of patches to mitigate or fix the problem across all platforms on which Perl is supported. Please only use this address for security issues in the Perl core, not for modules independently distributed on CPAN. =head1 SEE ALSO The F<Changes> file for an explanation of how to view exhaustive details on what changed. The F<INSTALL> file for how to build Perl. The F<README> file for general stuff. The F<Artistic> and F<Copying> files for copyright information. =cut PK PU�\��� �� perltoc.podnu �[��� # !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is autogenerated by buildtoc from all the other pods. # Edit those files and run pod/buildtoc to effect changes. =head1 NAME perltoc - perl documentation table of contents =head1 DESCRIPTION This page provides a brief table of contents for the rest of the Perl documentation set. It is meant to be scanned quickly or grepped through to locate the proper section you're looking for. =head1 BASIC DOCUMENTATION =head2 perl - The Perl 5 language interpreter =over 4 =item SYNOPSIS =item GETTING HELP =over 4 =item Overview =item Tutorials =item Reference Manual =item Internals and C Language Interface =item Miscellaneous =item Language-Specific =item Platform-Specific =item Stubs for Deleted Documents =back =item DESCRIPTION =item AVAILABILITY =item ENVIRONMENT =item AUTHOR =item FILES =item SEE ALSO =item DIAGNOSTICS =item BUGS =item NOTES =back =head2 perlintro -- a brief introduction and overview of Perl =over 4 =item DESCRIPTION =over 4 =item What is Perl? =item Running Perl programs =item Safety net =item Basic syntax overview =item Perl variable types Scalars, Arrays, Hashes =item Variable scoping =item Conditional and looping constructs if, while, for, foreach =item Builtin operators and functions Arithmetic, Numeric comparison, String comparison, Boolean logic, Miscellaneous =item Files and I/O =item Regular expressions Simple matching, Simple substitution, More complex regular expressions, Parentheses for capturing, Other regexp features =item Writing subroutines =item OO Perl =item Using Perl modules =back =item AUTHOR =back =head2 perlreftut - Mark's very short tutorial about references =over 4 =item DESCRIPTION =item Who Needs Complicated Data Structures? =item The Solution =item Syntax =over 4 =item Making References =item Using References =item An Example =item Arrow Rule =back =item Solution =item The Rest =item Summary =item Credits =over 4 =item Distribution Conditions =back =back =head2 perldsc - Perl Data Structures Cookbook =over 4 =item DESCRIPTION arrays of arrays, hashes of arrays, arrays of hashes, hashes of hashes, more elaborate constructs =item REFERENCES X<reference> X<dereference> X<dereferencing> X<pointer> =item COMMON MISTAKES =item CAVEAT ON PRECEDENCE X<dereference, precedence> X<dereferencing, precedence> =item WHY YOU SHOULD ALWAYS C<use strict> =item DEBUGGING X<data structure, debugging> X<complex data structure, debugging> X<AoA, debugging> X<HoA, debugging> X<AoH, debugging> X<HoH, debugging> X<array of arrays, debugging> X<hash of arrays, debugging> X<array of hashes, debugging> X<hash of hashes, debugging> =item CODE EXAMPLES =item ARRAYS OF ARRAYS X<array of arrays> X<AoA> =over 4 =item Declaration of an ARRAY OF ARRAYS =item Generation of an ARRAY OF ARRAYS =item Access and Printing of an ARRAY OF ARRAYS =back =item HASHES OF ARRAYS X<hash of arrays> X<HoA> =over 4 =item Declaration of a HASH OF ARRAYS =item Generation of a HASH OF ARRAYS =item Access and Printing of a HASH OF ARRAYS =back =item ARRAYS OF HASHES X<array of hashes> X<AoH> =over 4 =item Declaration of an ARRAY OF HASHES =item Generation of an ARRAY OF HASHES =item Access and Printing of an ARRAY OF HASHES =back =item HASHES OF HASHES X<hash of hashes> X<HoH> =over 4 =item Declaration of a HASH OF HASHES =item Generation of a HASH OF HASHES =item Access and Printing of a HASH OF HASHES =back =item MORE ELABORATE RECORDS X<record> X<structure> X<struct> =over 4 =item Declaration of MORE ELABORATE RECORDS =item Declaration of a HASH OF COMPLEX RECORDS =item Generation of a HASH OF COMPLEX RECORDS =back =item Database Ties =item SEE ALSO =item AUTHOR =back =head2 perllol - Manipulating Arrays of Arrays in Perl =over 4 =item DESCRIPTION =over 4 =item Declaration and Access of Arrays of Arrays =item Growing Your Own =item Access and Printing =item Slices =back =item SEE ALSO =item AUTHOR =back =head2 perlrequick - Perl regular expressions quick start =over 4 =item DESCRIPTION =item The Guide =over 4 =item Simple word matching =item Using character classes =item Matching this or that =item Grouping things and hierarchical matching =item Extracting matches =item Matching repetitions =item More matching =item Search and replace =item The split operator =back =item BUGS =item SEE ALSO =item AUTHOR AND COPYRIGHT =over 4 =item Acknowledgments =back =back =head2 perlretut - Perl regular expressions tutorial =over 4 =item DESCRIPTION =item Part 1: The basics =over 4 =item Simple word matching =item Using character classes =item Matching this or that =item Grouping things and hierarchical matching =item Extracting matches =item Backreferences =item Relative backreferences =item Named backreferences =item Alternative capture group numbering =item Position information =item Non-capturing groupings =item Matching repetitions =item Possessive quantifiers =item Building a regexp =item Using regular expressions in Perl =back =item Part 2: Power tools =over 4 =item More on characters, strings, and character classes =item Compiling and saving regular expressions =item Composing regular expressions at runtime =item Embedding comments and modifiers in a regular expression =item Looking ahead and looking behind =item Using independent subexpressions to prevent backtracking =item Conditional expressions =item Defining named patterns =item Recursive patterns =item A bit of magic: executing Perl code in a regular expression =item Backtracking control verbs =item Pragmas and debugging =back =item BUGS =item SEE ALSO =item AUTHOR AND COPYRIGHT =over 4 =item Acknowledgments =back =back =head2 perlootut - Object-Oriented Programming in Perl Tutorial =over 4 =item DATE =item DESCRIPTION =item OBJECT-ORIENTED FUNDAMENTALS =over 4 =item Object =item Class =item Methods =item Attributes =item Polymorphism =item Inheritance =item Encapsulation =item Composition =item Roles =item When to Use OO =back =item PERL OO SYSTEMS =over 4 =item Moose Declarative sugar, Roles built-in, A miniature type system, Full introspection and manipulation, Self-hosted and extensible, Rich ecosystem, Many more features =item Class::Accessor =item Object::Tiny =item Role::Tiny =item OO System Summary L<Moose>, L<Class::Accessor>, L<Object::Tiny>, L<Role::Tiny> =item Other OO Systems =back =item CONCLUSION =back =head2 perlperf - Perl Performance and Optimization Techniques =over 4 =item DESCRIPTION =item OVERVIEW =over 4 =item ONE STEP SIDEWAYS =item ONE STEP FORWARD =item ANOTHER STEP SIDEWAYS =back =item GENERAL GUIDELINES =item BENCHMARKS =over 4 =item Assigning and Dereferencing Variables. =item Search and replace or tr =back =item PROFILING TOOLS =over 4 =item Devel::DProf =item Devel::Profiler =item Devel::SmallProf =item Devel::FastProf =item Devel::NYTProf =back =item SORTING Elapsed Real Time, User CPU Time, System CPU Time =item LOGGING =over 4 =item Logging if DEBUG (constant) =back =item POSTSCRIPT =item SEE ALSO =over 4 =item PERLDOCS =item MAN PAGES =item MODULES =item URLS =back =item AUTHOR =back =head2 perlstyle - Perl style guide =over 4 =item DESCRIPTION =back =head2 perlcheat - Perl 5 Cheat Sheet =over 4 =item DESCRIPTION =over 4 =item The sheet =back =item ACKNOWLEDGEMENTS =item AUTHOR =item SEE ALSO =back =head2 perltrap - Perl traps for the unwary =over 4 =item DESCRIPTION =over 4 =item Awk Traps =item C/C++ Traps =item Sed Traps =item Shell Traps =item Perl Traps =item Perl4 to Perl5 Traps Discontinuance, Deprecation, and BugFix traps, Parsing Traps, Numerical Traps, General data type traps, Context Traps - scalar, list contexts, Precedence Traps, General Regular Expression Traps using s///, etc, Subroutine, Signal, Sorting Traps, OS Traps, DBM Traps, Unclassified Traps =item Discontinuance, Deprecation, and BugFix traps Symbols starting with "_" no longer forced into main, Double-colon valid package separator in variable name, 2nd and 3rd args to C<splice()> are now in scalar context, Can't do C<goto> into a block that is optimized away, Can't use whitespace as variable name or quote delimiter, C<while/if BLOCK BLOCK> gone, C<**> binds tighter than unary minus, C<foreach> changed when iterating over a list, C<split> with no args behavior changed, B<-e> behavior fixed, C<push> returns number of elements in resulting list, Some error messages differ, C<split()> honors subroutine args, Bugs removed =item Parsing Traps Space between . and = triggers syntax error, Better parsing in perl 5, Function parsing, String interpolation of C<$#array> differs, Perl guesses on C<map>, C<grep> followed by C<{> if it starts BLOCK or hash ref =item Numerical Traps Formatted output and significant digits, Auto-increment operator over signed int limit deleted, Assignment of return values from numeric equality tests doesn't work, Bitwise string ops =item General data type traps Negative array subscripts now count from the end of array, Setting C<$#array> lower now discards array elements, Hashes get defined before use, Glob assignment from localized variable to variable, Assigning C<undef> to glob, Changes in unary negation (of strings), Modifying of constants prohibited, C<defined $var> behavior changed, Variable Suicide =item Context Traps - scalar, list contexts Elements of argument lists for formats evaluated in list context, C<caller()> returns false value in scalar context if no caller present, Comma operator in scalar context gives scalar context to args, C<sprintf()> prototyped as C<($;@)> =item Precedence Traps LHS vs. RHS of any assignment operator, Semantic errors introduced due to precedence, Precedence of assignment operators same as the precedence of assignment, C<open> requires parentheses around filehandle, C<$:> precedence over C<$::> gone, Precedence of file test operators documented, C<keys>, C<each>, C<values> are regular named unary operators =item General Regular Expression Traps using s///, etc. C<s'$lhs'$rhs'> interpolates on either side, C<m//g> attaches its state to the searched string, C<m//o> used within an anonymous sub, C<$+> isn't set to whole match, Substitution now returns null string if it fails, C<s`lhs`rhs`> is now a normal substitution, Stricter parsing of variables in regular expressions, C<m?x?> matches only once, Failed matches don't reset the match variables =item Subroutine, Signal, Sorting Traps Barewords that used to look like strings look like subroutine calls, Reverse is no longer allowed as the name of a sort subroutine, C<warn()> won't let you specify a filehandle =item OS Traps SysV resets signal handler correctly, SysV C<seek()> appends correctly =item Interpolation Traps C<@> always interpolates an array in double-quotish strings, Double-quoted strings may no longer end with an unescaped $, Arbitrary expressions are evaluated inside braces within double quotes, C<$$x> now tries to dereference $x, Creation of hashes on the fly with C<eval "EXPR"> requires protection, Bugs in earlier perl versions, Array and hash brackets during interpolation, Interpolation of C<\$$foo{bar}>, C<qq()> string passed to C<eval> will not find string terminator =item DBM Traps Perl5 must have been linked with same dbm/ndbm as the default for C<dbmopen()>, DBM exceeding limit on the key/value size will cause perl5 to exit immediately =item Unclassified Traps C<require>/C<do> trap using returned value, C<split> on empty string with LIMIT specified =back =back =head2 perldebtut - Perl debugging tutorial =over 4 =item DESCRIPTION =item use strict =item Looking at data and -w and v =item help =item Stepping through code =item Placeholder for a, w, t, T =item REGULAR EXPRESSIONS =item OUTPUT TIPS =item CGI =item GUIs =item SUMMARY =item SEE ALSO =item AUTHOR =item CONTRIBUTORS =back =head2 perlfaq - frequently asked questions about Perl =over 4 =item DESCRIPTION =over 4 =item Where to find the perlfaq =item How to use the perlfaq =item How to contribute to the perlfaq =item What if my question isn't answered in the FAQ? =back =item TABLE OF CONTENTS perlfaq1 - General Questions About Perl, perlfaq2 - Obtaining and Learning about Perl, perlfaq3 - Programming Tools, perlfaq4 - Data Manipulation, perlfaq5 - Files and Formats, perlfaq6 - Regular Expressions, perlfaq7 - General Perl Language Issues, perlfaq8 - System Interaction, perlfaq9 - Web, Email and Networking =item THE QUESTIONS =over 4 =item L<perlfaq1>: General Questions About Perl =item L<perlfaq2>: Obtaining and Learning about Perl =item L<perlfaq3>: Programming Tools =item L<perlfaq4>: Data Manipulation =item L<perlfaq5>: Files and Formats =item L<perlfaq6>: Regular Expressions =item L<perlfaq7>: General Perl Language Issues =item L<perlfaq8>: System Interaction =item L<perlfaq9>: Web, Email and Networking =back =item CREDITS =item AUTHOR AND COPYRIGHT =back =head2 perlfaq1 - General Questions About Perl =over 4 =item DESCRIPTION =over 4 =item What is Perl? =item Who supports Perl? Who develops it? Why is it free? =item Which version of Perl should I use? =item What are Perl 4, Perl 5, or Perl 6? =item What is Perl 6? =item How stable is Perl? =item Is Perl difficult to learn? =item How does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl? =item Can I do [task] in Perl? =item When shouldn't I program in Perl? =item What's the difference between "perl" and "Perl"? =item What is a JAPH? =item How can I convince others to use Perl? L<http://www.perl.org/about.html>, L<http://perltraining.com.au/whyperl.html> =back =item AUTHOR AND COPYRIGHT =back =head2 perlfaq2 - Obtaining and Learning about Perl =over 4 =item DESCRIPTION =over 4 =item What machines support Perl? Where do I get it? =item How can I get a binary version of Perl? =item I don't have a C compiler. How can I build my own Perl interpreter? =item I copied the Perl binary from one machine to another, but scripts don't work. =item I grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work? =item What modules and extensions are available for Perl? What is CPAN? =item Where can I get information on Perl? L<http://www.perl.org/>, L<http://perldoc.perl.org/>, L<http://learn.perl.org/> =item What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? L<http://www.perl.org/>, L<http://learn.perl.org/>, L<http://jobs.perl.org/>, L<http://lists.perl.org/> =item Where can I post questions? =item Perl Books =item Which magazines have Perl content? =item Which Perl blogs should I read? =item What mailing lists are there for Perl? =item Where can I buy a commercial version of Perl? =item Where do I send bug reports? =back =item AUTHOR AND COPYRIGHT =back =head2 perlfaq3 - Programming Tools =over 4 =item DESCRIPTION =over 4 =item How do I do (anything)? Basics, L<perldata> - Perl data types, L<perlvar> - Perl pre-defined variables, L<perlsyn> - Perl syntax, L<perlop> - Perl operators and precedence, L<perlsub> - Perl subroutines, Execution, L<perlrun> - how to execute the Perl interpreter, L<perldebug> - Perl debugging, Functions, L<perlfunc> - Perl builtin functions, Objects, L<perlref> - Perl references and nested data structures, L<perlmod> - Perl modules (packages and symbol tables), L<perlobj> - Perl objects, L<perltie> - how to hide an object class in a simple variable, Data Structures, L<perlref> - Perl references and nested data structures, L<perllol> - Manipulating arrays of arrays in Perl, L<perldsc> - Perl Data Structures Cookbook, Modules, L<perlmod> - Perl modules (packages and symbol tables), L<perlmodlib> - constructing new Perl modules and finding existing ones, Regexes, L<perlre> - Perl regular expressions, L<perlfunc> - Perl builtin functions>, L<perlop> - Perl operators and precedence, L<perllocale> - Perl locale handling (internationalization and localization), Moving to perl5, L<perltrap> - Perl traps for the unwary, L<perl>, Linking with C, L<perlxstut> - Tutorial for writing XSUBs, L<perlxs> - XS language reference manual, L<perlcall> - Perl calling conventions from C, L<perlguts> - Introduction to the Perl API, L<perlembed> - how to embed perl in your C program, Various =item How can I use Perl interactively? =item How do I find which modules are installed on my system? =item How do I debug my Perl programs? =item How do I profile my Perl programs? =item How do I cross-reference my Perl programs? =item Is there a pretty-printer (formatter) for Perl? =item Is there an IDE or Windows Perl Editor? Eclipse, Enginsite, Komodo, Notepad++, Open Perl IDE, OptiPerl, Padre, PerlBuilder, visiPerl+, Visual Perl, Zeus, GNU Emacs, MicroEMACS, XEmacs, Jed, Vim, Vile, Codewright, MultiEdit, SlickEdit, ConTEXT, Bash, Ksh, Tcsh, Zsh, Affrus, Alpha, BBEdit and BBEdit Lite =item Where can I get Perl macros for vi? =item Where can I get perl-mode or cperl-mode for emacs? X<emacs> =item How can I use curses with Perl? =item How can I write a GUI (X, Tk, Gtk, etc.) in Perl? X<GUI> X<Tk> X<Wx> X<WxWidgets> X<Gtk> X<Gtk2> X<CamelBones> X<Qt> Tk, Wx, Gtk and Gtk2, Win32::GUI, CamelBones, Qt, Athena =item How can I make my Perl program run faster? =item How can I make my Perl program take less memory? Don't slurp!, Use map and grep selectively, Avoid unnecessary quotes and stringification, Pass by reference, Tie large variables to disk =item Is it safe to return a reference to local or lexical data? =item How can I free an array or hash so my program shrinks? =item How can I make my CGI script more efficient? =item How can I hide the source for my Perl program? =item How can I compile my Perl program into byte code or C? =item How can I get C<#!perl> to work on [MS-DOS,NT,...]? =item Can I write useful Perl programs on the command line? =item Why don't Perl one-liners work on my DOS/Mac/VMS system? =item Where can I learn about CGI or Web programming in Perl? =item Where can I learn about object-oriented Perl programming? =item Where can I learn about linking C with Perl? =item I've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong? =item When I tried to run my script, I got this message. What does it mean? =item What's MakeMaker? =back =item AUTHOR AND COPYRIGHT =back =head2 perlfaq4 - Data Manipulation =over 4 =item DESCRIPTION =item Data: Numbers =over 4 =item Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)? =item Why is int() broken? =item Why isn't my octal data interpreted correctly? =item Does Perl have a round() function? What about ceil() and floor()? Trig functions? =item How do I convert between numeric representations/bases/radixes? How do I convert hexadecimal into decimal, How do I convert from decimal to hexadecimal, How do I convert from octal to decimal, How do I convert from decimal to octal, How do I convert from binary to decimal, How do I convert from decimal to binary =item Why doesn't & work the way I want it to? =item How do I multiply matrices? =item How do I perform an operation on a series of integers? =item How can I output Roman numerals? =item Why aren't my random numbers random? =item How do I get a random number between X and Y? =back =item Data: Dates =over 4 =item How do I find the day or week of the year? =item How do I find the current century or millennium? =item How can I compare two dates and find the difference? =item How can I take a string and turn it into epoch seconds? =item How can I find the Julian Day? =item How do I find yesterday's date? X<date> X<yesterday> X<DateTime> X<Date::Calc> X<Time::Local> X<daylight saving time> X<day> X<Today_and_Now> X<localtime> X<timelocal> =item Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant? =back =item Data: Strings =over 4 =item How do I validate input? =item How do I unescape a string? =item How do I remove consecutive pairs of characters? =item How do I expand function calls in a string? =item How do I find matching/nesting anything? =item How do I reverse a string? =item How do I expand tabs in a string? =item How do I reformat a paragraph? =item How can I access or change N characters of a string? =item How do I change the Nth occurrence of something? =item How can I count the number of occurrences of a substring within a string? =item How do I capitalize all the words on one line? X<Text::Autoformat> X<capitalize> X<case, title> X<case, sentence> =item How can I split a [character]-delimited string except when inside [character]? =item How do I strip blank space from the beginning/end of a string? =item How do I pad a string with blanks or pad a number with zeroes? =item How do I extract selected columns from a string? =item How do I find the soundex value of a string? =item How can I expand variables in text strings? =item What's wrong with always quoting "$vars"? =item Why don't my E<lt>E<lt>HERE documents work? There must be no space after the E<lt>E<lt> part, There (probably) should be a semicolon at the end of the opening token, You can't (easily) have any space in front of the tag, There needs to be at least a line separator after the end token =back =item Data: Arrays =over 4 =item What is the difference between a list and an array? =item What is the difference between $array[1] and @array[1]? =item How can I remove duplicate elements from a list or array? =item How can I tell whether a certain element is contained in a list or array? =item How do I compute the difference of two arrays? How do I compute the intersection of two arrays? =item How do I test whether two arrays or hashes are equal? =item How do I find the first array element for which a condition is true? =item How do I handle linked lists? =item How do I handle circular lists? X<circular> X<array> X<Tie::Cycle> X<Array::Iterator::Circular> X<cycle> X<modulus> =item How do I shuffle an array randomly? =item How do I process/modify each element of an array? =item How do I select a random element from an array? =item How do I permute N elements of a list? X<List::Permutor> X<permute> X<Algorithm::Loops> X<Knuth> X<The Art of Computer Programming> X<Fischer-Krause> =item How do I sort an array by (anything)? =item How do I manipulate arrays of bits? =item Why does defined() return true on empty arrays and hashes? =back =item Data: Hashes (Associative Arrays) =over 4 =item How do I process an entire hash? =item How do I merge two hashes? X<hash> X<merge> X<slice, hash> =item What happens if I add or remove keys from a hash while iterating over it? =item How do I look up a hash element by value? =item How can I know how many entries are in a hash? =item How do I sort a hash (optionally by value instead of key)? =item How can I always keep my hash sorted? X<hash tie sort DB_File Tie::IxHash> =item What's the difference between "delete" and "undef" with hashes? =item Why don't my tied hashes make the defined/exists distinction? =item How do I reset an each() operation part-way through? =item How can I get the unique keys from two hashes? =item How can I store a multidimensional array in a DBM file? =item How can I make my hash remember the order I put elements into it? =item Why does passing a subroutine an undefined element in a hash create it? =item How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays? =item How can I use a reference as a hash key? =item How can I check if a key exists in a multilevel hash? =item How can I prevent addition of unwanted keys into a hash? =back =item Data: Misc =over 4 =item How do I handle binary data correctly? =item How do I determine whether a scalar is a number/whole/integer/float? =item How do I keep persistent data across program calls? =item How do I print out or copy a recursive data structure? =item How do I define methods for every class/object? =item How do I verify a credit card checksum? =item How do I pack arrays of doubles or floats for XS code? =back =item AUTHOR AND COPYRIGHT =back =head2 perlfaq5 - Files and Formats =over 4 =item DESCRIPTION =over 4 =item How do I flush/unbuffer an output filehandle? Why must I do this? X<flush> X<buffer> X<unbuffer> X<autoflush> =item How do I change, delete, or insert a line in a file, or append to the beginning of a file? X<file, editing> =item How do I count the number of lines in a file? X<file, counting lines> X<lines> X<line> =item How do I delete the last N lines from a file? X<lines> X<file> =item How can I use Perl's C<-i> option from within a program? X<-i> X<in-place> =item How can I copy a file? X<copy> X<file, copy> X<File::Copy> =item How do I make a temporary file name? X<file, temporary> =item How can I manipulate fixed-record-length files? X<fixed-length> X<file, fixed-length records> =item How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? X<filehandle, local> X<filehandle, passing> X<filehandle, reference> =item How can I use a filehandle indirectly? X<filehandle, indirect> =item How can I set up a footer format to be used with write()? X<footer> =item How can I write() into a string? X<write, into a string> =item How can I open a filehandle to a string? X<string> X<open> X<IO::String> X<filehandle> =item How can I output my numbers with commas added? X<number, commify> =item How can I translate tildes (~) in a filename? X<tilde> X<tilde expansion> =item How come when I open a file read-write it wipes it out? X<clobber> X<read-write> X<clobbering> X<truncate> X<truncating> =item Why do I sometimes get an "Argument list too long" when I use E<lt>*E<gt>? X<argument list too long> =item How can I open a file with a leading ">" or trailing blanks? X<filename, special characters> =item How can I reliably rename a file? X<rename> X<mv> X<move> X<file, rename> =item How can I lock a file? X<lock> X<file, lock> X<flock> =item Why can't I just open(FH, "E<gt>file.lock")? X<lock, lockfile race condition> =item I still don't get locking. I just want to increment the number in the file. How can I do this? X<counter> X<file, counter> =item All I want to do is append a small amount of text to the end of a file. Do I still have to use locking? X<append> X<file, append> =item How do I randomly update a binary file? X<file, binary patch> =item How do I get a file's timestamp in perl? X<timestamp> X<file, timestamp> =item How do I set a file's timestamp in perl? X<timestamp> X<file, timestamp> =item How do I print to more than one file at once? X<print, to multiple files> =item How can I read in an entire file all at once? X<slurp> X<file, slurping> =item How can I read in a file by paragraphs? X<file, reading by paragraphs> =item How can I read a single character from a file? From the keyboard? X<getc> X<file, reading one character at a time> =item How can I tell whether there's a character waiting on a filehandle? =item How do I do a C<tail -f> in perl? X<tail> X<IO::Handle> X<File::Tail> X<clearerr> =item How do I dup() a filehandle in Perl? X<dup> =item How do I close a file descriptor by number? X<file, closing file descriptors> X<POSIX> X<close> =item Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work? X<filename, DOS issues> =item Why doesn't glob("*.*") get all the files? X<glob> =item Why does Perl let me delete read-only files? Why does C<-i> clobber protected files? Isn't this a bug in Perl? =item How do I select a random line from a file? X<file, selecting a random line> =item Why do I get weird spaces when I print an array of lines? =item How do I traverse a directory tree? =item How do I delete a directory tree? =item How do I copy an entire directory? =back =item AUTHOR AND COPYRIGHT =back =head2 perlfaq6 - Regular Expressions =over 4 =item DESCRIPTION =over 4 =item How can I hope to use regular expressions without creating illegible and unmaintainable code? X<regex, legibility> X<regexp, legibility> X<regular expression, legibility> X</x> Comments Outside the Regex, Comments Inside the Regex, Different Delimiters =item I'm having trouble matching over more than one line. What's wrong? X<regex, multiline> X<regexp, multiline> X<regular expression, multiline> =item How can I pull out lines between two patterns that are themselves on different lines? X<..> =item How do I match XML, HTML, or other nasty, ugly things with a regex? X<regex, XML> X<regex, HTML> X<XML> X<HTML> X<pain> X<frustration> X<sucking out, will to live> =item I put a regular expression into $/ but it didn't work. What's wrong? X<$/, regexes in> X<$INPUT_RECORD_SEPARATOR, regexes in> X<$RS, regexes in> =item How do I substitute case-insensitively on the LHS while preserving case on the RHS? X<replace, case preserving> X<substitute, case preserving> X<substitution, case preserving> X<s, case preserving> =item How can I make C<\w> match national character sets? X<\w> =item How can I match a locale-smart version of C</[a-zA-Z]/>? X<alpha> =item How can I quote a variable to use in a regex? X<regex, escaping> X<regexp, escaping> X<regular expression, escaping> =item What is C</o> really for? X</o, regular expressions> X<compile, regular expressions> =item How do I use a regular expression to strip C-style comments from a file? =item Can I use Perl regular expressions to match balanced text? X<regex, matching balanced test> X<regexp, matching balanced test> X<regular expression, matching balanced test> X<possessive> X<PARNO> X<Text::Balanced> X<Regexp::Common> X<backtracking> X<recursion> =item What does it mean that regexes are greedy? How can I get around it? X<greedy> X<greediness> =item How do I process each word on each line? X<word> =item How can I print out a word-frequency or line-frequency summary? =item How can I do approximate matching? X<match, approximate> X<matching, approximate> =item How do I efficiently match many regular expressions at once? X<regex, efficiency> X<regexp, efficiency> X<regular expression, efficiency> =item Why don't word-boundary searches with C<\b> work for me? X<\b> =item Why does using $&, $`, or $' slow my program down? X<$MATCH> X<$&> X<$POSTMATCH> X<$'> X<$PREMATCH> X<$`> =item What good is C<\G> in a regular expression? X<\G> =item Are Perl regexes DFAs or NFAs? Are they POSIX compliant? X<DFA> X<NFA> X<POSIX> =item What's wrong with using grep in a void context? X<grep> =item How can I match strings with multibyte characters? X<regex, and multibyte characters> X<regexp, and multibyte characters> X<regular expression, and multibyte characters> X<martian> X<encoding, Martian> =item How do I match a regular expression that's in a variable? X<regex, in variable> X<eval> X<regex> X<quotemeta> X<\Q, regex> X<\E, regex> X<qr//> =back =item AUTHOR AND COPYRIGHT =back =head2 perlfaq7 - General Perl Language Issues =over 4 =item DESCRIPTION =over 4 =item Can I get a BNF/yacc/RE for the Perl language? =item What are all these $@%&* punctuation signs, and how do I know when to use them? =item Do I always/never have to quote my strings or use semicolons and commas? =item How do I skip some return values? =item How do I temporarily block warnings? =item What's an extension? =item Why do Perl operators have different precedence than C operators? =item How do I declare/create a structure? =item How do I create a module? =item How do I adopt or take over a module already on CPAN? =item How do I create a class? X<class, creation> X<package> =item How can I tell if a variable is tainted? =item What's a closure? =item What is variable suicide and how can I prevent it? =item How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}? Passing Variables and Functions, Passing Filehandles, Passing Regexes, Passing Methods =item How do I create a static variable? =item What's the difference between dynamic and lexical (static) scoping? Between local() and my()? =item How can I access a dynamic variable while a similarly named lexical is in scope? =item What's the difference between deep and shallow binding? =item Why doesn't "my($foo) = E<lt>$fhE<gt>;" work right? =item How do I redefine a builtin function, operator, or method? =item What's the difference between calling a function as &foo and foo()? =item How do I create a switch or case statement? =item How can I catch accesses to undefined variables, functions, or methods? =item Why can't a method included in this same file be found? =item How can I find out my current or calling package? =item How can I comment out a large block of Perl code? =item How do I clear a package? =item How can I use a variable as a variable name? =item What does "bad interpreter" mean? =back =item AUTHOR AND COPYRIGHT =back =head2 perlfaq8 - System Interaction =over 4 =item DESCRIPTION =over 4 =item How do I find out which operating system I'm running under? =item How come exec() doesn't return? X<exec> X<system> X<fork> X<open> X<pipe> =item How do I do fancy stuff with the keyboard/screen/mouse? Keyboard, Screen, Mouse =item How do I print something out in color? =item How do I read just one key without waiting for a return key? =item How do I check whether input is ready on the keyboard? =item How do I clear the screen? =item How do I get the screen size? =item How do I ask the user for a password? =item How do I read and write the serial port? lockfiles, open mode, end of line, flushing output, non-blocking input =item How do I decode encrypted password files? =item How do I start a process in the background? STDIN, STDOUT, and STDERR are shared, Signals, Zombies =item How do I trap control characters/signals? =item How do I modify the shadow password file on a Unix system? =item How do I set the time and date? =item How can I sleep() or alarm() for under a second? X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select> =item How can I measure time under a second? X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select> =item How can I do an atexit() or setjmp()/longjmp()? (Exception handling) =item Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean? =item How can I call my system's unique C functions from Perl? =item Where do I get the include files to do ioctl() or syscall()? =item Why do setuid perl scripts complain about kernel problems? =item How can I open a pipe both to and from a command? =item Why can't I get the output of a command with system()? =item How can I capture STDERR from an external command? =item Why doesn't open() return an error when a pipe open fails? =item What's wrong with using backticks in a void context? =item How can I call backticks without shell processing? =item Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)? =item How can I convert my shell script to perl? =item Can I use perl to run a telnet or ftp session? =item How can I write expect in Perl? =item Is there a way to hide perl's command line from programs such as "ps"? =item I {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible? Unix =item How do I close a process's filehandle without waiting for it to complete? =item How do I fork a daemon process? =item How do I find out if I'm running interactively or not? =item How do I timeout a slow event? =item How do I set CPU limits? X<BSD::Resource> X<limit> X<CPU> =item How do I avoid zombies on a Unix system? =item How do I use an SQL database? =item How do I make a system() exit on control-C? =item How do I open a file without blocking? =item How do I tell the difference between errors from the shell and perl? =item How do I install a module from CPAN? =item What's the difference between require and use? =item How do I keep my own module/library directory? =item How do I add the directory my program lives in to the module/library search path? =item How do I add a directory to my include path (@INC) at runtime? the C<PERLLIB> environment variable, the C<PERL5LIB> environment variable, the C<perl -Idir> command line flag, the C<lib> pragma:, the L<local::lib> module: =item What is socket.ph and where do I get it? =back =item AUTHOR AND COPYRIGHT =back =head2 perlfaq9 - Web, Email and Networking =over 4 =item DESCRIPTION =over 4 =item Should I use a web framework? =item Which web framework should I use? X<framework> X<CGI.pm> X<CGI> X<Catalyst> X<Dancer> L<Catalyst>, L<Dancer>, L<Mojolicious>, L<Web::Simple> =item What is Plack and PSGI? =item How do I remove HTML from a string? =item How do I extract URLs? =item How do I fetch an HTML file? =item How do I automate an HTML form submission? =item How do I decode or create those %-encodings on the web? X<URI> X<URI::Escape> X<RFC 2396> =item How do I redirect to another page? =item How do I put a password on my web pages? =item How do I make sure users can't enter values into a form that causes my CGI script to do bad things? =item How do I parse a mail header? =item How do I check a valid mail address? =item How do I decode a MIME/BASE64 string? =item How do I find the user's mail address? =item How do I send email? L<Email::Sender::Transport::Sendmail>, L<Email::Sender::Transport::SMTP>, L<Email::Sender::Transport::SMTP::TLS> =item How do I use MIME to make an attachment to a mail message? =item How do I read email? =item How do I find out my hostname, domainname, or IP address? X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa, gethostbyname, Socket, Net::Domain, Sys::Hostname> =item How do I fetch/put an (S)FTP file? =item How can I do RPC in Perl? =back =item AUTHOR AND COPYRIGHT =back =head2 perlsyn - Perl syntax =over 4 =item DESCRIPTION =over 4 =item Declarations X<declaration> X<undef> X<undefined> X<uninitialized> =item Comments X<comment> X<#> =item Simple Statements X<statement> X<semicolon> X<expression> X<;> =item Truth and Falsehood X<truth> X<falsehood> X<true> X<false> X<!> X<not> X<negation> X<0> =item Statement Modifiers X<statement modifier> X<modifier> X<if> X<unless> X<while> X<until> X<when> X<foreach> X<for> =item Compound Statements X<statement, compound> X<block> X<bracket, curly> X<curly bracket> X<brace> X<{> X<}> X<if> X<unless> X<given> X<while> X<until> X<foreach> X<for> X<continue> =item Loop Control X<loop control> X<loop, control> X<next> X<last> X<redo> X<continue> =item For Loops X<for> X<foreach> =item Foreach Loops X<for> X<foreach> =item Basic BLOCKs X<block> =item Switch Statements =item Goto X<goto> =item The Ellipsis Statement X<...> X<... statement> X<ellipsis operator> X<elliptical statement> X<unimplemented statement> X<unimplemented operator> X<yada-yada> X<yada-yada operator> X<... operator> X<whatever operator> X<triple-dot operator> =item PODs: Embedded Documentation X<POD> X<documentation> =item Plain Old Comments (Not!) X<comment> X<line> X<#> X<preprocessor> X<eval> =item Experimental Details on given and when =back =back =head2 perldata - Perl data types =over 4 =item DESCRIPTION =over 4 =item Variable names X<variable, name> X<variable name> X<data type> X<type> =item Context X<context> X<scalar context> X<list context> =item Scalar values X<scalar> X<number> X<string> X<reference> =item Scalar value constructors X<scalar, literal> X<scalar, constant> =item List value constructors X<list> =item Subscripts =item Multi-dimensional array emulation =item Slices X<slice> X<array, slice> X<hash, slice> =item Typeglobs and Filehandles X<typeglob> X<filehandle> X<*> =back =item SEE ALSO =back =head2 perlop - Perl operators and precedence =over 4 =item DESCRIPTION =over 4 =item Operator Precedence and Associativity X<operator, precedence> X<precedence> X<associativity> =item Terms and List Operators (Leftward) X<list operator> X<operator, list> X<term> =item The Arrow Operator X<arrow> X<dereference> X<< -> >> =item Auto-increment and Auto-decrement X<increment> X<auto-increment> X<++> X<decrement> X<auto-decrement> X<--> =item Exponentiation X<**> X<exponentiation> X<power> =item Symbolic Unary Operators X<unary operator> X<operator, unary> =item Binding Operators X<binding> X<operator, binding> X<=~> X<!~> =item Multiplicative Operators X<operator, multiplicative> =item Additive Operators X<operator, additive> =item Shift Operators X<shift operator> X<operator, shift> X<<< << >>> X<<< >> >>> X<right shift> X<left shift> X<bitwise shift> X<shl> X<shr> X<shift, right> X<shift, left> =item Named Unary Operators X<operator, named unary> =item Relational Operators X<relational operator> X<operator, relational> =item Equality Operators X<equality> X<equal> X<equals> X<operator, equality> =item Smartmatch Operator 1. Empty hashes or arrays match, 2. That is, each element smartmatches the element of the same index in the other array.[3], 3. If a circular reference is found, fall back to referential equality, 4. Either an actual number, or a string that looks like one =item Bitwise And X<operator, bitwise, and> X<bitwise and> X<&> =item Bitwise Or and Exclusive Or X<operator, bitwise, or> X<bitwise or> X<|> X<operator, bitwise, xor> X<bitwise xor> X<^> =item C-style Logical And X<&&> X<logical and> X<operator, logical, and> =item C-style Logical Or X<||> X<operator, logical, or> =item Logical Defined-Or X<//> X<operator, logical, defined-or> =item Range Operators X<operator, range> X<range> X<..> X<...> =item Conditional Operator X<operator, conditional> X<operator, ternary> X<ternary> X<?:> =item Assignment Operators X<assignment> X<operator, assignment> X<=> X<**=> X<+=> X<*=> X<&=> X<<< <<= >>> X<&&=> X<-=> X</=> X<|=> X<<< >>= >>> X<||=> X<//=> X<.=> X<%=> X<^=> X<x=> =item Comma Operator X<comma> X<operator, comma> X<,> =item List Operators (Rightward) X<operator, list, rightward> X<list operator> =item Logical Not X<operator, logical, not> X<not> =item Logical And X<operator, logical, and> X<and> =item Logical or and Exclusive Or X<operator, logical, or> X<operator, logical, xor> X<operator, logical, exclusive or> X<or> X<xor> =item C Operators Missing From Perl X<operator, missing from perl> X<&> X<*> X<typecasting> X<(TYPE)> unary &, unary *, (TYPE) =item Quote and Quote-like Operators X<operator, quote> X<operator, quote-like> X<q> X<qq> X<qx> X<qw> X<m> X<qr> X<s> X<tr> X<'> X<''> X<"> X<""> X<//> X<`> X<``> X<<< << >>> X<escape sequence> X<escape> [1], [2], [3], [4], [5], [6], [7], [8] =item Regexp Quote-Like Operators X<operator, regexp> qr/STRING/msixpodual X<qr> X</i> X</m> X</o> X</s> X</x> X</p>, m/PATTERN/msixpodualgc X<m> X<operator, match> X<regexp, options> X<regexp> X<regex, options> X<regex> X</m> X</s> X</i> X</x> X</p> X</o> X</g> X</c>, /PATTERN/msixpodualgc, The empty pattern //, Matching in list context, \G assertion, m?PATTERN?msixpodualgc X<?> X<operator, match-once>, ?PATTERN?msixpodualgc, s/PATTERN/REPLACEMENT/msixpodualgcer X<substitute> X<substitution> X<replace> X<regexp, replace> X<regexp, substitute> X</m> X</s> X</i> X</x> X</p> X</o> X</g> X</c> X</e> X</r> =item Quote-Like Operators X<operator, quote-like> q/STRING/ X<q> X<quote, single> X<'> X<''>, 'STRING', qq/STRING/ X<qq> X<quote, double> X<"> X<"">, "STRING", qx/STRING/ X<qx> X<`> X<``> X<backtick>, `STRING`, qw/STRING/ X<qw> X<quote, list> X<quote, words>, tr/SEARCHLIST/REPLACEMENTLIST/cdsr X<tr> X<y> X<transliterate> X</c> X</d> X</s>, y/SEARCHLIST/REPLACEMENTLIST/cdsr, <<EOF X<here-doc> X<heredoc> X<here-document> X<<< << >>>, Double Quotes, Single Quotes, Backticks =item Gory details of parsing quoted constructs X<quote, gory details> Finding the end, Interpolation X<interpolation>, C<<<'EOF'>, C<m''>, the pattern of C<s'''>, C<''>, C<q//>, C<tr'''>, C<y'''>, the replacement of C<s'''>, C<tr///>, C<y///>, C<"">, C<``>, C<qq//>, C<qx//>, C<< <file*glob> >>, C<<<"EOF">, the replacement of C<s///>, C<RE> in C<?RE?>, C</RE/>, C<m/RE/>, C<s/RE/foo/>,, parsing regular expressions X<regexp, parse>, Optimization of regular expressions X<regexp, optimization> =item I/O Operators X<operator, i/o> X<operator, io> X<io> X<while> X<filehandle> X<< <> >> X<@ARGV> =item Constant Folding X<constant folding> X<folding> =item No-ops X<no-op> X<nop> =item Bitwise String Operators X<operator, bitwise, string> =item Integer Arithmetic X<integer> =item Floating-point Arithmetic =item Bigger Numbers X<number, arbitrary precision> =back =back =head2 perlsub - Perl subroutines =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Private Variables via my() X<my> X<variable, lexical> X<lexical> X<lexical variable> X<scope, lexical> X<lexical scope> X<attributes, my> =item Persistent Private Variables X<state> X<state variable> X<static> X<variable, persistent> X<variable, static> X<closure> =item Temporary Values via local() X<local> X<scope, dynamic> X<dynamic scope> X<variable, local> X<variable, temporary> =item Lvalue subroutines X<lvalue> X<subroutine, lvalue> Lvalue subroutines are EXPERIMENTAL =item Passing Symbol Table Entries (typeglobs) X<typeglob> X<*> =item When to Still Use local() X<local> X<variable, local> =item Pass by Reference X<pass by reference> X<pass-by-reference> X<reference> =item Prototypes X<prototype> X<subroutine, prototype> =item Constant Functions X<constant> =item Overriding Built-in Functions X<built-in> X<override> X<CORE> X<CORE::GLOBAL> =item Autoloading X<autoloading> X<AUTOLOAD> =item Subroutine Attributes X<attribute> X<subroutine, attribute> X<attrs> =back =item SEE ALSO =back =head2 perlfunc - Perl builtin functions =over 4 =item DESCRIPTION =over 4 =item Perl Functions by Category X<function> Functions for SCALARs or strings X<scalar> X<string> X<character>, Regular expressions and pattern matching X<regular expression> X<regex> X<regexp>, Numeric functions X<numeric> X<number> X<trigonometric> X<trigonometry>, Functions for real @ARRAYs X<array>, Functions for list data X<list>, Functions for real %HASHes X<hash>, Input and output functions X<I/O> X<input> X<output> X<dbm>, Functions for fixed-length data or records, Functions for filehandles, files, or directories X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink>, Keywords related to the control flow of your Perl program X<control flow>, Keywords related to scoping, Miscellaneous functions, Functions for processes and process groups X<process> X<pid> X<process id>, Keywords related to Perl modules X<module>, Keywords related to classes and object-orientation X<object> X<class> X<package>, Low-level socket functions X<socket> X<sock>, System V interprocess communication functions X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message>, Fetching user and group info X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd>, Fetching network info X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service>, Time-related functions X<time> X<date>, Non-function keywords =item Portability X<portability> X<Unix> X<portable> =item Alphabetical Listing of Perl Functions -I<X> FILEHANDLE X<-r>X<-w>X<-x>X<-o>X<-R>X<-W>X<-X>X<-O>X<-e>X<-z>X<-s>X<-f>X<-d>X<-l>X<-p> X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C>, -I<X> EXPR, -I<X> DIRHANDLE, -I<X>, abs VALUE X<abs> X<absolute>, abs, accept NEWSOCKET,GENERICSOCKET X<accept>, alarm SECONDS X<alarm> X<SIGALRM> X<timer>, alarm, atan2 Y,X X<atan2> X<arctangent> X<tan> X<tangent>, bind SOCKET,NAME X<bind>, binmode FILEHANDLE, LAYER X<binmode> X<binary> X<text> X<DOS> X<Windows>, binmode FILEHANDLE, bless REF,CLASSNAME X<bless>, bless REF, break, caller EXPR X<caller> X<call stack> X<stack> X<stack trace>, caller, chdir EXPR X<chdir> X<cd> X<directory, change>, chdir FILEHANDLE, chdir DIRHANDLE, chdir, chmod LIST X<chmod> X<permission> X<mode>, chomp VARIABLE X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol>, chomp( LIST ), chomp, chop VARIABLE X<chop>, chop( LIST ), chop, chown LIST X<chown> X<owner> X<user> X<group>, chr NUMBER X<chr> X<character> X<ASCII> X<Unicode>, chr, chroot FILENAME X<chroot> X<root>, chroot, close FILEHANDLE X<close>, close, closedir DIRHANDLE X<closedir>, connect SOCKET,NAME X<connect>, continue BLOCK X<continue>, continue, cos EXPR X<cos> X<cosine> X<acos> X<arccosine>, cos, crypt PLAINTEXT,SALT X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> X<decrypt> X<cryptography> X<passwd> X<encrypt>, dbmclose HASH X<dbmclose>, dbmopen HASH,DBNAME,MASK X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm>, defined EXPR X<defined> X<undef> X<undefined>, defined, delete EXPR X<delete>, die LIST X<die> X<throw> X<exception> X<raise> X<$@> X<abort>, do BLOCK X<do> X<block>, do SUBROUTINE(LIST) X<do>, do EXPR X<do>, dump LABEL X<dump> X<core> X<undump>, dump, each HASH X<each> X<hash, iterator>, each ARRAY X<array, iterator>, each EXPR, eof FILEHANDLE X<eof> X<end of file> X<end-of-file>, eof (), eof, eval EXPR X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> X<error, handling> X<exception, handling>, eval BLOCK, eval, evalbytes EXPR X<evalbytes>, evalbytes, exec LIST X<exec> X<execute>, exec PROGRAM LIST, exists EXPR X<exists> X<autovivification>, exit EXPR X<exit> X<terminate> X<abort>, exit, exp EXPR X<exp> X<exponential> X<antilog> X<antilogarithm> X<e>, exp, fc EXPR X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold>, fc, fcntl FILEHANDLE,FUNCTION,SCALAR X<fcntl>, __FILE__ X<__FILE__>, fileno FILEHANDLE X<fileno>, flock FILEHANDLE,OPERATION X<flock> X<lock> X<locking>, fork X<fork> X<child> X<parent>, format X<format>, formline PICTURE,LIST X<formline>, getc FILEHANDLE X<getc> X<getchar> X<character> X<file, read>, getc, getlogin X<getlogin> X<login>, getpeername SOCKET X<getpeername> X<peer>, getpgrp PID X<getpgrp> X<group>, getppid X<getppid> X<parent> X<pid>, getpriority WHICH,WHO X<getpriority> X<priority> X<nice>, getpwnam NAME X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> X<endnetent> X<endprotoent> X<endservent>, getgrnam NAME, gethostbyname NAME, getnetbyname NAME, getprotobyname NAME, getpwuid UID, getgrgid GID, getservbyname NAME,PROTO, gethostbyaddr ADDR,ADDRTYPE, getnetbyaddr ADDR,ADDRTYPE, getprotobynumber NUMBER, getservbyport PORT,PROTO, getpwent, getgrent, gethostent, getnetent, getprotoent, getservent, setpwent, setgrent, sethostent STAYOPEN, setnetent STAYOPEN, setprotoent STAYOPEN, setservent STAYOPEN, endpwent, endgrent, endhostent, endnetent, endprotoent, endservent, getsockname SOCKET X<getsockname>, getsockopt SOCKET,LEVEL,OPTNAME X<getsockopt>, glob EXPR X<glob> X<wildcard> X<filename, expansion> X<expand>, glob, gmtime EXPR X<gmtime> X<UTC> X<Greenwich>, gmtime, goto LABEL X<goto> X<jump> X<jmp>, goto EXPR, goto &NAME, grep BLOCK LIST X<grep>, grep EXPR,LIST, hex EXPR X<hex> X<hexadecimal>, hex, import LIST X<import>, index STR,SUBSTR,POSITION X<index> X<indexOf> X<InStr>, index STR,SUBSTR, int EXPR X<int> X<integer> X<truncate> X<trunc> X<floor>, int, ioctl FILEHANDLE,FUNCTION,SCALAR X<ioctl>, join EXPR,LIST X<join>, keys HASH X<keys> X<key>, keys ARRAY, keys EXPR, kill SIGNAL, LIST, kill SIGNAL X<kill> X<signal>, last LABEL X<last> X<break>, last, lc EXPR X<lc> X<lowercase>, lc, If C<use bytes> is in effect:, On EBCDIC platforms, On ASCII platforms, Otherwise, if C<use locale> (but not C<use locale ':not_characters'>) is in effect:, Otherwise, If EXPR has the UTF8 flag set:, Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'>) is in effect:, Otherwise:, On EBCDIC platforms, On ASCII platforms, lcfirst EXPR X<lcfirst> X<lowercase>, lcfirst, length EXPR X<length> X<size>, length, __LINE__ X<__LINE__>, link OLDFILE,NEWFILE X<link>, listen SOCKET,QUEUESIZE X<listen>, local EXPR X<local>, localtime EXPR X<localtime> X<ctime>, localtime, lock THING X<lock>, log EXPR X<log> X<logarithm> X<e> X<ln> X<base>, log, lstat FILEHANDLE X<lstat>, lstat EXPR, lstat DIRHANDLE, lstat, m//, map BLOCK LIST X<map>, map EXPR,LIST, mkdir FILENAME,MASK X<mkdir> X<md> X<directory, create>, mkdir FILENAME, mkdir, msgctl ID,CMD,ARG X<msgctl>, msgget KEY,FLAGS X<msgget>, msgrcv ID,VAR,SIZE,TYPE,FLAGS X<msgrcv>, msgsnd ID,MSG,FLAGS X<msgsnd>, my EXPR X<my>, my TYPE EXPR, my EXPR : ATTRS, my TYPE EXPR : ATTRS, next LABEL X<next> X<continue>, next, no MODULE VERSION LIST X<no declarations> X<unimporting>, no MODULE VERSION, no MODULE LIST, no MODULE, no VERSION, oct EXPR X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin>, oct, open FILEHANDLE,EXPR X<open> X<pipe> X<file, open> X<fopen>, open FILEHANDLE,MODE,EXPR, open FILEHANDLE,MODE,EXPR,LIST, open FILEHANDLE,MODE,REFERENCE, open FILEHANDLE, opendir DIRHANDLE,EXPR X<opendir>, ord EXPR X<ord> X<encoding>, ord, our EXPR X<our> X<global>, our TYPE EXPR, our EXPR : ATTRS, our TYPE EXPR : ATTRS, pack TEMPLATE,LIST X<pack>, package NAMESPACE, package NAMESPACE VERSION X<package> X<module> X<namespace> X<version>, package NAMESPACE BLOCK, package NAMESPACE VERSION BLOCK X<package> X<module> X<namespace> X<version>, __PACKAGE__ X<__PACKAGE__>, pipe READHANDLE,WRITEHANDLE X<pipe>, pop ARRAY X<pop> X<stack>, pop EXPR, pop, pos SCALAR X<pos> X<match, position>, pos, print FILEHANDLE LIST X<print>, print FILEHANDLE, print LIST, print, printf FILEHANDLE FORMAT, LIST X<printf>, printf FILEHANDLE, printf FORMAT, LIST, printf, prototype FUNCTION X<prototype>, push ARRAY,LIST X<push> X<stack>, push EXPR,LIST, q/STRING/, qq/STRING/, qw/STRING/, qx/STRING/, qr/STRING/, quotemeta EXPR X<quotemeta> X<metacharacter>, quotemeta, rand EXPR X<rand> X<random>, rand, read FILEHANDLE,SCALAR,LENGTH,OFFSET X<read> X<file, read>, read FILEHANDLE,SCALAR,LENGTH, readdir DIRHANDLE X<readdir>, readline EXPR, readline X<readline> X<gets> X<fgets>, readlink EXPR X<readlink>, readlink, readpipe EXPR, readpipe X<readpipe>, recv SOCKET,SCALAR,LENGTH,FLAGS X<recv>, redo LABEL X<redo>, redo, ref EXPR X<ref> X<reference>, ref, rename OLDNAME,NEWNAME X<rename> X<move> X<mv> X<ren>, require VERSION X<require>, require EXPR, require, reset EXPR X<reset>, reset, return EXPR X<return>, return, reverse LIST X<reverse> X<rev> X<invert>, rewinddir DIRHANDLE X<rewinddir>, rindex STR,SUBSTR,POSITION X<rindex>, rindex STR,SUBSTR, rmdir FILENAME X<rmdir> X<rd> X<directory, remove>, rmdir, s///, say FILEHANDLE LIST X<say>, say FILEHANDLE, say LIST, say, scalar EXPR X<scalar> X<context>, seek FILEHANDLE,POSITION,WHENCE X<seek> X<fseek> X<filehandle, position>, seekdir DIRHANDLE,POS X<seekdir>, select FILEHANDLE X<select> X<filehandle, default>, select, select RBITS,WBITS,EBITS,TIMEOUT X<select>, semctl ID,SEMNUM,CMD,ARG X<semctl>, semget KEY,NSEMS,FLAGS X<semget>, semop KEY,OPSTRING X<semop>, send SOCKET,MSG,FLAGS,TO X<send>, send SOCKET,MSG,FLAGS, setpgrp PID,PGRP X<setpgrp> X<group>, setpriority WHICH,WHO,PRIORITY X<setpriority> X<priority> X<nice> X<renice>, setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL X<setsockopt>, shift ARRAY X<shift>, shift EXPR, shift, shmctl ID,CMD,ARG X<shmctl>, shmget KEY,SIZE,FLAGS X<shmget>, shmread ID,VAR,POS,SIZE X<shmread> X<shmwrite>, shmwrite ID,STRING,POS,SIZE, shutdown SOCKET,HOW X<shutdown>, sin EXPR X<sin> X<sine> X<asin> X<arcsine>, sin, sleep EXPR X<sleep> X<pause>, sleep, socket SOCKET,DOMAIN,TYPE,PROTOCOL X<socket>, socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL X<socketpair>, sort SUBNAME LIST X<sort> X<qsort> X<quicksort> X<mergesort>, sort BLOCK LIST, sort LIST, splice ARRAY or EXPR,OFFSET,LENGTH,LIST X<splice>, splice ARRAY or EXPR,OFFSET,LENGTH, splice ARRAY or EXPR,OFFSET, splice ARRAY or EXPR, split /PATTERN/,EXPR,LIMIT X<split>, split /PATTERN/,EXPR, split /PATTERN/, split, sprintf FORMAT, LIST X<sprintf>, format parameter index, flags, vector flag, (minimum) width, precision, or maximum width X<precision>, size, order of arguments, sqrt EXPR X<sqrt> X<root> X<square root>, sqrt, srand EXPR X<srand> X<seed> X<randseed>, srand, stat FILEHANDLE X<stat> X<file, status> X<ctime>, stat EXPR, stat DIRHANDLE, stat, state EXPR X<state>, state TYPE EXPR, state EXPR : ATTRS, state TYPE EXPR : ATTRS, study SCALAR X<study>, study, sub NAME BLOCK X<sub>, sub NAME (PROTO) BLOCK, sub NAME : ATTRS BLOCK, sub NAME (PROTO) : ATTRS BLOCK, __SUB__ X<__SUB__>, substr EXPR,OFFSET,LENGTH,REPLACEMENT X<substr> X<substring> X<mid> X<left> X<right>, substr EXPR,OFFSET,LENGTH, substr EXPR,OFFSET, symlink OLDFILE,NEWFILE X<symlink> X<link> X<symbolic link> X<link, symbolic>, syscall NUMBER, LIST X<syscall> X<system call>, sysopen FILEHANDLE,FILENAME,MODE X<sysopen>, sysopen FILEHANDLE,FILENAME,MODE,PERMS, sysread FILEHANDLE,SCALAR,LENGTH,OFFSET X<sysread>, sysread FILEHANDLE,SCALAR,LENGTH, sysseek FILEHANDLE,POSITION,WHENCE X<sysseek> X<lseek>, system LIST X<system> X<shell>, system PROGRAM LIST, syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET X<syswrite>, syswrite FILEHANDLE,SCALAR,LENGTH, syswrite FILEHANDLE,SCALAR, tell FILEHANDLE X<tell>, tell, telldir DIRHANDLE X<telldir>, tie VARIABLE,CLASSNAME,LIST X<tie>, tied VARIABLE X<tied>, time X<time> X<epoch>, times X<times>, tr///, truncate FILEHANDLE,LENGTH X<truncate>, truncate EXPR,LENGTH, uc EXPR X<uc> X<uppercase> X<toupper>, uc, ucfirst EXPR X<ucfirst> X<uppercase>, ucfirst, umask EXPR X<umask>, umask, undef EXPR X<undef> X<undefine>, undef, unlink LIST X<unlink> X<delete> X<remove> X<rm> X<del>, unlink, unpack TEMPLATE,EXPR X<unpack>, unpack TEMPLATE, unshift ARRAY,LIST X<unshift>, unshift EXPR,LIST, untie VARIABLE X<untie>, use Module VERSION LIST X<use> X<module> X<import>, use Module VERSION, use Module LIST, use Module, use VERSION, utime LIST X<utime>, values HASH X<values>, values ARRAY, values EXPR, vec EXPR,OFFSET,BITS X<vec> X<bit> X<bit vector>, wait X<wait>, waitpid PID,FLAGS X<waitpid>, wantarray X<wantarray> X<context>, warn LIST X<warn> X<warning> X<STDERR>, write FILEHANDLE X<write>, write EXPR, write, y/// =item Non-function Keywords by Cross-reference __DATA__, __END__, BEGIN, CHECK, END, INIT, UNITCHECK, DESTROY, and, cmp, eq, ge, gt, if, le, lt, ne, not, or, x, xor, AUTOLOAD, else, elseif, elsif, for, foreach, unless, until, while, default, given, when =back =back =head2 perlopentut - tutorial on opening things in Perl =over 4 =item DESCRIPTION =item Open E<agrave> la shell =over 4 =item Simple Opens =item Indirect Filehandles =item Pipe Opens =item The Minus File =item Mixing Reads and Writes =item Filters =back =item Open E<agrave> la C =over 4 =item Permissions E<agrave> la mode =back =item Obscure Open Tricks =over 4 =item Re-Opening Files (dups) =item Dispelling the Dweomer =item Paths as Opens =item Single Argument Open =item Playing with STDIN and STDOUT =back =item Other I/O Issues =over 4 =item Opening Non-File Files =item Opening Named Pipes =item Opening Sockets =item Binary Files =item File Locking =item IO Layers =back =item SEE ALSO =item AUTHOR and COPYRIGHT =item HISTORY =back =head2 perlpacktut - tutorial on C<pack> and C<unpack> =over 4 =item DESCRIPTION =item The Basic Principle =item Packing Text =item Packing Numbers =over 4 =item Integers =item Unpacking a Stack Frame =item How to Eat an Egg on a Net =item Byte-order modifiers =item Floating point Numbers =back =item Exotic Templates =over 4 =item Bit Strings =item Uuencoding =item Doing Sums =item Unicode =item Another Portable Binary Encoding =back =item Template Grouping =item Lengths and Widths =over 4 =item String Lengths =item Dynamic Templates =item Counting Repetitions =item Intel HEX =back =item Packing and Unpacking C Structures =over 4 =item The Alignment Pit =item Dealing with Endian-ness =item Alignment, Take 2 =item Alignment, Take 3 =item Pointers for How to Use Them =back =item Pack Recipes =item Funnies Section =item Authors =back =head2 perlpod - the Plain Old Documentation format =over 4 =item DESCRIPTION =over 4 =item Ordinary Paragraph X<POD, ordinary paragraph> =item Verbatim Paragraph X<POD, verbatim paragraph> X<verbatim> =item Command Paragraph X<POD, command> C<=head1 I<Heading Text>> X<=head1> X<=head2> X<=head3> X<=head4> X<head1> X<head2> X<head3> X<head4>, C<=head2 I<Heading Text>>, C<=head3 I<Heading Text>>, C<=head4 I<Heading Text>>, C<=over I<indentlevel>> X<=over> X<=item> X<=back> X<over> X<item> X<back>, C<=item I<stuff...>>, C<=back>, C<=cut> X<=cut> X<cut>, C<=pod> X<=pod> X<pod>, C<=begin I<formatname>> X<=begin> X<=end> X<=for> X<begin> X<end> X<for>, C<=end I<formatname>>, C<=for I<formatname> I<text...>>, C<=encoding I<encodingname>> X<=encoding> X<encoding> =item Formatting Codes X<POD, formatting code> X<formatting code> X<POD, interior sequence> X<interior sequence> C<IE<lt>textE<gt>> -- italic text X<I> X<< IZ<><> >> X<POD, formatting code, italic> X<italic>, C<BE<lt>textE<gt>> -- bold text X<B> X<< BZ<><> >> X<POD, formatting code, bold> X<bold>, C<CE<lt>codeE<gt>> -- code text X<C> X<< CZ<><> >> X<POD, formatting code, code> X<code>, C<LE<lt>nameE<gt>> -- a hyperlink X<L> X<< LZ<><> >> X<POD, formatting code, hyperlink> X<hyperlink>, C<EE<lt>escapeE<gt>> -- a character escape X<E> X<< EZ<><> >> X<POD, formatting code, escape> X<escape>, C<FE<lt>filenameE<gt>> -- used for filenames X<F> X<< FZ<><> >> X<POD, formatting code, filename> X<filename>, C<SE<lt>textE<gt>> -- text contains non-breaking spaces X<S> X<< SZ<><> >> X<POD, formatting code, non-breaking space> X<non-breaking space>, C<XE<lt>topic nameE<gt>> -- an index entry X<X> X<< XZ<><> >> X<POD, formatting code, index entry> X<index entry>, C<ZE<lt>E<gt>> -- a null (zero-effect) formatting code X<Z> X<< ZZ<><> >> X<POD, formatting code, null> X<null> =item The Intent X<POD, intent of> =item Embedding Pods in Perl Modules X<POD, embedding> =item Hints for Writing Pod X<podchecker> X<POD, validating> =back =item SEE ALSO =item AUTHOR =back =head2 perlpodspec - Plain Old Documentation: format specification and notes =over 4 =item DESCRIPTION =item Pod Definitions =item Pod Commands "=head1", "=head2", "=head3", "=head4", "=pod", "=cut", "=over", "=item", "=back", "=begin formatname", "=begin formatname parameter", "=end formatname", "=for formatname text...", "=encoding encodingname" =item Pod Formatting Codes C<IE<lt>textE<gt>> -- italic text, C<BE<lt>textE<gt>> -- bold text, C<CE<lt>codeE<gt>> -- code text, C<FE<lt>filenameE<gt>> -- style for filenames, C<XE<lt>topic nameE<gt>> -- an index entry, C<ZE<lt>E<gt>> -- a null (zero-effect) formatting code, C<LE<lt>nameE<gt>> -- a hyperlink, C<EE<lt>escapeE<gt>> -- a character escape, C<SE<lt>textE<gt>> -- text contains non-breaking spaces =item Notes on Implementing Pod Processors =item About LE<lt>...E<gt> Codes First:, Second:, Third:, Fourth:, Fifth:, Sixth: =item About =over...=back Regions =item About Data Paragraphs and "=begin/=end" Regions =item SEE ALSO =item AUTHOR =back =head2 perlpodstyle - Perl POD style guide =over 4 =item DESCRIPTION bold (BE<lt>E<gt>), italic (IE<lt>E<gt>), code (CE<lt>E<gt>), files (FE<lt>E<gt>), NAME, SYNOPSIS, DESCRIPTION, OPTIONS, RETURN VALUE, ERRORS, DIAGNOSTICS, EXAMPLES, ENVIRONMENT, FILES, CAVEATS, BUGS, RESTRICTIONS, NOTES, AUTHOR, HISTORY, COPYRIGHT AND LICENSE, SEE ALSO =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 perlrun - how to execute the Perl interpreter =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item #! and quoting on non-Unix systems X<hashbang> X<#!> OS/2, MS-DOS, Win95/NT, VMS =item Location of Perl X<perl, location of interpreter> =item Command Switches X<perl, command switches> X<command switches> B<-0>[I<octal/hexadecimal>] X<-0> X<$/>, B<-a> X<-a> X<autosplit>, B<-C [I<number/list>]> X<-C>, B<-c> X<-c>, B<-d> X<-d> X<-dt>, B<-dt>, B<-d:>I<MOD[=bar,baz]> X<-d> X<-dt>, B<-dt:>I<MOD[=bar,baz]>, B<-D>I<letters> X<-D> X<DEBUGGING> X<-DDEBUGGING>, B<-D>I<number>, B<-e> I<commandline> X<-e>, B<-E> I<commandline> X<-E>, B<-f> X<-f> X<sitecustomize> X<sitecustomize.pl>, B<-F>I<pattern> X<-F>, B<-h> X<-h>, B<-i>[I<extension>] X<-i> X<in-place>, B<-I>I<directory> X<-I> X<@INC>, B<-l>[I<octnum>] X<-l> X<$/> X<$\>, B<-m>[B<->]I<module> X<-m> X<-M>, B<-M>[B<->]I<module>, B<-M>[B<->]I<'module ...'>, B<-[mM]>[B<->]I<module=arg[,arg]...>, B<-n> X<-n>, B<-p> X<-p>, B<-s> X<-s>, B<-S> X<-S>, B<-t> X<-t>, B<-T> X<-T>, B<-u> X<-u>, B<-U> X<-U>, B<-v> X<-v>, B<-V> X<-V>, B<-V:>I<configvar>, B<-w> X<-w>, B<-W> X<-W>, B<-X> X<-X>, B<-x> X<-x>, B<-x>I<directory> =back =item ENVIRONMENT X<perl, environment variables> HOME X<HOME>, LOGDIR X<LOGDIR>, PATH X<PATH>, PERL5LIB X<PERL5LIB>, PERL5OPT X<PERL5OPT>, PERLIO X<PERLIO>, :bytes X<:bytes>, :crlf X<:crlf>, :mmap X<:mmap>, :perlio X<:perlio>, :pop X<:pop>, :raw X<:raw>, :stdio X<:stdio>, :unix X<:unix>, :utf8 X<:utf8>, :win32 X<:win32>, PERLIO_DEBUG X<PERLIO_DEBUG>, PERLLIB X<PERLLIB>, PERL5DB X<PERL5DB>, PERL5DB_THREADED X<PERL5DB_THREADED>, PERL5SHELL (specific to the Win32 port) X<PERL5SHELL>, PERL_ALLOW_NON_IFS_LSP (specific to the Win32 port) X<PERL_ALLOW_NON_IFS_LSP>, PERL_DEBUG_MSTATS X<PERL_DEBUG_MSTATS>, PERL_DESTRUCT_LEVEL X<PERL_DESTRUCT_LEVEL>, PERL_DL_NONLAZY X<PERL_DL_NONLAZY>, PERL_ENCODING X<PERL_ENCODING>, PERL_HASH_SEED X<PERL_HASH_SEED>, PERL_HASH_SEED_DEBUG X<PERL_HASH_SEED_DEBUG>, PERL_MEM_LOG X<PERL_MEM_LOG>, PERL_ROOT (specific to the VMS port) X<PERL_ROOT>, PERL_SIGNALS X<PERL_SIGNALS>, PERL_UNICODE X<PERL_UNICODE>, SYS$LOGIN (specific to the VMS port) X<SYS$LOGIN> =back =head2 perldiag - various Perl diagnostics =over 4 =item DESCRIPTION =item SEE ALSO =back =head2 perllexwarn - Perl Lexical Warnings =over 4 =item DESCRIPTION =over 4 =item Default Warnings and Optional Warnings =item What's wrong with B<-w> and C<$^W> =item Controlling Warnings from the Command Line B<-w> X<-w>, B<-W> X<-W>, B<-X> X<-X> =item Backward Compatibility =item Category Hierarchy X<warning, categories> =item Fatal Warnings X<warning, fatal> =item Reporting Warnings from a Module X<warning, reporting> X<warning, registering> =back =item SEE ALSO =item AUTHOR =back =head2 perldebug - Perl debugging =over 4 =item DESCRIPTION =item The Perl Debugger =over 4 =item Calling the Debugger perl -d program_name, perl -d -e 0, perl -d:Ptkdb program_name, perl -dt threaded_program_name =item Debugger Commands h X<debugger command, h>, h [command], h h, p expr X<debugger command, p>, x [maxdepth] expr X<debugger command, x>, V [pkg [vars]] X<debugger command, V>, X [vars] X<debugger command, X>, y [level [vars]] X<debugger command, y>, T X<debugger command, T> X<backtrace> X<stack, backtrace>, s [expr] X<debugger command, s> X<step>, n [expr] X<debugger command, n>, r X<debugger command, r>, <CR>, c [line|sub] X<debugger command, c>, l X<debugger command, l>, l min+incr, l min-max, l line, l subname, - X<debugger command, ->, v [line] X<debugger command, v>, . X<debugger command, .>, f filename X<debugger command, f>, /pattern/, ?pattern?, L [abw] X<debugger command, L>, S [[!]regex] X<debugger command, S>, t [n] X<debugger command, t>, t [n] expr X<debugger command, t>, b X<breakpoint> X<debugger command, b>, b [line] [condition] X<breakpoint> X<debugger command, b>, b [file]:[line] [condition] X<breakpoint> X<debugger command, b>, b subname [condition] X<breakpoint> X<debugger command, b>, b postpone subname [condition] X<breakpoint> X<debugger command, b>, b load filename X<breakpoint> X<debugger command, b>, b compile subname X<breakpoint> X<debugger command, b>, B line X<breakpoint> X<debugger command, B>, B * X<breakpoint> X<debugger command, B>, disable [file]:[line] X<breakpoint> X<debugger command, disable> X<disable>, disable [line] X<breakpoint> X<debugger command, disable> X<disable>, enable [file]:[line] X<breakpoint> X<debugger command, disable> X<disable>, enable [line] X<breakpoint> X<debugger command, disable> X<disable>, a [line] command X<debugger command, a>, A line X<debugger command, A>, A * X<debugger command, A>, w expr X<debugger command, w>, W expr X<debugger command, W>, W * X<debugger command, W>, o X<debugger command, o>, o booloption ... X<debugger command, o>, o anyoption? ... X<debugger command, o>, o option=value ... X<debugger command, o>, < ? X<< debugger command, < >>, < [ command ] X<< debugger command, < >>, < * X<< debugger command, < >>, << command X<< debugger command, << >>, > ? X<< debugger command, > >>, > command X<< debugger command, > >>, > * X<< debugger command, > >>, >> command X<<< debugger command, >> >>>, { ? X<debugger command, {>, { [ command ], { * X<debugger command, {>, {{ command X<debugger command, {{>, ! number X<debugger command, !>, ! -number X<debugger command, !>, ! pattern X<debugger command, !>, !! cmd X<debugger command, !!>, source file X<debugger command, source>, H -number X<debugger command, H>, q or ^D X<debugger command, q> X<debugger command, ^D>, R X<debugger command, R>, |dbcmd X<debugger command, |>, ||dbcmd X<debugger command, ||>, command, m expr X<debugger command, m>, M X<debugger command, M>, man [manpage] X<debugger command, man> =item Configurable Options C<recallCommand>, C<ShellBang> X<debugger option, recallCommand> X<debugger option, ShellBang>, C<pager> X<debugger option, pager>, C<tkRunning> X<debugger option, tkRunning>, C<signalLevel>, C<warnLevel>, C<dieLevel> X<debugger option, signalLevel> X<debugger option, warnLevel> X<debugger option, dieLevel>, C<AutoTrace> X<debugger option, AutoTrace>, C<LineInfo> X<debugger option, LineInfo>, C<inhibit_exit> X<debugger option, inhibit_exit>, C<PrintRet> X<debugger option, PrintRet>, C<ornaments> X<debugger option, ornaments>, C<frame> X<debugger option, frame>, C<maxTraceLen> X<debugger option, maxTraceLen>, C<windowSize> X<debugger option, windowSize>, C<arrayDepth>, C<hashDepth> X<debugger option, arrayDepth> X<debugger option, hashDepth>, C<dumpDepth> X<debugger option, dumpDepth>, C<compactDump>, C<veryCompact> X<debugger option, compactDump> X<debugger option, veryCompact>, C<globPrint> X<debugger option, globPrint>, C<DumpDBFiles> X<debugger option, DumpDBFiles>, C<DumpPackages> X<debugger option, DumpPackages>, C<DumpReused> X<debugger option, DumpReused>, C<quote>, C<HighBit>, C<undefPrint> X<debugger option, quote> X<debugger option, HighBit> X<debugger option, undefPrint>, C<UsageOnly> X<debugger option, UsageOnly>, C<TTY> X<debugger option, TTY>, C<noTTY> X<debugger option, noTTY>, C<ReadLine> X<debugger option, ReadLine>, C<NonStop> X<debugger option, NonStop> =item Debugger Input/Output Prompt, Multiline commands, Stack backtrace X<backtrace> X<stack, backtrace>, Line Listing Format, Frame listing =item Debugging Compile-Time Statements =item Debugger Customization =item Readline Support / History in the Debugger =item Editor Support for Debugging =item The Perl Profiler X<profile> X<profiling> X<profiler> =back =item Debugging Regular Expressions X<regular expression, debugging> X<regex, debugging> X<regexp, debugging> =item Debugging Memory Usage X<memory usage> =item SEE ALSO =item BUGS =back =head2 perlvar - Perl predefined variables =over 4 =item DESCRIPTION =over 4 =item The Syntax of Variable Names =back =item SPECIAL VARIABLES =over 4 =item General Variables $ARG, $_ X<$_> X<$ARG>, @ARG, @_ X<@_> X<@ARG>, $LIST_SEPARATOR, $" X<$"> X<$LIST_SEPARATOR>, $PROCESS_ID, $PID, $$ X<$$> X<$PID> X<$PROCESS_ID>, $PROGRAM_NAME, $0 X<$0> X<$PROGRAM_NAME>, $REAL_GROUP_ID, $GID, $( X<$(> X<$GID> X<$REAL_GROUP_ID>, $EFFECTIVE_GROUP_ID, $EGID, $) X<$)> X<$EGID> X<$EFFECTIVE_GROUP_ID>, $REAL_USER_ID, $UID, $< X<< $< >> X<$UID> X<$REAL_USER_ID>, $EFFECTIVE_USER_ID, $EUID, $> X<< $> >> X<$EUID> X<$EFFECTIVE_USER_ID>, $SUBSCRIPT_SEPARATOR, $SUBSEP, $; X<$;> X<$SUBSEP> X<SUBSCRIPT_SEPARATOR>, $a, $b X<$a> X<$b>, %ENV X<%ENV>, $SYSTEM_FD_MAX, $^F X<$^F> X<$SYSTEM_FD_MAX>, @F X<@F>, @INC X<@INC>, %INC X<%INC>, $INPLACE_EDIT, $^I X<$^I> X<$INPLACE_EDIT>, $^M X<$^M>, $OSNAME, $^O X<$^O> X<$OSNAME>, %SIG X<%SIG>, $BASETIME, $^T X<$^T> X<$BASETIME>, $PERL_VERSION, $^V X<$^V> X<$PERL_VERSION>, ${^WIN32_SLOPPY_STAT} X<${^WIN32_SLOPPY_STAT}> X<sitecustomize> X<sitecustomize.pl>, $EXECUTABLE_NAME, $^X X<$^X> X<$EXECUTABLE_NAME> =item Variables related to regular expressions $<I<digits>> ($1, $2, ...) X<$1> X<$2> X<$3>, $MATCH, $& X<$&> X<$MATCH>, ${^MATCH} X<${^MATCH}>, $PREMATCH, $` X<$`> X<$PREMATCH> X<${^PREMATCH}>, ${^PREMATCH} X<$`> X<${^PREMATCH}>, $POSTMATCH, $' X<$'> X<$POSTMATCH> X<${^POSTMATCH}> X<@->, ${^POSTMATCH} X<${^POSTMATCH}> X<$'> X<$POSTMATCH>, $LAST_PAREN_MATCH, $+ X<$+> X<$LAST_PAREN_MATCH>, $LAST_SUBMATCH_RESULT, $^N X<$^N> X<$LAST_SUBMATCH_RESULT>, @LAST_MATCH_END, @+ X<@+> X<@LAST_MATCH_END>, %LAST_PAREN_MATCH, %+ X<%+> X<%LAST_PAREN_MATCH>, @LAST_MATCH_START, @- X<@-> X<@LAST_MATCH_START>, C<$`> is the same as C<substr($var, 0, $-[0])>, C<$&> is the same as C<substr($var, $-[0], $+[0] - $-[0])>, C<$'> is the same as C<substr($var, $+[0])>, C<$1> is the same as C<substr($var, $-[1], $+[1] - $-[1])>, C<$2> is the same as C<substr($var, $-[2], $+[2] - $-[2])>, C<$3> is the same as C<substr($var, $-[3], $+[3] - $-[3])>, %LAST_MATCH_START, %- X<%-> X<%LAST_MATCH_START>, $LAST_REGEXP_CODE_RESULT, $^R X<$^R> X<$LAST_REGEXP_CODE_RESULT>, ${^RE_DEBUG_FLAGS} X<${^RE_DEBUG_FLAGS}>, ${^RE_TRIE_MAXBUF} X<${^RE_TRIE_MAXBUF}> =item Variables related to filehandles $ARGV X<$ARGV>, @ARGV X<@ARGV>, ARGV X<ARGV>, ARGVOUT X<ARGVOUT>, Handle->output_field_separator( EXPR ), $OUTPUT_FIELD_SEPARATOR, $OFS, $, X<$,> X<$OFS> X<$OUTPUT_FIELD_SEPARATOR>, HANDLE->input_line_number( EXPR ), $INPUT_LINE_NUMBER, $NR, $. X<$.> X<$NR> X<$INPUT_LINE_NUMBER> X<line number>, HANDLE->input_record_separator( EXPR ), $INPUT_RECORD_SEPARATOR, $RS, $/ X<$/> X<$RS> X<$INPUT_RECORD_SEPARATOR>, Handle->output_record_separator( EXPR ), $OUTPUT_RECORD_SEPARATOR, $ORS, $\ X<$\> X<$ORS> X<$OUTPUT_RECORD_SEPARATOR>, HANDLE->autoflush( EXPR ), $OUTPUT_AUTOFLUSH, $| X<$|> X<autoflush> X<flush> X<$OUTPUT_AUTOFLUSH>, $ACCUMULATOR, $^A X<$^A> X<$ACCUMULATOR>, HANDLE->format_formfeed(EXPR), $FORMAT_FORMFEED, $^L X<$^L> X<$FORMAT_FORMFEED>, HANDLE->format_page_number(EXPR), $FORMAT_PAGE_NUMBER, $% X<$%> X<$FORMAT_PAGE_NUMBER>, HANDLE->format_lines_left(EXPR), $FORMAT_LINES_LEFT, $- X<$-> X<$FORMAT_LINES_LEFT>, Handle->format_line_break_characters EXPR, $FORMAT_LINE_BREAK_CHARACTERS, $: X<$:> X<FORMAT_LINE_BREAK_CHARACTERS>, HANDLE->format_lines_per_page(EXPR), $FORMAT_LINES_PER_PAGE, $= X<$=> X<$FORMAT_LINES_PER_PAGE>, HANDLE->format_top_name(EXPR), $FORMAT_TOP_NAME, $^ X<$^> X<$FORMAT_TOP_NAME>, HANDLE->format_name(EXPR), $FORMAT_NAME, $~ X<$~> X<$FORMAT_NAME> =item Error Variables X<error> X<exception> ${^CHILD_ERROR_NATIVE} X<$^CHILD_ERROR_NATIVE>, $EXTENDED_OS_ERROR, $^E X<$^E> X<$EXTENDED_OS_ERROR>, $EXCEPTIONS_BEING_CAUGHT, $^S X<$^S> X<$EXCEPTIONS_BEING_CAUGHT>, $WARNING, $^W X<$^W> X<$WARNING>, ${^WARNING_BITS} X<${^WARNING_BITS}>, $OS_ERROR, $ERRNO, $! X<$!> X<$ERRNO> X<$OS_ERROR>, %OS_ERROR, %ERRNO, %! X<%!> X<%OS_ERROR> X<%ERRNO>, $CHILD_ERROR, $? X<$?> X<$CHILD_ERROR>, $EVAL_ERROR, $@ X<$@> X<$EVAL_ERROR> =item Variables related to the interpreter state $COMPILING, $^C X<$^C> X<$COMPILING>, $DEBUGGING, $^D X<$^D> X<$DEBUGGING>, ${^ENCODING} X<${^ENCODING}>, ${^GLOBAL_PHASE} X<${^GLOBAL_PHASE}>, CONSTRUCT, START, CHECK, INIT, RUN, END, DESTRUCT, $^H X<$^H>, %^H X<%^H>, ${^OPEN} X<${^OPEN}>, $PERLDB, $^P X<$^P> X<$PERLDB>, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, ${^TAINT} X<${^TAINT}>, ${^UNICODE} X<${^UNICODE}>, ${^UTF8CACHE} X<${^UTF8CACHE}>, ${^UTF8LOCALE} X<${^UTF8LOCALE}> =item Deprecated and removed variables $OFMT, $# X<$#> X<$OFMT>, $* X<$*>, $ARRAY_BASE, $[ X<$[> X<$ARRAY_BASE>, $OLD_PERL_VERSION, $] X<$]> X<$OLD_PERL_VERSION> =back =back =head2 perlre - Perl regular expressions =over 4 =item DESCRIPTION =over 4 =item Modifiers m X</m> X<regex, multiline> X<regexp, multiline> X<regular expression, multiline>, s X</s> X<regex, single-line> X<regexp, single-line> X<regular expression, single-line>, i X</i> X<regex, case-insensitive> X<regexp, case-insensitive> X<regular expression, case-insensitive>, x X</x>, p X</p> X<regex, preserve> X<regexp, preserve>, g and c X</g> X</c>, a, d, l and u X</a> X</d> X</l> X</u> =item Regular Expressions [1], [2], [3], [4], [5], [6], [7] =item Quoting metacharacters =item Extended Patterns C<(?#text)> X<(?#)>, C<(?adlupimsx-imsx)>, C<(?^alupimsx)> X<(?)> X<(?^)>, C<(?:pattern)> X<(?:)>, C<(?adluimsx-imsx:pattern)>, C<(?^aluimsx:pattern)> X<(?^:)>, C<(?|pattern)> X<(?|)> X<Branch reset>, Look-Around Assertions X<look-around assertion> X<lookaround assertion> X<look-around> X<lookaround>, C<(?=pattern)> X<(?=)> X<look-ahead, positive> X<lookahead, positive>, C<(?!pattern)> X<(?!)> X<look-ahead, negative> X<lookahead, negative>, C<(?<=pattern)> C<\K> X<(?<=)> X<look-behind, positive> X<lookbehind, positive> X<\K>, C<(?<!pattern)> X<(?<!)> X<look-behind, negative> X<lookbehind, negative>, C<(?'NAME'pattern)>, C<< (?<NAME>pattern) >> X<< (?<NAME>) >> X<(?'NAME')> X<named capture> X<capture>, C<< \k<NAME> >>, C<< \k'NAME' >>, C<(?{ code })> X<(?{})> X<regex, code in> X<regexp, code in> X<regular expression, code in>, C<(??{ code })> X<(??{})> X<regex, postponed> X<regexp, postponed> X<regular expression, postponed>, C<(?PARNO)> C<(?-PARNO)> C<(?+PARNO)> C<(?R)> C<(?0)> X<(?PARNO)> X<(?1)> X<(?R)> X<(?0)> X<(?-1)> X<(?+1)> X<(?-PARNO)> X<(?+PARNO)> X<regex, recursive> X<regexp, recursive> X<regular expression, recursive> X<regex, relative recursion>, C<(?&NAME)> X<(?&NAME)>, C<(?(condition)yes-pattern|no-pattern)> X<(?()>, C<(?(condition)yes-pattern)>, (1) (2) .., (<NAME>) ('NAME'), (?=...) (?!...) (?<=...) (?<!...), (?{ CODE }), (R), (R1) (R2) .., (R&NAME), (DEFINE), C<< (?>pattern) >> X<backtrack> X<backtracking> X<atomic> X<possessive> =item Special Backtracking Control Verbs Verbs that take an argument, C<(*PRUNE)> C<(*PRUNE:NAME)> X<(*PRUNE)> X<(*PRUNE:NAME)>, C<(*SKIP)> C<(*SKIP:NAME)> X<(*SKIP)>, C<(*MARK:NAME)> C<(*:NAME)> X<(*MARK)> X<(*MARK:NAME)> X<(*:NAME)>, C<(*THEN)> C<(*THEN:NAME)>, Verbs without an argument, C<(*COMMIT)> X<(*COMMIT)>, C<(*FAIL)> C<(*F)> X<(*FAIL)> X<(*F)>, C<(*ACCEPT)> X<(*ACCEPT)> =item Backtracking X<backtrack> X<backtracking> =item Version 8 Regular Expressions X<regular expression, version 8> X<regex, version 8> X<regexp, version 8> =item Warning on \1 Instead of $1 =item Repeated Patterns Matching a Zero-length Substring =item Combining RE Pieces C<ST>, C<S|T>, C<S{REPEAT_COUNT}>, C<S{min,max}>, C<S{min,max}?>, C<S?>, C<S*>, C<S+>, C<S??>, C<S*?>, C<S+?>, C<< (?>S) >>, C<(?=S)>, C<(?<=S)>, C<(?!S)>, C<(?<!S)>, C<(??{ EXPR })>, C<(?PARNO)>, C<(?(condition)yes-pattern|no-pattern)> =item Creating Custom RE Engines =item PCRE/Python Support C<< (?PE<lt>NAMEE<gt>pattern) >>, C<< (?P=NAME) >>, C<< (?P>NAME) >> =back =item BUGS =item SEE ALSO =back =head2 perlrebackslash - Perl Regular Expression Backslash Sequences and Escapes =over 4 =item DESCRIPTION =over 4 =item The backslash [1] =item All the sequences and escapes =item Character Escapes [1], [2] =item Modifiers =item Character classes =item Referencing =item Assertions \A, \z, \Z, \G, \b, \B =item Misc \C, \K, \N, \R X<\R>, \X X<\X> =back =back =head2 perlrecharclass - Perl Regular Expression Character Classes =over 4 =item DESCRIPTION =over 4 =item The dot =item Backslash sequences X<\w> X<\W> X<\s> X<\S> X<\d> X<\D> X<\p> X<\P> X<\N> X<\v> X<\V> X<\h> X<\H> X<word> X<whitespace> If the C</a> modifier is in effect .., otherwise .., For code points above 255 .., For code points below 256 .., if locale rules are in effect .., if Unicode rules are in effect or if on an EBCDIC platform .., otherwise .., If the C</a> modifier is in effect .., otherwise .., For code points above 255 .., For code points below 256 .., if locale rules are in effect .., if Unicode rules are in effect or if on an EBCDIC platform .., otherwise .., [1] =item Bracketed Character Classes [1], [2], [3], [4], [5], [6], If the C</a> modifier, is in effect .., otherwise .., For code points above 255 .., For code points below 256 .., if locale rules are in effect .., if Unicode rules are in effect or if on an EBCDIC platform .., otherwise .. =back =back =head2 perlreref - Perl Regular Expressions Reference =over 4 =item DESCRIPTION =over 4 =item OPERATORS =item SYNTAX =item ESCAPE SEQUENCES =item CHARACTER CLASSES =item ANCHORS =item QUANTIFIERS =item EXTENDED CONSTRUCTS =item VARIABLES =item FUNCTIONS =item TERMINOLOGY =back =item AUTHOR =item SEE ALSO =item THANKS =back =head2 perlref - Perl references and nested data structures =over 4 =item NOTE =item DESCRIPTION =over 4 =item Making References X<reference, creation> X<referencing> 1. X<\> X<backslash>, 2. X<array, anonymous> X<[> X<[]> X<square bracket> X<bracket, square> X<arrayref> X<array reference> X<reference, array>, 3. X<hash, anonymous> X<{> X<{}> X<curly bracket> X<bracket, curly> X<brace> X<hashref> X<hash reference> X<reference, hash>, 4. X<subroutine, anonymous> X<subroutine, reference> X<reference, subroutine> X<scope, lexical> X<closure> X<lexical> X<lexical scope>, 5. X<constructor> X<new>, 6. X<autovivification>, 7. X<*foo{THING}> X<*> =item Using References X<reference, use> X<dereferencing> X<dereference> =item Circular References X<circular reference> X<reference, circular> =item Symbolic references X<reference, symbolic> X<reference, soft> X<symbolic reference> X<soft reference> =item Not-so-symbolic references =item Pseudo-hashes: Using an array as a hash X<pseudo-hash> X<pseudo hash> X<pseudohash> =item Function Templates X<scope, lexical> X<closure> X<lexical> X<lexical scope> X<subroutine, nested> X<sub, nested> X<subroutine, local> X<sub, local> =back =item WARNING X<reference, string context> X<reference, use as hash key> =item SEE ALSO =back =head2 perlform - Perl formats =over 4 =item DESCRIPTION =over 4 =item Text Fields X<format, text field> =item Numeric Fields X<#> X<format, numeric field> =item The Field @* for Variable-Width Multi-Line Text X<@*> =item The Field ^* for Variable-Width One-line-at-a-time Text X<^*> =item Specifying Values X<format, specifying values> =item Using Fill Mode X<format, fill mode> =item Suppressing Lines Where All Fields Are Void X<format, suppressing lines> =item Repeating Format Lines X<format, repeating lines> =item Top of Form Processing X<format, top of form> X<top> X<header> =item Format Variables X<format variables> X<format, variables> =back =item NOTES =over 4 =item Footers X<format, footer> X<footer> =item Accessing Formatting Internals X<format, internals> =back =item WARNINGS =back =head2 perlobj - Perl object reference =over 4 =item DESCRIPTION =over 4 =item An Object is Simply a Data Structure X<object> X<bless> X<constructor> X<new> =item A Class is Simply a Package X<class> X<package> X<@ISA> X<inheritance> =item A Method is Simply a Subroutine X<method> =item Method Invocation X<invocation> X<method> X<arrow> X<< -> >> =item Inheritance X<inheritance> =item Writing Constructors X<constructor> =item Attributes X<attribute> =item An Aside About Smarter and Safer Code =item Method Call Variations X<method> =item Invoking Class Methods X<invocation> =item C<bless>, C<blessed>, and C<ref> =item The UNIVERSAL Class X<UNIVERSAL> isa($class) X<isa>, DOES($role) X<DOES>, can($method) X<can>, VERSION($need) X<VERSION> =item AUTOLOAD X<AUTOLOAD> =item Destructors X<destructor> X<DESTROY> =item Non-Hash Objects =item Inside-Out objects =item Pseudo-hashes =back =item SEE ALSO =back =head2 perltie - how to hide an object class in a simple variable =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Tying Scalars X<scalar, tying> TIESCALAR classname, LIST X<TIESCALAR>, FETCH this X<FETCH>, STORE this, value X<STORE>, UNTIE this X<UNTIE>, DESTROY this X<DESTROY> =item Tying Arrays X<array, tying> TIEARRAY classname, LIST X<TIEARRAY>, FETCH this, index X<FETCH>, STORE this, index, value X<STORE>, FETCHSIZE this X<FETCHSIZE>, STORESIZE this, count X<STORESIZE>, EXTEND this, count X<EXTEND>, EXISTS this, key X<EXISTS>, DELETE this, key X<DELETE>, CLEAR this X<CLEAR>, PUSH this, LIST X<PUSH>, POP this X<POP>, SHIFT this X<SHIFT>, UNSHIFT this, LIST X<UNSHIFT>, SPLICE this, offset, length, LIST X<SPLICE>, UNTIE this X<UNTIE>, DESTROY this X<DESTROY> =item Tying Hashes X<hash, tying> USER, HOME, CLOBBER, LIST, TIEHASH classname, LIST X<TIEHASH>, FETCH this, key X<FETCH>, STORE this, key, value X<STORE>, DELETE this, key X<DELETE>, CLEAR this X<CLEAR>, EXISTS this, key X<EXISTS>, FIRSTKEY this X<FIRSTKEY>, NEXTKEY this, lastkey X<NEXTKEY>, SCALAR this X<SCALAR>, UNTIE this X<UNTIE>, DESTROY this X<DESTROY> =item Tying FileHandles X<filehandle, tying> TIEHANDLE classname, LIST X<TIEHANDLE>, WRITE this, LIST X<WRITE>, PRINT this, LIST X<PRINT>, PRINTF this, LIST X<PRINTF>, READ this, LIST X<READ>, READLINE this X<READLINE>, GETC this X<GETC>, EOF this X<EOF>, CLOSE this X<CLOSE>, UNTIE this X<UNTIE>, DESTROY this X<DESTROY> =item UNTIE this X<UNTIE> =item The C<untie> Gotcha X<untie> =back =item SEE ALSO =item BUGS =item AUTHOR =back =head2 perldbmfilter - Perl DBM Filters =over 4 =item SYNOPSIS =item DESCRIPTION B<filter_store_key>, B<filter_store_value>, B<filter_fetch_key>, B<filter_fetch_value> =over 4 =item The Filter =item An Example: the NULL termination problem. =item Another Example: Key is a C int. =back =item SEE ALSO =item AUTHOR =back =head2 perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores) =over 4 =item DESCRIPTION =item Signals =over 4 =item Handling the SIGHUP Signal in Daemons =item Deferred Signals (Safe Signals) Long-running opcodes, Interrupting IO, Restartable system calls, Signals as "faults", Signals triggered by operating system state =back =item Named Pipes =item Using open() for IPC =over 4 =item Filehandles =item Background Processes =item Complete Dissociation of Child from Parent =item Safe Pipe Opens =item Avoiding Pipe Deadlocks =item Bidirectional Communication with Another Process =item Bidirectional Communication with Yourself =back =item Sockets: Client/Server Communication =over 4 =item Internet Line Terminators =item Internet TCP Clients and Servers =item Unix-Domain TCP Clients and Servers =back =item TCP Clients with IO::Socket =over 4 =item A Simple Client C<Proto>, C<PeerAddr>, C<PeerPort> =item A Webget Client =item Interactive Client with IO::Socket =back =item TCP Servers with IO::Socket Proto, LocalPort, Listen, Reuse =item UDP: Message Passing =item SysV IPC =item NOTES =item BUGS =item AUTHOR =item SEE ALSO =back =head2 perlfork - Perl's fork() emulation =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Behavior of other Perl features in forked pseudo-processes $$ or $PROCESS_ID, %ENV, chdir() and all other builtins that accept filenames, wait() and waitpid(), kill(), exec(), exit(), Open handles to files, directories and network sockets =item Resource limits =item Killing the parent process =item Lifetime of the parent process and pseudo-processes =back =item CAVEATS AND LIMITATIONS BEGIN blocks, Open filehandles, Open directory handles, Forking pipe open() not yet implemented, Global state maintained by XSUBs, Interpreter embedded in larger application, Thread-safety of extensions =item PORTABILITY CAVEATS =item BUGS =item AUTHOR =item SEE ALSO =back =head2 perlnumber - semantics of numbers and numeric operations in Perl =over 4 =item SYNOPSIS =item DESCRIPTION =item Storing numbers =item Numeric operators and numeric conversions =item Flavors of Perl numeric operations Arithmetic operators, ++, Arithmetic operators during C<use integer>, Other mathematical operators, Bitwise operators, Bitwise operators during C<use integer>, Operators which expect an integer, Operators which expect a string =item AUTHOR =item SEE ALSO =back =head2 perlthrtut - Tutorial on threads in Perl =over 4 =item DESCRIPTION =item What Is A Thread Anyway? =item Threaded Program Models =over 4 =item Boss/Worker =item Work Crew =item Pipeline =back =item What kind of threads are Perl threads? =item Thread-Safe Modules =item Thread Basics =over 4 =item Basic Thread Support =item A Note about the Examples =item Creating Threads =item Waiting For A Thread To Exit =item Ignoring A Thread =item Process and Thread Termination =back =item Threads And Data =over 4 =item Shared And Unshared Data =item Thread Pitfalls: Races =back =item Synchronization and control =over 4 =item Controlling access: lock() =item A Thread Pitfall: Deadlocks =item Queues: Passing Data Around =item Semaphores: Synchronizing Data Access =item Basic semaphores =item Advanced Semaphores =item Waiting for a Condition =item Giving up control =back =item General Thread Utility Routines =over 4 =item What Thread Am I In? =item Thread IDs =item Are These Threads The Same? =item What Threads Are Running? =back =item A Complete Example =item Different implementations of threads =item Performance considerations =item Process-scope Changes =item Thread-Safety of System Libraries =item Conclusion =item SEE ALSO =item Bibliography =over 4 =item Introductory Texts =item OS-Related References =item Other References =back =item Acknowledgements =item AUTHOR =item Copyrights =back =head2 perlport - Writing portable Perl =over 4 =item DESCRIPTION Not all Perl programs have to be portable, Nearly all of Perl already I<is> portable =item ISSUES =over 4 =item Newlines =item Numbers endianness and Width =item Files and Filesystems =item System Interaction =item Command names versus file pathnames =item Networking =item Interprocess Communication (IPC) =item External Subroutines (XS) =item Standard Modules =item Time and Date =item Character sets and character encoding =item Internationalisation =item System Resources =item Security =item Style =back =item CPAN Testers =item PLATFORMS =over 4 =item Unix =item DOS and Derivatives =item VMS =item VOS =item EBCDIC Platforms =item Acorn RISC OS =item Other perls =back =item FUNCTION IMPLEMENTATIONS =over 4 =item Alphabetical Listing of Perl Functions -I<X>, alarm, atan2, binmode, chmod, chown, chroot, crypt, dbmclose, dbmopen, dump, exec, exit, fcntl, flock, fork, getlogin, getpgrp, getppid, getpriority, getpwnam, getgrnam, getnetbyname, getpwuid, getgrgid, getnetbyaddr, getprotobynumber, getservbyport, getpwent, getgrent, gethostbyname, gethostent, getnetent, getprotoent, getservent, sethostent, setnetent, setprotoent, setservent, endpwent, endgrent, endhostent, endnetent, endprotoent, endservent, getsockopt SOCKET,LEVEL,OPTNAME, glob, gmtime, ioctl FILEHANDLE,FUNCTION,SCALAR, kill, link, localtime, lstat, msgctl, msgget, msgsnd, msgrcv, open, readlink, rename, rewinddir, select, semctl, semget, semop, setgrent, setpgrp, setpriority, setpwent, setsockopt, shmctl, shmget, shmread, shmwrite, sockatmark, socketpair, stat, symlink, syscall, sysopen, system, times, truncate, umask, utime, wait, waitpid =back =item Supported Platforms Linux (x86, ARM, IA64), HP-UX, AIX, Win32, Windows 2000, Windows XP, Windows Server 2003, Windows Vista, Windows Server 2008, Windows 7, Cygwin, Solaris (x86, SPARC), OpenVMS, Alpha (7.2 and later), I64 (8.2 and later), Symbian, NetBSD, FreeBSD, Debian GNU/kFreeBSD, Haiku, Irix (6.5. What else?), OpenBSD, Dragonfly BSD, QNX Neutrino RTOS (6.5.0), MirOS BSD, time_t issues that may or may not be fixed, Symbian (Series 60 v3, 3.2 and 5 - what else?), Stratus VOS / OpenVOS, AIX =item EOL Platforms (Perl 5.14) Atari MiNT, Apollo Domain/OS, Apple Mac OS 8/9, Tenon Machten, Windows 95, Windows 98, Windows ME, Windows NT4 =item Supported Platforms (Perl 5.8) =item SEE ALSO =item AUTHORS / CONTRIBUTORS =back =head2 perllocale - Perl locale handling (internationalization and localization) =over 4 =item DESCRIPTION =item WHAT IS A LOCALE Category LC_NUMERIC: Numeric formatting, Category LC_MONETARY: Formatting of monetary amounts, Category LC_TIME: Date/Time formatting, Category LC_MESSAGES: Error and other messages, Category LC_COLLATE: Collation, Category LC_CTYPE: Character Types =item PREPARING TO USE LOCALES =item USING LOCALES =over 4 =item The use locale pragma B<Under C<use locale ':not_characters';>>, B<Under just plain C<use locale;>> =item The setlocale function =item Finding locales =item LOCALE PROBLEMS =item Temporarily fixing locale problems =item Permanently fixing locale problems =item Permanently fixing your system's locale configuration =item Fixing system locale configuration =item The localeconv function =item I18N::Langinfo =back =item LOCALE CATEGORIES =over 4 =item Category LC_COLLATE: Collation =item Category LC_CTYPE: Character Types =item Category LC_NUMERIC: Numeric Formatting =item Category LC_MONETARY: Formatting of monetary amounts =item LC_TIME =item Other categories =back =item SECURITY =item ENVIRONMENT PERL_BADLANG, LC_ALL, LANGUAGE, LC_CTYPE, LC_COLLATE, LC_MONETARY, LC_NUMERIC, LC_TIME, LANG =over 4 =item Examples =back =item NOTES =over 4 =item Backward compatibility =item I18N:Collate obsolete =item Sort speed and memory use impacts =item write() and LC_NUMERIC =item Freely available locale definitions =item I18n and l10n =item An imperfect standard =back =item Unicode and UTF-8 =item BUGS =over 4 =item Broken systems =back =item SEE ALSO =item HISTORY =back =head2 perluniintro - Perl Unicode introduction =over 4 =item DESCRIPTION =over 4 =item Unicode =item Perl's Unicode Support =item Perl's Unicode Model =item Unicode and EBCDIC =item Creating Unicode =item Handling Unicode =item Legacy Encodings =item Unicode I/O =item Displaying Unicode As Text =item Special Cases =item Advanced Topics =item Miscellaneous =item Questions With Answers =item Hexadecimal Notation =item Further Resources =back =item UNICODE IN OLDER PERLS =item SEE ALSO =item ACKNOWLEDGMENTS =item AUTHOR, COPYRIGHT, AND LICENSE =back =head2 perlunicode - Unicode support in Perl =over 4 =item DESCRIPTION =over 4 =item Important Caveats Safest if you "use feature 'unicode_strings'", Input and Output Layers, C<use utf8> still needed to enable UTF-8/UTF-EBCDIC in scripts, BOM-marked scripts and UTF-16 scripts autodetected, C<use encoding> needed to upgrade non-Latin-1 byte strings =item Byte and Character Semantics =item Effects of Character Semantics =item Unicode Character Properties B<C<\p{All}>>, B<C<\p{Alnum}>>, B<C<\p{Any}>>, B<C<\p{ASCII}>>, B<C<\p{Assigned}>>, B<C<\p{Blank}>>, B<C<\p{Decomposition_Type: Non_Canonical}>> (Short: C<\p{Dt=NonCanon}>), B<C<\p{Graph}>>, B<C<\p{HorizSpace}>>, B<C<\p{In=*}>>, B<C<\p{PerlSpace}>>, B<C<\p{PerlWord}>>, B<C<\p{Posix...}>>, B<C<\p{Present_In: *}>> (Short: C<\p{In=*}>), B<C<\p{Print}>>, B<C<\p{SpacePerl}>>, B<C<\p{Title}>> and B<C<\p{Titlecase}>>, B<C<\p{VertSpace}>>, B<C<\p{Word}>>, B<C<\p{XPosix...}>> =item User-Defined Character Properties =item User-Defined Case Mappings (for serious hackers only) =item Character Encodings for Input and Output =item Unicode Regular Expression Support Level =item Unicode Encodings =item Non-character code points =item Beyond Unicode code points =item Security Implications of Unicode =item Unicode in Perl on EBCDIC =item Locales =item When Unicode Does Not Happen =item The "Unicode Bug" =item Forcing Unicode in Perl (Or Unforcing Unicode in Perl) =item Using Unicode in XS =item Hacking Perl to work on earlier Unicode versions (for very serious hackers only) =back =item BUGS =over 4 =item Interaction with Locales =item Problems with characters in the Latin-1 Supplement range =item Interaction with Extensions =item Speed =item Problems on EBCDIC platforms =item Porting code from perl-5.6.X =back =item SEE ALSO =back =head2 perlunifaq - Perl Unicode FAQ =over 4 =item Q and A =over 4 =item perlunitut isn't really a Unicode tutorial, is it? =item What character encodings does Perl support? =item Which version of perl should I use? =item What about binary data, like images? =item When should I decode or encode? =item What if I don't decode? =item What if I don't encode? =item Is there a way to automatically decode or encode? =item What if I don't know which encoding was used? =item Can I use Unicode in my Perl sources? =item Data::Dumper doesn't restore the UTF8 flag; is it broken? =item Why do regex character classes sometimes match only in the ASCII range? =item Why do some characters not uppercase or lowercase correctly? =item How can I determine if a string is a text string or a binary string? =item How do I convert from encoding FOO to encoding BAR? =item What are C<decode_utf8> and C<encode_utf8>? =item What is a "wide character"? =back =item INTERNALS =over 4 =item What is "the UTF8 flag"? =item What about the C<use bytes> pragma? =item What about the C<use encoding> pragma? =item What is the difference between C<:encoding> and C<:utf8>? =item What's the difference between C<UTF-8> and C<utf8>? =item I lost track; what encoding is the internal format really? =back =item AUTHOR =item SEE ALSO =back =head2 perluniprops - Index of Unicode Version 6.1.0 character properties in Perl =over 4 =item DESCRIPTION =item Properties accessible through C<\p{}> and C<\P{}> Single form (C<\p{name}>) tighter rules:, white space adjacent to a non-word character, underscores separating digits in numbers, Compound form (C<\p{name=value}> or C<\p{name:value}>) tighter rules:, Stabilized, Deprecated, Obsolete, Z<>B<*> is a wild-card, B<(\d+)> in the info column gives the number of code points matched by this property, B<D> means this is deprecated, B<O> means this is obsolete, B<S> means this is stabilized, B<T> means tighter (stricter) name matching applies, B<X> means use of this form is discouraged, and may not be stable =over 4 =item Legal C<\p{}> and C<\P{}> constructs that match no characters \p{Canonical_Combining_Class=Attached_Below_Left}, \p{Grapheme_Cluster_Break=Prepend}, \p{Joining_Type=Left_Joining} =back =item Properties accessible through Unicode::UCD =item Properties accessible through other means =item Unicode character properties that are NOT accepted by Perl I<Expands_On_NFC> (XO_NFC), I<Expands_On_NFD> (XO_NFD), I<Expands_On_NFKC> (XO_NFKC), I<Expands_On_NFKD> (XO_NFKD), I<Grapheme_Link> (Gr_Link), I<Indic_Matra_Category> (InMC), I<Indic_Syllabic_Category> (InSC), I<Jamo_Short_Name> (JSN), I<Other_Alphabetic> (OAlpha), I<Other_Default_Ignorable_Code_Point> (ODI), I<Other_Grapheme_Extend> (OGr_Ext), I<Other_ID_Continue> (OIDC), I<Other_ID_Start> (OIDS), I<Other_Lowercase> (OLower), I<Other_Math> (OMath), I<Other_Uppercase> (OUpper), I<Script=Katakana_Or_Hiragana> (sc=Hrkt), I<Script_Extensions=Katakana_Or_Hiragana> (scx=Hrkt) =item Other information in the Unicode data base F<auxiliary/GraphemeBreakTest.html>, F<auxiliary/LineBreakTest.html>, F<auxiliary/SentenceBreakTest.html>, F<auxiliary/WordBreakTest.html>, F<auxiliary/LBTest.txt>, F<auxiliary/SBTest.txt>, F<auxiliary/WBTest.txt>, F<BidiTest.txt>, F<NormalizationTest.txt>, F<CJKRadicals.txt>, F<EmojiSources.txt>, F<Index.txt>, F<IndicMatraCategory.txt>, F<IndicSyllabicCategory.txt>, F<NamedSqProv.txt>, F<NamesList.txt>, F<NormalizationCorrections.txt>, F<Props.txt>, F<ReadMe.txt>, F<StandardizedVariants.txt> =item SEE ALSO =back =head2 perlunitut - Perl Unicode Tutorial =over 4 =item DESCRIPTION =over 4 =item Definitions =item Your new toolkit =item I/O flow (the actual 5 minute tutorial) =back =item SUMMARY =item Q and A (or FAQ) =item ACKNOWLEDGEMENTS =item AUTHOR =item SEE ALSO =back =head2 perlebcdic - Considerations for running Perl on EBCDIC platforms =over 4 =item DESCRIPTION =item COMMON CHARACTER CODE SETS =over 4 =item ASCII =item ISO 8859 =item Latin 1 (ISO 8859-1) =item EBCDIC =item The 13 variant characters =item 0037 =item 1047 =item POSIX-BC =item Unicode code points versus EBCDIC code points =item Remaining Perl Unicode problems in EBCDIC =item Unicode and UTF =item Using Encode =back =item SINGLE OCTET TABLES recipe 0, recipe 1, recipe 2, recipe 3, recipe 4, recipe 5, recipe 6 =item IDENTIFYING CHARACTER CODE SETS =item CONVERSIONS =over 4 =item tr/// =item iconv =item C RTL =back =item OPERATOR DIFFERENCES =item FUNCTION DIFFERENCES chr(), ord(), pack(), print(), printf(), sort(), sprintf(), unpack() =item REGULAR EXPRESSION DIFFERENCES =item SOCKETS =item SORTING =over 4 =item Ignore ASCII vs. EBCDIC sort differences. =item MONO CASE then sort data. =item Convert, sort data, then re convert. =item Perform sorting on one type of platform only. =back =item TRANSFORMATION FORMATS =over 4 =item URL decoding and encoding =item uu encoding and decoding =item Quoted-Printable encoding and decoding =item Caesarean ciphers =back =item Hashing order and checksums =item I18N AND L10N =item MULTI-OCTET CHARACTER SETS =item OS ISSUES =over 4 =item OS/400 PASE, IFS access =item OS/390, z/OS chcp, dataset access, OS/390, z/OS iconv, locales =item VM/ESA? =item POSIX-BC? =back =item BUGS =item SEE ALSO =item REFERENCES =item HISTORY =item AUTHOR =back =head2 perlsec - Perl security =over 4 =item DESCRIPTION =item SECURITY VULNERABILITY CONTACT INFORMATION =item SECURITY MECHANISMS AND CONCERNS =over 4 =item Taint mode =item Laundering and Detecting Tainted Data =item Switches On the "#!" Line =item Taint mode and @INC =item Cleaning Up Your Path =item Security Bugs =item Protecting Your Programs =item Unicode =item Algorithmic Complexity Attacks =back =item SEE ALSO =back =head2 perlmod - Perl modules (packages and symbol tables) =over 4 =item DESCRIPTION =over 4 =item Packages X<package> X<namespace> X<variable, global> X<global variable> X<global> =item Symbol Tables X<symbol table> X<stash> X<%::> X<%main::> X<typeglob> X<glob> X<alias> =item BEGIN, UNITCHECK, CHECK, INIT and END X<BEGIN> X<UNITCHECK> X<CHECK> X<INIT> X<END> =item Perl Classes X<class> X<@ISA> =item Perl Modules X<module> =item Making your module threadsafe X<threadsafe> X<thread safe> X<module, threadsafe> X<module, thread safe> X<CLONE> X<CLONE_SKIP> X<thread> X<threads> X<ithread> =back =item SEE ALSO =back =head2 perlmodlib - constructing new Perl modules and finding existing ones =over 4 =item THE PERL MODULE LIBRARY =over 4 =item Pragmatic Modules arybase, attributes, autodie, autodie::exception, autodie::exception::system, autodie::hints, autouse, base, bigint, bignum, bigrat, blib, bytes, charnames, constant, deprecate, diagnostics, encoding, encoding::warnings, feature, fields, filetest, if, inc::latest, integer, less, lib, locale, mro, open, ops, overload, overloading, parent, perldoc, perlfaq, perlfaq1, perlfaq2, perlfaq3, perlfaq4, perlfaq5, perlfaq6, perlfaq7, perlfaq8, perlfaq9, perlfunc, perlglossary, perlpodspeccopy, perlvarcopy, perlxs, perlxstut, perlxstypemap, re, sigtrap, sort, strict, subs, threads, threads::shared, utf8, vars, version, vmsish, warnings, warnings::register =item Standard Modules AnyDBM_File, App::Cpan, App::Prove, App::Prove::State, App::Prove::State::Result, App::Prove::State::Result::Test, Archive::Extract, Archive::Tar, Archive::Tar::File, Attribute::Handlers, AutoLoader, AutoSplit, B, B::Concise, B::Debug, B::Deparse, B::Lint, B::Lint::Debug, B::Showlex, B::Terse, B::Xref, Benchmark, C<Socket>, CGI, CGI::Apache, CGI::Carp, CGI::Cookie, CGI::Fast, CGI::Pretty, CGI::Push, CGI::Switch, CGI::Util, CORE, CPAN, CPAN::API::HOWTO, CPAN::Debug, CPAN::Distroprefs, CPAN::FirstTime, CPAN::HandleConfig, CPAN::Kwalify, CPAN::Meta, CPAN::Meta::Converter, CPAN::Meta::Feature, CPAN::Meta::History, CPAN::Meta::Prereqs, CPAN::Meta::Requirements, CPAN::Meta::Spec, CPAN::Meta::Validator, CPAN::Meta::YAML, CPAN::Nox, CPAN::Queue, CPAN::Tarzip, CPAN::Version, CPANPLUS, CPANPLUS::Backend, CPANPLUS::Backend::RV, CPANPLUS::Config, CPANPLUS::Configure, CPANPLUS::Dist, CPANPLUS::Dist::Autobundle, CPANPLUS::Dist::Base, CPANPLUS::Dist::Build, CPANPLUS::Dist::Build::Constants, CPANPLUS::Dist::MM, CPANPLUS::Dist::Sample, CPANPLUS::Error, CPANPLUS::FAQ, CPANPLUS::Hacking, CPANPLUS::Internals, CPANPLUS::Internals::Extract, CPANPLUS::Internals::Fetch, CPANPLUS::Internals::Report, CPANPLUS::Internals::Search, CPANPLUS::Internals::Source, CPANPLUS::Internals::Source::Memory, CPANPLUS::Internals::Source::SQLite, CPANPLUS::Internals::Utils, CPANPLUS::Module, CPANPLUS::Module::Author, CPANPLUS::Module::Author::Fake, CPANPLUS::Module::Checksums, CPANPLUS::Module::Fake, CPANPLUS::Selfupdate, CPANPLUS::Shell, CPANPLUS::Shell::Classic, CPANPLUS::Shell::Default, CPANPLUS::Shell::Default::Plugins::CustomSource, CPANPLUS::Shell::Default::Plugins::HOWTO, CPANPLUS::Shell::Default::Plugins::Remote, CPANPLUS::Shell::Default::Plugins::Source, Carp, Class::Struct, Compress::Raw::Bzip2, Compress::Raw::Zlib, Compress::Zlib, Config, Cwd, DB, DBM_Filter, DBM_Filter::compress, DBM_Filter::encode, DBM_Filter::int32, DBM_Filter::null, DBM_Filter::utf8, DB_File, Data::Dumper, Devel::InnerPackage, Devel::PPPort, Devel::Peek, Devel::SelfStubber, Digest, Digest::MD5, Digest::SHA, Digest::base, Digest::file, DirHandle, Dumpvalue, DynaLoader, Encode, Encode::Alias, Encode::Byte, Encode::CJKConstants, Encode::CN, Encode::CN::HZ, Encode::Config, Encode::EBCDIC, Encode::Encoder, Encode::Encoding, Encode::GSM0338, Encode::Guess, Encode::JP, Encode::JP::H2Z, Encode::JP::JIS7, Encode::KR, Encode::KR::2022_KR, Encode::MIME::Header, Encode::MIME::Name, Encode::PerlIO, Encode::Supported, Encode::Symbol, Encode::TW, Encode::Unicode, Encode::Unicode::UTF7, English, Env, Errno, Exporter, Exporter::Heavy, ExtUtils::CBuilder, ExtUtils::CBuilder::Platform::Windows, ExtUtils::Command, ExtUtils::Command::MM, ExtUtils::Constant, ExtUtils::Constant::Base, ExtUtils::Constant::Utils, ExtUtils::Constant::XS, ExtUtils::Embed, ExtUtils::Install, ExtUtils::Installed, ExtUtils::Liblist, ExtUtils::MM, ExtUtils::MM_AIX, ExtUtils::MM_Any, ExtUtils::MM_BeOS, ExtUtils::MM_Cygwin, ExtUtils::MM_DOS, ExtUtils::MM_Darwin, ExtUtils::MM_MacOS, ExtUtils::MM_NW5, ExtUtils::MM_OS2, ExtUtils::MM_QNX, ExtUtils::MM_UWIN, ExtUtils::MM_Unix, ExtUtils::MM_VMS, ExtUtils::MM_VOS, ExtUtils::MM_Win32, ExtUtils::MM_Win95, ExtUtils::MY, ExtUtils::MakeMaker, ExtUtils::MakeMaker::Config, ExtUtils::MakeMaker::FAQ, ExtUtils::MakeMaker::Tutorial, ExtUtils::Manifest, ExtUtils::Mkbootstrap, ExtUtils::Mksymlists, ExtUtils::Packlist, ExtUtils::ParseXS, ExtUtils::ParseXS::Constants, ExtUtils::ParseXS::Utilities, ExtUtils::Typemaps, ExtUtils::Typemaps::Cmd, ExtUtils::Typemaps::InputMap, ExtUtils::Typemaps::OutputMap, ExtUtils::Typemaps::Type, ExtUtils::XSSymSet, ExtUtils::testlib, Fatal, Fcntl, File::Basename, File::CheckTree, File::Compare, File::Copy, File::DosGlob, File::Fetch, File::Find, File::Glob, File::GlobMapper, File::Path, File::Spec, File::Spec::Cygwin, File::Spec::Epoc, File::Spec::Functions, File::Spec::Mac, File::Spec::OS2, File::Spec::Unix, File::Spec::VMS, File::Spec::Win32, File::Temp, File::stat, FileCache, FileHandle, Filter::Simple, Filter::Util::Call, FindBin, GDBM_File, Getopt::Long, Getopt::Std, HTTP::Tiny, Hash::Util, Hash::Util::FieldHash, I18N::Collate, I18N::LangTags, I18N::LangTags::Detect, I18N::LangTags::List, I18N::Langinfo, IO, IO::Compress::Base, IO::Compress::Bzip2, IO::Compress::Deflate, IO::Compress::FAQ, IO::Compress::Gzip, IO::Compress::RawDeflate, IO::Compress::Zip, IO::Dir, IO::File, IO::Handle, IO::Pipe, IO::Poll, IO::Seekable, IO::Select, IO::Socket, IO::Socket::INET, IO::Socket::UNIX, IO::Uncompress::AnyInflate, IO::Uncompress::AnyUncompress, IO::Uncompress::Base, IO::Uncompress::Bunzip2, IO::Uncompress::Gunzip, IO::Uncompress::Inflate, IO::Uncompress::RawInflate, IO::Uncompress::Unzip, IO::Zlib, IPC::Cmd, IPC::Msg, IPC::Open2, IPC::Open3, IPC::Semaphore, IPC::SharedMem, IPC::SysV, JSON::PP, JSON::PP::Boolean, List::Util, List::Util::XS, Locale::Codes, Locale::Codes::API, Locale::Codes::Changes, Locale::Codes::Constants, Locale::Codes::Country, Locale::Codes::Country_Codes, Locale::Codes::Country_Retired, Locale::Codes::Currency, Locale::Codes::Currency_Codes, Locale::Codes::Currency_Retired, Locale::Codes::LangExt, Locale::Codes::LangExt_Codes, Locale::Codes::LangExt_Retired, Locale::Codes::LangFam, Locale::Codes::LangFam_Codes, Locale::Codes::LangFam_Retired, Locale::Codes::LangVar, Locale::Codes::LangVar_Codes, Locale::Codes::LangVar_Retired, Locale::Codes::Language, Locale::Codes::Language_Codes, Locale::Codes::Language_Retired, Locale::Codes::Script, Locale::Codes::Script_Codes, Locale::Codes::Script_Retired, Locale::Country, Locale::Currency, Locale::Language, Locale::Maketext, Locale::Maketext::Cookbook, Locale::Maketext::Guts, Locale::Maketext::GutsLoader, Locale::Maketext::Simple, Locale::Maketext::TPJ13, Locale::Script, Log::Message, Log::Message::Config, Log::Message::Handlers, Log::Message::Item, Log::Message::Simple, MIME::Base64, MIME::QuotedPrint, Math::BigFloat, Math::BigInt, Math::BigInt::Calc, Math::BigInt::CalcEmu, Math::BigInt::FastCalc, Math::BigRat, Math::Complex, Math::Trig, Memoize, Memoize::AnyDBM_File, Memoize::Expire, Memoize::ExpireFile, Memoize::ExpireTest, Memoize::NDBM_File, Memoize::SDBM_File, Memoize::Storable, Module::Build, Module::Build::API, Module::Build::Authoring, Module::Build::Base, Module::Build::Bundling, Module::Build::Compat, Module::Build::ConfigData, Module::Build::Cookbook, Module::Build::ModuleInfo, Module::Build::Notes, Module::Build::PPMMaker, Module::Build::Platform::Amiga, Module::Build::Platform::Default, Module::Build::Platform::EBCDIC, Module::Build::Platform::MPEiX, Module::Build::Platform::MacOS, Module::Build::Platform::RiscOS, Module::Build::Platform::Unix, Module::Build::Platform::VMS, Module::Build::Platform::VOS, Module::Build::Platform::Windows, Module::Build::Platform::aix, Module::Build::Platform::cygwin, Module::Build::Platform::darwin, Module::Build::Platform::os2, Module::Build::Version, Module::Build::YAML, Module::CoreList, Module::Load, Module::Load::Conditional, Module::Loaded, Module::Metadata, Module::Pluggable, Module::Pluggable::Object, NDBM_File, NEXT, Net::Cmd, Net::Config, Net::Domain, Net::FTP, Net::NNTP, Net::Netrc, Net::POP3, Net::Ping, Net::SMTP, Net::Time, Net::hostent, Net::libnetFAQ, Net::netent, Net::protoent, Net::servent, O, ODBM_File, Object::Accessor, Opcode, POSIX, Package::Constants, Params::Check, Parse::CPAN::Meta, Perl::OSType, PerlIO, PerlIO::encoding, PerlIO::mmap, PerlIO::scalar, PerlIO::via, PerlIO::via::QuotedPrint, Pod::Checker, Pod::Escapes, Pod::Find, Pod::Functions, Pod::Html, Pod::InputObjects, Pod::LaTeX, Pod::Man, Pod::ParseLink, Pod::ParseUtils, Pod::Parser, Pod::Perldoc, Pod::Perldoc::BaseTo, Pod::Perldoc::GetOptsOO, Pod::Perldoc::ToANSI, Pod::Perldoc::ToChecker, Pod::Perldoc::ToMan, Pod::Perldoc::ToNroff, Pod::Perldoc::ToPod, Pod::Perldoc::ToRtf, Pod::Perldoc::ToTerm, Pod::Perldoc::ToText, Pod::Perldoc::ToTk, Pod::Perldoc::ToXml, Pod::PlainText, Pod::Select, Pod::Simple, Pod::Simple::Checker, Pod::Simple::Debug, Pod::Simple::DumpAsText, Pod::Simple::DumpAsXML, Pod::Simple::HTML, Pod::Simple::HTMLBatch, Pod::Simple::LinkSection, Pod::Simple::Methody, Pod::Simple::PullParser, Pod::Simple::PullParserEndToken, Pod::Simple::PullParserStartToken, Pod::Simple::PullParserTextToken, Pod::Simple::PullParserToken, Pod::Simple::RTF, Pod::Simple::Search, Pod::Simple::SimpleTree, Pod::Simple::Subclassing, Pod::Simple::Text, Pod::Simple::TextContent, Pod::Simple::XHTML, Pod::Simple::XMLOutStream, Pod::Text, Pod::Text::Color, Pod::Text::Termcap, Pod::Usage, SDBM_File, Safe, Scalar::Util, Search::Dict, SelectSaver, SelfLoader, Storable, Symbol, Sys::Hostname, Sys::Syslog, Sys::Syslog::Win32, TAP::Base, TAP::Formatter::Base, TAP::Formatter::Color, TAP::Formatter::Console, TAP::Formatter::Console::ParallelSession, TAP::Formatter::Console::Session, TAP::Formatter::File, TAP::Formatter::File::Session, TAP::Formatter::Session, TAP::Harness, TAP::Object, TAP::Parser, TAP::Parser::Aggregator, TAP::Parser::Grammar, TAP::Parser::Iterator, TAP::Parser::Iterator::Array, TAP::Parser::Iterator::Process, TAP::Parser::Iterator::Stream, TAP::Parser::IteratorFactory, TAP::Parser::Multiplexer, TAP::Parser::Result, TAP::Parser::Result::Bailout, TAP::Parser::Result::Comment, TAP::Parser::Result::Plan, TAP::Parser::Result::Pragma, TAP::Parser::Result::Test, TAP::Parser::Result::Unknown, TAP::Parser::Result::Version, TAP::Parser::Result::YAML, TAP::Parser::ResultFactory, TAP::Parser::Scheduler, TAP::Parser::Scheduler::Job, TAP::Parser::Scheduler::Spinner, TAP::Parser::Source, TAP::Parser::SourceHandler, TAP::Parser::SourceHandler::Executable, TAP::Parser::SourceHandler::File, TAP::Parser::SourceHandler::Handle, TAP::Parser::SourceHandler::Perl, TAP::Parser::SourceHandler::RawTAP, TAP::Parser::Utils, TAP::Parser::YAMLish::Reader, TAP::Parser::YAMLish::Writer, Term::ANSIColor, Term::Cap, Term::Complete, Term::ReadLine, Term::UI, Term::UI::History, Test, Test::Builder, Test::Builder::Module, Test::Builder::Tester, Test::Builder::Tester::Color, Test::Harness, Test::More, Test::Simple, Test::Tutorial, Text::Abbrev, Text::Balanced, Text::ParseWords, Text::Soundex, Text::Tabs, Text::Wrap, Thread, Thread::Queue, Thread::Semaphore, Tie::Array, Tie::File, Tie::Handle, Tie::Hash, Tie::Hash::NamedCapture, Tie::Memoize, Tie::RefHash, Tie::Scalar, Tie::StdHandle, Tie::SubstrHash, Time::HiRes, Time::Local, Time::Piece, Time::Seconds, Time::gmtime, Time::localtime, Time::tm, UNIVERSAL, Unicode::Collate, Unicode::Collate::CJK::Big5, Unicode::Collate::CJK::GB2312, Unicode::Collate::CJK::JISX0208, Unicode::Collate::CJK::Korean, Unicode::Collate::CJK::Pinyin, Unicode::Collate::CJK::Stroke, Unicode::Collate::Locale, Unicode::Normalize, Unicode::UCD, User::grent, User::pwent, VMS::DCLsym, VMS::Stdio, Version::Requirements, Win32API::File, Win32CORE, XS::APItest, XS::Typemap, XSLoader, version::Internals =item Extension Modules =back =item CPAN =over 4 =item Africa South Africa =item Asia China, Hong Kong, India, Indonesia, Japan, Republic of Korea, Russia, Singapore, Taiwan, Thailand, Turkey =item Central America Costa Rica =item Europe Austria, Belgium, Bosnia and Herzegovina, Bulgaria, Croatia, Czech Republic, Denmark, Finland, France, Germany, Greece, Hungary, Iceland, Ireland, Italy, Latvia, Lithuania, Malta, Netherlands, Norway, Poland, Portugal, Romania, Russia, Slovakia, Slovenia, Spain, Sweden, Switzerland, Ukraine, United Kingdom =item North America Bahamas, Canada, Mexico, United States, Alabama, Arizona, California, Florida, Idaho, Illinois, Indiana, Massachusetts, Michigan, Minnesota, New Jersey, New York, North Carolina, Oregon, Pennsylvania, South Carolina, Tennessee, Texas, Utah, Virginia, Washington, Wisconsin =item Oceania Australia, New Zealand =item South America Argentina, Brazil, Chile, Colombia =item RSYNC Mirrors =back =item Modules: Creation, Use, and Abuse =over 4 =item Guidelines for Module Creation =item Guidelines for Converting Perl 4 Library Scripts into Modules =item Guidelines for Reusing Application Code =back =item NOTE =back =head2 perlmodstyle - Perl module style guide =over 4 =item INTRODUCTION =item QUICK CHECKLIST =over 4 =item Before you start =item The API =item Stability =item Documentation =item Release considerations =back =item BEFORE YOU START WRITING A MODULE =over 4 =item Has it been done before? =item Do one thing and do it well =item What's in a name? =back =item DESIGNING AND WRITING YOUR MODULE =over 4 =item To OO or not to OO? =item Designing your API Write simple routines to do simple things, Separate functionality from output, Provide sensible shortcuts and defaults, Naming conventions, Parameter passing =item Strictness and warnings =item Backwards compatibility =item Error handling and messages =back =item DOCUMENTING YOUR MODULE =over 4 =item POD =item README, INSTALL, release notes, changelogs perl Makefile.PL, make, make test, make install, perl Build.PL, perl Build, perl Build test, perl Build install =back =item RELEASE CONSIDERATIONS =over 4 =item Version numbering =item Pre-requisites =item Testing =item Packaging =item Licensing =back =item COMMON PITFALLS =over 4 =item Reinventing the wheel =item Trying to do too much =item Inappropriate documentation =back =item SEE ALSO L<perlstyle>, L<perlnewmod>, L<perlpod>, L<podchecker>, Packaging Tools, Testing tools, http://pause.perl.org/, Any good book on software engineering =item AUTHOR =back =head2 perlmodinstall - Installing CPAN Modules =over 4 =item DESCRIPTION =over 4 =item PREAMBLE B<DECOMPRESS> the file, B<UNPACK> the file into a directory, B<BUILD> the module (sometimes unnecessary), B<INSTALL> the module =back =item PORTABILITY =item HEY =item AUTHOR =item COPYRIGHT =back =head2 perlnewmod - preparing a new module for distribution =over 4 =item DESCRIPTION =over 4 =item Warning =item What should I make into a module? =item Step-by-step: Preparing the ground Look around, Check it's new, Discuss the need, Choose a name, Check again =item Step-by-step: Making the module Start with F<module-starter> or F<h2xs>, Use L<strict|strict> and L<warnings|warnings>, Use L<Carp|Carp>, Use L<Exporter|Exporter> - wisely!, Use L<plain old documentation|perlpod>, Write tests, Write the README =item Step-by-step: Distributing your module Get a CPAN user ID, C<perl Makefile.PL; make test; make dist>, Upload the tarball, Announce to the modules list, Announce to clpa, Fix bugs! =back =item AUTHOR =item SEE ALSO =back =head2 perlpragma - how to write a user pragma =over 4 =item DESCRIPTION =item A basic example =item Key naming =item Implementation details =back =head2 perlutil - utilities packaged with the Perl distribution =over 4 =item DESCRIPTION =item LIST OF UTILITIES =over 4 =item Documentation L<perldoc|perldoc>, L<pod2man|pod2man> and L<pod2text|pod2text>, L<pod2html|pod2html> and L<pod2latex|pod2latex>, L<pod2usage|pod2usage>, L<podselect|podselect>, L<podchecker|podchecker>, L<splain|splain>, C<roffitall> =item Converters L<a2p|a2p>, L<s2p|s2p> and L<psed>, L<find2perl|find2perl> =item Administration L<config_data|config_data>, L<libnetcfg|libnetcfg>, L<perlivp> =item Development L<perlbug|perlbug>, L<perlthanks|perlbug>, L<h2ph|h2ph>, L<c2ph|c2ph> and L<pstruct|pstruct>, L<h2xs|h2xs>, L<enc2xs>, L<xsubpp>, L<prove>, L<corelist> =item General tools L<piconv>, L<ptar>, L<ptardiff>, L<ptargrep>, L<shasum>, L<zipdetails> =item Installation L<cpan>, L<cpanp>, L<cpan2dist>, L<instmodsh> =back =item SEE ALSO =back =head2 perlfilter - Source Filters =over 4 =item DESCRIPTION =item CONCEPTS =item USING FILTERS =item WRITING A SOURCE FILTER =item WRITING A SOURCE FILTER IN C B<Decryption Filters> =item CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE =item WRITING A SOURCE FILTER IN PERL =item USING CONTEXT: THE DEBUG FILTER =item CONCLUSION =item THINGS TO LOOK OUT FOR Some Filters Clobber the C<DATA> Handle =item REQUIREMENTS =item AUTHOR =item Copyrights =back =head2 perldtrace - Perl's support for DTrace =over 4 =item SYNOPSIS =item DESCRIPTION =item HISTORY =item PROBES sub-entry(SUBNAME, FILE, LINE, PACKAGE), sub-return(SUBNAME, FILE, LINE, PACKAGE), phase-change(NEWPHASE, OLDPHASE) =item EXAMPLES Most frequently called functions, Trace function calls, Function calls during interpreter cleanup, System calls at compile time =item REFERENCES DTrace User Guide, DTrace: Dynamic Tracing in Oracle Solaris, Mac OS X and FreeBSD =item AUTHORS =back =head2 perlglossary - Perl Glossary =over 4 =item DESCRIPTION =over 4 =item A accessor methods, actual arguments, address operator, algorithm, alias, alternatives, anonymous, architecture, argument, ARGV, arithmetical operator, array, array context, ASCII, assertion, assignment, assignment operator, associative array, associativity, asynchronous, atom, atomic operation, attribute, autogeneration, autoincrement, autoload, autosplit, autovivification, AV, awk =item B backreference, backtracking, backward compatibility, bareword, base class, big-endian, binary, binary operator, bind, bit, bit shift, bit string, bless, block, BLOCK, block buffering, Boolean, Boolean context, breakpoint, broadcast, BSD, bucket, buffer, built-in, bundle, byte, bytecode =item C C, C preprocessor, call by reference, call by value, callback, canonical, capture buffer, capture group, capturing, character, character class, character property, circumfix operator, class, class method, client, cloister, closure, cluster, CODE, code generator, code point, code subpattern, collating sequence, command, command buffering, command name, command-line arguments, comment, compilation unit, compile phase, compile time, compiler, composer, concatenation, conditional, connection, construct, constructor, context, continuation, core dump, CPAN, cracker, current package, current working directory, currently selected output channel, CV =item D dangling statement, data structure, data type, datagram, DBM, declaration, decrement, default, defined, delimiter, deprecated modules and features, dereference, derived class, descriptor, destroy, destructor, device, directive, directory, directory handle, dispatch, distribution, (to be) dropped modules, dweomer, dwimmer, dynamic scoping =item E eclectic, element, embedding, empty list, empty subclass test, en passant, encapsulation, endian, environment, environment variable, EOF, errno, error, escape sequence, exception, exception handling, exec, executable file, execute, execute bit, exit status, export, expression, extension =item F false, FAQ, fatal error, field, FIFO, file, file descriptor, file test operator, fileglob, filehandle, filename, filesystem, filter, flag, floating point, flush, FMTEYEWTK, fork, formal arguments, format, freely available, freely redistributable, freeware, function, funny character =item G garbage collection, GID, glob, global, global destruction, glue language, granularity, greedy, grep, group, GV =item H hacker, handler, hard reference, hash, hash table, header file, here document, hexadecimal, home directory, host, hubris, HV =item I identifier, impatience, implementation, import, increment, indexing, indirect filehandle, indirect object, indirect object slot, indirection, infix, inheritance, instance, instance variable, integer, interface, interpolation, interpreter, invocant, invocation, I/O, IO, IP, IPC, is-a, iteration, iterator, IV =item J JAPH =item K key, keyword =item L label, laziness, left shift, leftmost longest, lexeme, lexer, lexical analysis, lexical scoping, lexical variable, library, LIFO, line, line buffering, line number, link, LIST, list, list context, list operator, list value, literal, little-endian, local, logical operator, lookahead, lookbehind, loop, loop control statement, loop label, lvaluable, lvalue, lvalue modifier =item M magic, magical increment, magical variables, Makefile, man, manpage, matching, member data, memory, metacharacter, metasymbol, method, minimalism, mode, modifier, module, modulus, monger, mortal, multidimensional array, multiple inheritance =item N named pipe, namespace, network address, newline, NFS, null character, null list, null string, numeric context, NV, nybble =item O object, octal, offset, one-liner, open source software, operand, operating system, operator, operator overloading, options, ordinal, overloading, overriding, owner =item P package, pad, parameter, parent class, parse tree, parsing, patch, PATH, pathname, pattern, pattern matching, permission bits, Pern, pipe, pipeline, platform, pod, pointer, polymorphism, port, portable, porter, POSIX, postfix, pp, pragma, precedence, prefix, preprocessing, procedure, process, program generator, progressive matching, property, protocol, prototype, pseudofunction, pseudohash, pseudoliteral, public domain, pumpkin, pumpking, PV =item Q qualified, quantifier =item R readable, reaping, record, recursion, reference, referent, regex, regular expression, regular expression modifier, regular file, relational operator, reserved words, restricted hash, return value, RFC, right shift, root, RTFM, run phase, run time, run-time pattern, RV, rvalue =item S scalar, scalar context, scalar literal, scalar value, scalar variable, scope, scratchpad, script, script kiddie, sed, semaphore, separator, serialization, server, service, setgid, setuid, shared memory, shebang, shell, side effects, signal, signal handler, single inheritance, slice, slurp, socket, soft reference, source filter, stack, standard, standard error, standard I/O, standard input, standard output, stat structure, statement, statement modifier, static, static method, static scoping, static variable, status, STDERR, STDIN, STDIO, STDOUT, stream, string, string context, stringification, struct, structure, subclass, subpattern, subroutine, subscript, substitution, substring, superclass, superuser, SV, switch, switch cluster, switch statement, symbol, symbol table, symbolic debugger, symbolic link, symbolic reference, synchronous, syntactic sugar, syntax, syntax tree, syscall =item T tainted, TCP, term, terminator, ternary, text, thread, tie, TMTOWTDI, token, tokener, tokenizing, toolbox approach, transliterate, trigger, trinary, troff, true, truncating, type, type casting, typed lexical, typedef, typeglob, typemap =item U UDP, UID, umask, unary operator, Unicode, Unix =item V value, variable, variable interpolation, variadic, vector, virtual, void context, v-string =item W warning, watch expression, whitespace, word, working directory, wrapper, WYSIWYG =item X XS, XSUB =item Y yacc =item Z zero width, zombie =back =item AUTHOR AND COPYRIGHT =back =head2 perlembed - how to embed perl in your C program =over 4 =item DESCRIPTION =over 4 =item PREAMBLE B<Use C from Perl?>, B<Use a Unix program from Perl?>, B<Use Perl from Perl?>, B<Use C from C?>, B<Use Perl from C?> =item ROADMAP =item Compiling your C program =item Adding a Perl interpreter to your C program =item Calling a Perl subroutine from your C program =item Evaluating a Perl statement from your C program =item Performing Perl pattern matches and substitutions from your C program =item Fiddling with the Perl stack from your C program =item Maintaining a persistent interpreter =item Execution of END blocks =item $0 assignments =item Maintaining multiple interpreter instances =item Using Perl modules, which themselves use C libraries, from your C program =back =item Hiding Perl_ =item MORAL =item AUTHOR =item COPYRIGHT =back =head2 perldebguts - Guts of Perl debugging =over 4 =item DESCRIPTION =item Debugger Internals =over 4 =item Writing Your Own Debugger =back =item Frame Listing Output Examples =item Debugging Regular Expressions =over 4 =item Compile-time Output C<anchored> I<STRING> C<at> I<POS>, C<floating> I<STRING> C<at> I<POS1..POS2>, C<matching floating/anchored>, C<minlen>, C<stclass> I<TYPE>, C<noscan>, C<isall>, C<GPOS>, C<plus>, C<implicit>, C<with eval>, C<anchored(TYPE)> =item Types of Nodes =item Run-time Output =back =item Debugging Perl Memory Usage =over 4 =item Using C<$ENV{PERL_DEBUG_MSTATS}> C<buckets SMALLEST(APPROX)..GREATEST(APPROX)>, Free/Used, C<Total sbrk(): SBRKed/SBRKs:CONTINUOUS>, C<pad: 0>, C<heads: 2192>, C<chain: 0>, C<tail: 6144> =back =item SEE ALSO =back =head2 perlxstut - Tutorial for writing XSUBs =over 4 =item DESCRIPTION =item SPECIAL NOTES =over 4 =item make =item Version caveat =item Dynamic Loading versus Static Loading =back =item TUTORIAL =over 4 =item EXAMPLE 1 =item EXAMPLE 2 =item What has gone on? =item Writing good test scripts =item EXAMPLE 3 =item What's new here? =item Input and Output Parameters =item The XSUBPP Program =item The TYPEMAP file =item Warning about Output Arguments =item EXAMPLE 4 =item What has happened here? =item Anatomy of .xs file =item Getting the fat out of XSUBs =item More about XSUB arguments =item The Argument Stack =item Extending your Extension =item Documenting your Extension =item Installing your Extension =item EXAMPLE 5 =item New Things in this Example =item EXAMPLE 6 =item New Things in this Example =item EXAMPLE 7 (Coming Soon) =item EXAMPLE 8 (Coming Soon) =item EXAMPLE 9 Passing open files to XSes =item Troubleshooting these Examples =back =item See also =item Author =over 4 =item Last Changed =back =back =head2 perlxs - XS language reference manual =over 4 =item DESCRIPTION =over 4 =item Introduction =item On The Road =item The Anatomy of an XSUB =item The Argument Stack =item The RETVAL Variable =item Returning SVs, AVs and HVs through RETVAL =item The MODULE Keyword =item The PACKAGE Keyword =item The PREFIX Keyword =item The OUTPUT: Keyword =item The NO_OUTPUT Keyword =item The CODE: Keyword =item The INIT: Keyword =item The NO_INIT Keyword =item The TYPEMAP: Keyword =item Initializing Function Parameters =item Default Parameter Values =item The PREINIT: Keyword =item The SCOPE: Keyword =item The INPUT: Keyword =item The IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT Keywords =item The C<length(NAME)> Keyword =item Variable-length Parameter Lists =item The C_ARGS: Keyword =item The PPCODE: Keyword =item Returning Undef And Empty Lists =item The REQUIRE: Keyword =item The CLEANUP: Keyword =item The POSTCALL: Keyword =item The BOOT: Keyword =item The VERSIONCHECK: Keyword =item The PROTOTYPES: Keyword =item The PROTOTYPE: Keyword =item The ALIAS: Keyword =item The OVERLOAD: Keyword =item The FALLBACK: Keyword =item The INTERFACE: Keyword =item The INTERFACE_MACRO: Keyword =item The INCLUDE: Keyword =item The INCLUDE_COMMAND: Keyword =item The CASE: Keyword =item The EXPORT_XSUB_SYMBOLS: Keyword =item The & Unary Operator =item Inserting POD, Comments and C Preprocessor Directives =item Using XS With C++ =item Interface Strategy =item Perl Objects And C Structures =item Safely Storing Static Data in XS MY_CXT_KEY, typedef my_cxt_t, START_MY_CXT, MY_CXT_INIT, dMY_CXT, MY_CXT, aMY_CXT/pMY_CXT, MY_CXT_CLONE, MY_CXT_INIT_INTERP(my_perl), dMY_CXT_INTERP(my_perl) =item Thread-aware system interfaces =back =item EXAMPLES =item XS VERSION =item AUTHOR =back =head2 perlxstypemap - Perl XS C/Perl type mapping =over 4 =item DESCRIPTION =over 4 =item Anatomy of a typemap =item The Role of the typemap File in Your Distribution =item Sharing typemaps Between CPAN Distributions =item Writing typemap Entries =item Full Listing of Core Typemaps T_SV, T_SVREF, T_SVREF_FIXED, T_AVREF, T_AVREF_REFCOUNT_FIXED, T_HVREF, T_HVREF_REFCOUNT_FIXED, T_CVREF, T_CVREF_REFCOUNT_FIXED, T_SYSRET, T_UV, T_IV, T_INT, T_ENUM, T_BOOL, T_U_INT, T_SHORT, T_U_SHORT, T_LONG, T_U_LONG, T_CHAR, T_U_CHAR, T_FLOAT, T_NV, T_DOUBLE, T_PV, T_PTR, T_PTRREF, T_PTROBJ, T_REF_IV_REF, T_REF_IV_PTR, T_PTRDESC, T_REFREF, T_REFOBJ, T_OPAQUEPTR, T_OPAQUE, Implicit array, T_PACKED, T_PACKEDARRAY, T_DATAUNIT, T_CALLBACK, T_ARRAY, T_STDIO, T_INOUT, T_IN, T_OUT =back =back =head2 perlclib - Internal replacements for standard C library functions =over 4 =item DESCRIPTION =over 4 =item Conventions C<t>, C<p>, C<n>, C<s> =item File Operations =item File Input and Output =item File Positioning =item Memory Management and String Handling =item Character Class Tests =item F<stdlib.h> functions =item Miscellaneous functions =back =item SEE ALSO =back =head2 perlguts - Introduction to the Perl API =over 4 =item DESCRIPTION =item Variables =over 4 =item Datatypes =item What is an "IV"? =item Working with SVs =item Offsets =item What's Really Stored in an SV? =item Working with AVs =item Working with HVs =item Hash API Extensions =item AVs, HVs and undefined values =item References =item Blessed References and Class Objects =item Creating New Variables GV_ADDMULTI, GV_ADDWARN =item Reference Counts and Mortality =item Stashes and Globs =item Double-Typed SVs =item Magic Variables =item Assigning Magic =item Magic Virtual Tables =item Finding Magic =item Understanding the Magic of Tied Hashes and Arrays =item Localizing changes C<SAVEINT(int i)>, C<SAVEIV(IV i)>, C<SAVEI32(I32 i)>, C<SAVELONG(long i)>, C<SAVESPTR(s)>, C<SAVEPPTR(p)>, C<SAVEFREESV(SV *sv)>, C<SAVEMORTALIZESV(SV *sv)>, C<SAVEFREEOP(OP *op)>, C<SAVEFREEPV(p)>, C<SAVECLEARSV(SV *sv)>, C<SAVEDELETE(HV *hv, char *key, I32 length)>, C<SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)>, C<SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)>, C<SAVESTACK_POS()>, C<SV* save_scalar(GV *gv)>, C<AV* save_ary(GV *gv)>, C<HV* save_hash(GV *gv)>, C<void save_item(SV *item)>, C<void save_list(SV **sarg, I32 maxsarg)>, C<SV* save_svref(SV **sptr)>, C<void save_aptr(AV **aptr)>, C<void save_hptr(HV **hptr)> =back =item Subroutines =over 4 =item XSUBs and the Argument Stack =item Autoloading with XSUBs =item Calling Perl Routines from within C Programs =item Memory Allocation =item PerlIO =item Putting a C value on Perl stack =item Scratchpads =item Scratchpads and recursion =back =item Compiled code =over 4 =item Code tree =item Examining the tree =item Compile pass 1: check routines =item Compile pass 1a: constant folding =item Compile pass 2: context propagation =item Compile pass 3: peephole optimization =item Pluggable runops =item Compile-time scope hooks C<void bhk_start(pTHX_ int full)>, C<void bhk_pre_end(pTHX_ OP **o)>, C<void bhk_post_end(pTHX_ OP **o)>, C<void bhk_eval(pTHX_ OP *const o)> =back =item Examining internal data structures with the C<dump> functions =item How multiple interpreters and concurrency are supported =over 4 =item Background and PERL_IMPLICIT_CONTEXT =item So what happened to dTHR? =item How do I use all this in extensions? =item Should I do anything special if I call perl from multiple threads? =item Future Plans and PERL_IMPLICIT_SYS =back =item Internal Functions A, p, d, s, n, r, f, M, o, x, m, X, E, b, others =over 4 =item Formatted Printing of IVs, UVs, and NVs =item Pointer-To-Integer and Integer-To-Pointer =item Exception Handling =item Source Documentation =item Backwards compatibility =back =item Unicode Support =over 4 =item What B<is> Unicode, anyway? =item How can I recognise a UTF-8 string? =item How does UTF-8 represent Unicode characters? =item How does Perl store UTF-8 strings? =item How do I convert a string to UTF-8? =item Is there anything else I need to know? =back =item Custom Operators xop_name, xop_desc, xop_class, OA_BASEOP, OA_UNOP, OA_BINOP, OA_LOGOP, OA_LISTOP, OA_PMOP, OA_SVOP, OA_PADOP, OA_PVOP_OR_SVOP, OA_LOOP, OA_COP, xop_peep =item AUTHORS =item SEE ALSO =back =head2 perlcall - Perl calling conventions from C =over 4 =item DESCRIPTION An Error Handler, An Event-Driven Program =item THE CALL_ FUNCTIONS call_sv, call_pv, call_method, call_argv =item FLAG VALUES =over 4 =item G_VOID =item G_SCALAR =item G_ARRAY =item G_DISCARD =item G_NOARGS =item G_EVAL =item G_KEEPERR =item Determining the Context =back =item EXAMPLES =over 4 =item No Parameters, Nothing Returned =item Passing Parameters =item Returning a Scalar =item Returning a List of Values =item Returning a List in a Scalar Context =item Returning Data from Perl via the Parameter List =item Using G_EVAL =item Using G_KEEPERR =item Using call_sv =item Using call_argv =item Using call_method =item Using GIMME_V =item Using Perl to Dispose of Temporaries =item Strategies for Storing Callback Context Information 1. Ignore the problem - Allow only 1 callback, 2. Create a sequence of callbacks - hard wired limit, 3. Use a parameter to map to the Perl callback =item Alternate Stack Manipulation =item Creating and Calling an Anonymous Subroutine in C =back =item LIGHTWEIGHT CALLBACKS =item SEE ALSO =item AUTHOR =item DATE =back =head2 perlmroapi - Perl method resolution plugin interface =over 4 =item DESCRIPTION resolve, name, length, kflags, hash =item Callbacks =item Caching =item Examples =item AUTHORS =back =head2 perlreapi - perl regular expression plugin interface =over 4 =item DESCRIPTION =item Callbacks =over 4 =item comp C</m> - RXf_PMf_MULTILINE, C</s> - RXf_PMf_SINGLELINE, C</i> - RXf_PMf_FOLD, C</x> - RXf_PMf_EXTENDED, C</p> - RXf_PMf_KEEPCOPY, Character set, RXf_UTF8, RXf_SPLIT, RXf_SKIPWHITE, RXf_START_ONLY, RXf_WHITE, RXf_NULL =item exec =item intuit =item checkstr =item free =item Numbered capture callbacks =item Named capture callbacks =item qr_package =item dupe =back =item The REGEXP structure =over 4 =item C<engine> =item C<mother_re> =item C<extflags> =item C<minlen> C<minlenret> =item C<gofs> =item C<substrs> =item C<nparens>, C<lastparen>, and C<lastcloseparen> =item C<intflags> =item C<pprivate> =item C<swap> =item C<offs> =item C<precomp> C<prelen> =item C<paren_names> =item C<substrs> =item C<subbeg> C<sublen> C<saved_copy> =item C<wrapped> C<wraplen> =item C<seen_evals> =item C<refcnt> =back =item HISTORY =item AUTHORS =item LICENSE =back =head2 perlreguts - Description of the Perl regular expression engine. =over 4 =item DESCRIPTION =item OVERVIEW =over 4 =item A quick note on terms =item What is a regular expression engine? =item Structure of a Regexp Program C<regnode_1>, C<regnode_2>, C<regnode_string>, C<regnode_charclass>, C<regnode_charclass_class> =back =item Process Overview A. Compilation, 1. Parsing for size, 2. Parsing for construction, 3. Peep-hole optimisation and analysis, B. Execution, 4. Start position and no-match optimisations, 5. Program execution =over 4 =item Compilation anchored fixed strings, floating fixed strings, minimum and maximum length requirements, start class, Beginning/End of line positions =item Execution =back =item MISCELLANEOUS =over 4 =item Unicode and Localisation Support =item Base Structures C<swap>, C<offsets>, C<regstclass>, C<data>, C<program> =back =item SEE ALSO =item AUTHOR =item LICENCE =item REFERENCES =back =head2 perlapi - autogenerated documentation for the perl public API =over 4 =item DESCRIPTION X<Perl API> X<API> X<api> =item "Gimme" Values GIMME X<GIMME>, GIMME_V X<GIMME_V>, G_ARRAY X<G_ARRAY>, G_DISCARD X<G_DISCARD>, G_EVAL X<G_EVAL>, G_NOARGS X<G_NOARGS>, G_SCALAR X<G_SCALAR>, G_VOID X<G_VOID> =item Array Manipulation Functions AvFILL X<AvFILL>, av_clear X<av_clear>, av_create_and_push X<av_create_and_push>, av_create_and_unshift_one X<av_create_and_unshift_one>, av_delete X<av_delete>, av_exists X<av_exists>, av_extend X<av_extend>, av_fetch X<av_fetch>, av_fill X<av_fill>, av_len X<av_len>, av_make X<av_make>, av_pop X<av_pop>, av_push X<av_push>, av_shift X<av_shift>, av_store X<av_store>, av_undef X<av_undef>, av_unshift X<av_unshift>, get_av X<get_av>, newAV X<newAV>, sortsv X<sortsv>, sortsv_flags X<sortsv_flags> =item Callback Functions call_argv X<call_argv>, call_method X<call_method>, call_pv X<call_pv>, call_sv X<call_sv>, ENTER X<ENTER>, eval_pv X<eval_pv>, eval_sv X<eval_sv>, FREETMPS X<FREETMPS>, LEAVE X<LEAVE>, SAVETMPS X<SAVETMPS> =item Character case changing toLOWER X<toLOWER>, toUPPER X<toUPPER> =item Character classes isALPHA X<isALPHA>, isASCII X<isASCII>, isDIGIT X<isDIGIT>, isLOWER X<isLOWER>, isOCTAL X<isOCTAL>, isSPACE X<isSPACE>, isUPPER X<isUPPER>, isWORDCHAR X<isWORDCHAR>, isXDIGIT X<isXDIGIT> =item Cloning an interpreter perl_clone X<perl_clone> =item Compile-time scope hooks BhkDISABLE X<BhkDISABLE>, BhkENABLE X<BhkENABLE>, BhkENTRY_set X<BhkENTRY_set>, blockhook_register X<blockhook_register> =item COP Hint Hashes cophh_2hv X<cophh_2hv>, cophh_copy X<cophh_copy>, cophh_delete_pv X<cophh_delete_pv>, cophh_delete_pvn X<cophh_delete_pvn>, cophh_delete_pvs X<cophh_delete_pvs>, cophh_delete_sv X<cophh_delete_sv>, cophh_fetch_pv X<cophh_fetch_pv>, cophh_fetch_pvn X<cophh_fetch_pvn>, cophh_fetch_pvs X<cophh_fetch_pvs>, cophh_fetch_sv X<cophh_fetch_sv>, cophh_free X<cophh_free>, cophh_new_empty X<cophh_new_empty>, cophh_store_pv X<cophh_store_pv>, cophh_store_pvn X<cophh_store_pvn>, cophh_store_pvs X<cophh_store_pvs>, cophh_store_sv X<cophh_store_sv> =item COP Hint Reading cop_hints_2hv X<cop_hints_2hv>, cop_hints_fetch_pv X<cop_hints_fetch_pv>, cop_hints_fetch_pvn X<cop_hints_fetch_pvn>, cop_hints_fetch_pvs X<cop_hints_fetch_pvs>, cop_hints_fetch_sv X<cop_hints_fetch_sv> =item Custom Operators custom_op_register X<custom_op_register>, custom_op_xop X<custom_op_xop>, XopDISABLE X<XopDISABLE>, XopENABLE X<XopENABLE>, XopENTRY X<XopENTRY>, XopENTRY_set X<XopENTRY_set>, XopFLAGS X<XopFLAGS> =item CV Manipulation Functions CvSTASH X<CvSTASH>, get_cv X<get_cv>, get_cvn_flags X<get_cvn_flags> =item Embedding Functions cv_clone X<cv_clone>, cv_undef X<cv_undef>, find_rundefsv X<find_rundefsv>, find_rundefsvoffset X<find_rundefsvoffset>, load_module X<load_module>, nothreadhook X<nothreadhook>, pad_add_anon X<pad_add_anon>, pad_add_name_pv X<pad_add_name_pv>, pad_add_name_pvn X<pad_add_name_pvn>, pad_add_name_sv X<pad_add_name_sv>, pad_alloc X<pad_alloc>, pad_compname_type X<pad_compname_type>, pad_findmy_pv X<pad_findmy_pv>, pad_findmy_pvn X<pad_findmy_pvn>, pad_findmy_sv X<pad_findmy_sv>, pad_setsv X<pad_setsv>, pad_sv X<pad_sv>, pad_tidy X<pad_tidy>, perl_alloc X<perl_alloc>, perl_construct X<perl_construct>, perl_destruct X<perl_destruct>, perl_free X<perl_free>, perl_parse X<perl_parse>, perl_run X<perl_run>, require_pv X<require_pv> =item Functions in file dump.c pv_display X<pv_display>, pv_escape X<pv_escape>, pv_pretty X<pv_pretty> =item Functions in file mathoms.c custom_op_desc X<custom_op_desc>, custom_op_name X<custom_op_name>, gv_fetchmethod X<gv_fetchmethod>, pack_cat X<pack_cat>, sv_2pvbyte_nolen X<sv_2pvbyte_nolen>, sv_2pvutf8_nolen X<sv_2pvutf8_nolen>, sv_2pv_nolen X<sv_2pv_nolen>, sv_catpvn_mg X<sv_catpvn_mg>, sv_catsv_mg X<sv_catsv_mg>, sv_force_normal X<sv_force_normal>, sv_iv X<sv_iv>, sv_nolocking X<sv_nolocking>, sv_nounlocking X<sv_nounlocking>, sv_nv X<sv_nv>, sv_pv X<sv_pv>, sv_pvbyte X<sv_pvbyte>, sv_pvbyten X<sv_pvbyten>, sv_pvn X<sv_pvn>, sv_pvutf8 X<sv_pvutf8>, sv_pvutf8n X<sv_pvutf8n>, sv_taint X<sv_taint>, sv_unref X<sv_unref>, sv_usepvn X<sv_usepvn>, sv_usepvn_mg X<sv_usepvn_mg>, sv_uv X<sv_uv>, unpack_str X<unpack_str> =item Functions in file op.c op_contextualize X<op_contextualize> =item Functions in file perl.h PERL_SYS_INIT X<PERL_SYS_INIT>, PERL_SYS_INIT3 X<PERL_SYS_INIT3>, PERL_SYS_TERM X<PERL_SYS_TERM> =item Functions in file pp_ctl.c caller_cx X<caller_cx>, find_runcv X<find_runcv> =item Functions in file pp_pack.c packlist X<packlist>, unpackstring X<unpackstring> =item Functions in file pp_sys.c setdefout X<setdefout> =item Functions in file utf8.h ibcmp_utf8 X<ibcmp_utf8> =item Functions in file util.h ibcmp X<ibcmp>, ibcmp_locale X<ibcmp_locale> =item Global Variables PL_check X<PL_check>, PL_keyword_plugin X<PL_keyword_plugin> =item GV Functions GvSV X<GvSV>, gv_const_sv X<gv_const_sv>, gv_fetchmeth X<gv_fetchmeth>, gv_fetchmethod_autoload X<gv_fetchmethod_autoload>, gv_fetchmeth_autoload X<gv_fetchmeth_autoload>, gv_fetchmeth_pv X<gv_fetchmeth_pv>, gv_fetchmeth_pvn X<gv_fetchmeth_pvn>, gv_fetchmeth_pvn_autoload X<gv_fetchmeth_pvn_autoload>, gv_fetchmeth_pv_autoload X<gv_fetchmeth_pv_autoload>, gv_fetchmeth_sv X<gv_fetchmeth_sv>, gv_fetchmeth_sv_autoload X<gv_fetchmeth_sv_autoload>, gv_init X<gv_init>, gv_init_pv X<gv_init_pv>, gv_init_pvn X<gv_init_pvn>, gv_init_sv X<gv_init_sv>, gv_stashpv X<gv_stashpv>, gv_stashpvn X<gv_stashpvn>, gv_stashpvs X<gv_stashpvs>, gv_stashsv X<gv_stashsv> =item Handy Values Nullav X<Nullav>, Nullch X<Nullch>, Nullcv X<Nullcv>, Nullhv X<Nullhv>, Nullsv X<Nullsv> =item Hash Manipulation Functions cop_fetch_label X<cop_fetch_label>, cop_store_label X<cop_store_label>, get_hv X<get_hv>, HEf_SVKEY X<HEf_SVKEY>, HeHASH X<HeHASH>, HeKEY X<HeKEY>, HeKLEN X<HeKLEN>, HePV X<HePV>, HeSVKEY X<HeSVKEY>, HeSVKEY_force X<HeSVKEY_force>, HeSVKEY_set X<HeSVKEY_set>, HeUTF8 X<HeUTF8>, HeVAL X<HeVAL>, HvENAME X<HvENAME>, HvENAMELEN X<HvENAMELEN>, HvENAMEUTF8 X<HvENAMEUTF8>, HvNAME X<HvNAME>, HvNAMELEN X<HvNAMELEN>, HvNAMEUTF8 X<HvNAMEUTF8>, hv_assert X<hv_assert>, hv_clear X<hv_clear>, hv_clear_placeholders X<hv_clear_placeholders>, hv_copy_hints_hv X<hv_copy_hints_hv>, hv_delete X<hv_delete>, hv_delete_ent X<hv_delete_ent>, hv_exists X<hv_exists>, hv_exists_ent X<hv_exists_ent>, hv_fetch X<hv_fetch>, hv_fetchs X<hv_fetchs>, hv_fetch_ent X<hv_fetch_ent>, hv_fill X<hv_fill>, hv_iterinit X<hv_iterinit>, hv_iterkey X<hv_iterkey>, hv_iterkeysv X<hv_iterkeysv>, hv_iternext X<hv_iternext>, hv_iternextsv X<hv_iternextsv>, hv_iternext_flags X<hv_iternext_flags>, hv_iterval X<hv_iterval>, hv_magic X<hv_magic>, hv_scalar X<hv_scalar>, hv_store X<hv_store>, hv_stores X<hv_stores>, hv_store_ent X<hv_store_ent>, hv_undef X<hv_undef>, newHV X<newHV> =item Hook manipulation wrap_op_checker X<wrap_op_checker> =item Lexer interface lex_bufutf8 X<lex_bufutf8>, lex_discard_to X<lex_discard_to>, lex_grow_linestr X<lex_grow_linestr>, lex_next_chunk X<lex_next_chunk>, lex_peek_unichar X<lex_peek_unichar>, lex_read_space X<lex_read_space>, lex_read_to X<lex_read_to>, lex_read_unichar X<lex_read_unichar>, lex_start X<lex_start>, lex_stuff_pv X<lex_stuff_pv>, lex_stuff_pvn X<lex_stuff_pvn>, lex_stuff_pvs X<lex_stuff_pvs>, lex_stuff_sv X<lex_stuff_sv>, lex_unstuff X<lex_unstuff>, parse_arithexpr X<parse_arithexpr>, parse_barestmt X<parse_barestmt>, parse_block X<parse_block>, parse_fullexpr X<parse_fullexpr>, parse_fullstmt X<parse_fullstmt>, parse_label X<parse_label>, parse_listexpr X<parse_listexpr>, parse_stmtseq X<parse_stmtseq>, parse_termexpr X<parse_termexpr>, PL_parser X<PL_parser>, PL_parser-E<gt>bufend X<PL_parser-E<gt>bufend>, PL_parser-E<gt>bufptr X<PL_parser-E<gt>bufptr>, PL_parser-E<gt>linestart X<PL_parser-E<gt>linestart>, PL_parser-E<gt>linestr X<PL_parser-E<gt>linestr> =item Magical Functions mg_clear X<mg_clear>, mg_copy X<mg_copy>, mg_find X<mg_find>, mg_findext X<mg_findext>, mg_free X<mg_free>, mg_free_type X<mg_free_type>, mg_get X<mg_get>, mg_length X<mg_length>, mg_magical X<mg_magical>, mg_set X<mg_set>, SvGETMAGIC X<SvGETMAGIC>, SvLOCK X<SvLOCK>, SvSETMAGIC X<SvSETMAGIC>, SvSetMagicSV X<SvSetMagicSV>, SvSetMagicSV_nosteal X<SvSetMagicSV_nosteal>, SvSetSV X<SvSetSV>, SvSetSV_nosteal X<SvSetSV_nosteal>, SvSHARE X<SvSHARE>, SvUNLOCK X<SvUNLOCK> =item Memory Management Copy X<Copy>, CopyD X<CopyD>, Move X<Move>, MoveD X<MoveD>, Newx X<Newx>, Newxc X<Newxc>, Newxz X<Newxz>, Poison X<Poison>, PoisonFree X<PoisonFree>, PoisonNew X<PoisonNew>, PoisonWith X<PoisonWith>, Renew X<Renew>, Renewc X<Renewc>, Safefree X<Safefree>, savepv X<savepv>, savepvn X<savepvn>, savepvs X<savepvs>, savesharedpv X<savesharedpv>, savesharedpvn X<savesharedpvn>, savesharedpvs X<savesharedpvs>, savesharedsvpv X<savesharedsvpv>, savesvpv X<savesvpv>, StructCopy X<StructCopy>, Zero X<Zero>, ZeroD X<ZeroD> =item Miscellaneous Functions fbm_compile X<fbm_compile>, fbm_instr X<fbm_instr>, foldEQ X<foldEQ>, foldEQ_locale X<foldEQ_locale>, form X<form>, getcwd_sv X<getcwd_sv>, mess X<mess>, mess_sv X<mess_sv>, my_snprintf X<my_snprintf>, my_sprintf X<my_sprintf>, my_vsnprintf X<my_vsnprintf>, new_version X<new_version>, prescan_version X<prescan_version>, scan_version X<scan_version>, strEQ X<strEQ>, strGE X<strGE>, strGT X<strGT>, strLE X<strLE>, strLT X<strLT>, strNE X<strNE>, strnEQ X<strnEQ>, strnNE X<strnNE>, sv_destroyable X<sv_destroyable>, sv_nosharing X<sv_nosharing>, upg_version X<upg_version>, vcmp X<vcmp>, vmess X<vmess>, vnormal X<vnormal>, vnumify X<vnumify>, vstringify X<vstringify>, vverify X<vverify> =item MRO Functions mro_get_linear_isa X<mro_get_linear_isa>, mro_method_changed_in X<mro_method_changed_in>, mro_register X<mro_register> =item Multicall Functions dMULTICALL X<dMULTICALL>, MULTICALL X<MULTICALL>, POP_MULTICALL X<POP_MULTICALL>, PUSH_MULTICALL X<PUSH_MULTICALL> =item Numeric functions grok_bin X<grok_bin>, grok_hex X<grok_hex>, grok_number X<grok_number>, grok_numeric_radix X<grok_numeric_radix>, grok_oct X<grok_oct>, Perl_signbit X<Perl_signbit>, scan_bin X<scan_bin>, scan_hex X<scan_hex>, scan_oct X<scan_oct> =item Optree construction newASSIGNOP X<newASSIGNOP>, newBINOP X<newBINOP>, newCONDOP X<newCONDOP>, newFOROP X<newFOROP>, newGIVENOP X<newGIVENOP>, newGVOP X<newGVOP>, newLISTOP X<newLISTOP>, newLOGOP X<newLOGOP>, newLOOPEX X<newLOOPEX>, newLOOPOP X<newLOOPOP>, newNULLLIST X<newNULLLIST>, newOP X<newOP>, newPADOP X<newPADOP>, newPMOP X<newPMOP>, newPVOP X<newPVOP>, newRANGE X<newRANGE>, newSLICEOP X<newSLICEOP>, newSTATEOP X<newSTATEOP>, newSVOP X<newSVOP>, newUNOP X<newUNOP>, newWHENOP X<newWHENOP>, newWHILEOP X<newWHILEOP> =item Optree Manipulation Functions ck_entersub_args_list X<ck_entersub_args_list>, ck_entersub_args_proto X<ck_entersub_args_proto>, ck_entersub_args_proto_or_list X<ck_entersub_args_proto_or_list>, cv_const_sv X<cv_const_sv>, cv_get_call_checker X<cv_get_call_checker>, cv_set_call_checker X<cv_set_call_checker>, LINKLIST X<LINKLIST>, newCONSTSUB X<newCONSTSUB>, newCONSTSUB_flags X<newCONSTSUB_flags>, newXS X<newXS>, op_append_elem X<op_append_elem>, op_append_list X<op_append_list>, OP_CLASS X<OP_CLASS>, OP_DESC X<OP_DESC>, op_linklist X<op_linklist>, op_lvalue X<op_lvalue>, OP_NAME X<OP_NAME>, op_prepend_elem X<op_prepend_elem>, op_scope X<op_scope>, rv2cv_op_cv X<rv2cv_op_cv> =item Pad Data Structures CvPADLIST X<CvPADLIST>, pad_add_name_pvs X<pad_add_name_pvs>, pad_findmy_pvs X<pad_findmy_pvs>, pad_new X<pad_new>, PL_comppad X<PL_comppad>, PL_comppad_name X<PL_comppad_name>, PL_curpad X<PL_curpad> =item Per-Interpreter Variables PL_modglobal X<PL_modglobal>, PL_na X<PL_na>, PL_opfreehook X<PL_opfreehook>, PL_peepp X<PL_peepp>, PL_rpeepp X<PL_rpeepp>, PL_sv_no X<PL_sv_no>, PL_sv_undef X<PL_sv_undef>, PL_sv_yes X<PL_sv_yes> =item REGEXP Functions SvRX X<SvRX>, SvRXOK X<SvRXOK> =item Simple Exception Handling Macros dXCPT X<dXCPT>, XCPT_CATCH X<XCPT_CATCH>, XCPT_RETHROW X<XCPT_RETHROW>, XCPT_TRY_END X<XCPT_TRY_END>, XCPT_TRY_START X<XCPT_TRY_START> =item Stack Manipulation Macros dMARK X<dMARK>, dORIGMARK X<dORIGMARK>, dSP X<dSP>, EXTEND X<EXTEND>, MARK X<MARK>, mPUSHi X<mPUSHi>, mPUSHn X<mPUSHn>, mPUSHp X<mPUSHp>, mPUSHs X<mPUSHs>, mPUSHu X<mPUSHu>, mXPUSHi X<mXPUSHi>, mXPUSHn X<mXPUSHn>, mXPUSHp X<mXPUSHp>, mXPUSHs X<mXPUSHs>, mXPUSHu X<mXPUSHu>, ORIGMARK X<ORIGMARK>, POPi X<POPi>, POPl X<POPl>, POPn X<POPn>, POPp X<POPp>, POPpbytex X<POPpbytex>, POPpx X<POPpx>, POPs X<POPs>, PUSHi X<PUSHi>, PUSHMARK X<PUSHMARK>, PUSHmortal X<PUSHmortal>, PUSHn X<PUSHn>, PUSHp X<PUSHp>, PUSHs X<PUSHs>, PUSHu X<PUSHu>, PUTBACK X<PUTBACK>, SP X<SP>, SPAGAIN X<SPAGAIN>, XPUSHi X<XPUSHi>, XPUSHmortal X<XPUSHmortal>, XPUSHn X<XPUSHn>, XPUSHp X<XPUSHp>, XPUSHs X<XPUSHs>, XPUSHu X<XPUSHu>, XSRETURN X<XSRETURN>, XSRETURN_EMPTY X<XSRETURN_EMPTY>, XSRETURN_IV X<XSRETURN_IV>, XSRETURN_NO X<XSRETURN_NO>, XSRETURN_NV X<XSRETURN_NV>, XSRETURN_PV X<XSRETURN_PV>, XSRETURN_UNDEF X<XSRETURN_UNDEF>, XSRETURN_UV X<XSRETURN_UV>, XSRETURN_YES X<XSRETURN_YES>, XST_mIV X<XST_mIV>, XST_mNO X<XST_mNO>, XST_mNV X<XST_mNV>, XST_mPV X<XST_mPV>, XST_mUNDEF X<XST_mUNDEF>, XST_mYES X<XST_mYES> =item SV Flags svtype X<svtype>, SVt_IV X<SVt_IV>, SVt_NV X<SVt_NV>, SVt_PV X<SVt_PV>, SVt_PVAV X<SVt_PVAV>, SVt_PVCV X<SVt_PVCV>, SVt_PVHV X<SVt_PVHV>, SVt_PVMG X<SVt_PVMG> =item SV Manipulation Functions boolSV X<boolSV>, croak_xs_usage X<croak_xs_usage>, get_sv X<get_sv>, newRV_inc X<newRV_inc>, newSVpvn_utf8 X<newSVpvn_utf8>, SvCUR X<SvCUR>, SvCUR_set X<SvCUR_set>, SvEND X<SvEND>, SvGAMAGIC X<SvGAMAGIC>, SvGROW X<SvGROW>, SvIOK X<SvIOK>, SvIOKp X<SvIOKp>, SvIOK_notUV X<SvIOK_notUV>, SvIOK_off X<SvIOK_off>, SvIOK_on X<SvIOK_on>, SvIOK_only X<SvIOK_only>, SvIOK_only_UV X<SvIOK_only_UV>, SvIOK_UV X<SvIOK_UV>, SvIsCOW X<SvIsCOW>, SvIsCOW_shared_hash X<SvIsCOW_shared_hash>, SvIV X<SvIV>, SvIVX X<SvIVX>, SvIVx X<SvIVx>, SvIV_nomg X<SvIV_nomg>, SvIV_set X<SvIV_set>, SvLEN X<SvLEN>, SvLEN_set X<SvLEN_set>, SvMAGIC_set X<SvMAGIC_set>, SvNIOK X<SvNIOK>, SvNIOKp X<SvNIOKp>, SvNIOK_off X<SvNIOK_off>, SvNOK X<SvNOK>, SvNOKp X<SvNOKp>, SvNOK_off X<SvNOK_off>, SvNOK_on X<SvNOK_on>, SvNOK_only X<SvNOK_only>, SvNV X<SvNV>, SvNVX X<SvNVX>, SvNVx X<SvNVx>, SvNV_nomg X<SvNV_nomg>, SvNV_set X<SvNV_set>, SvOK X<SvOK>, SvOOK X<SvOOK>, SvOOK_offset X<SvOOK_offset>, SvPOK X<SvPOK>, SvPOKp X<SvPOKp>, SvPOK_off X<SvPOK_off>, SvPOK_on X<SvPOK_on>, SvPOK_only X<SvPOK_only>, SvPOK_only_UTF8 X<SvPOK_only_UTF8>, SvPV X<SvPV>, SvPVbyte X<SvPVbyte>, SvPVbytex X<SvPVbytex>, SvPVbytex_force X<SvPVbytex_force>, SvPVbyte_force X<SvPVbyte_force>, SvPVbyte_nolen X<SvPVbyte_nolen>, SvPVutf8 X<SvPVutf8>, SvPVutf8x X<SvPVutf8x>, SvPVutf8x_force X<SvPVutf8x_force>, SvPVutf8_force X<SvPVutf8_force>, SvPVutf8_nolen X<SvPVutf8_nolen>, SvPVX X<SvPVX>, SvPVx X<SvPVx>, SvPV_force X<SvPV_force>, SvPV_force_nomg X<SvPV_force_nomg>, SvPV_nolen X<SvPV_nolen>, SvPV_nomg X<SvPV_nomg>, SvPV_nomg_nolen X<SvPV_nomg_nolen>, SvPV_set X<SvPV_set>, SvREFCNT X<SvREFCNT>, SvREFCNT_dec X<SvREFCNT_dec>, SvREFCNT_inc X<SvREFCNT_inc>, SvREFCNT_inc_NN X<SvREFCNT_inc_NN>, SvREFCNT_inc_simple X<SvREFCNT_inc_simple>, SvREFCNT_inc_simple_NN X<SvREFCNT_inc_simple_NN>, SvREFCNT_inc_simple_void X<SvREFCNT_inc_simple_void>, SvREFCNT_inc_simple_void_NN X<SvREFCNT_inc_simple_void_NN>, SvREFCNT_inc_void X<SvREFCNT_inc_void>, SvREFCNT_inc_void_NN X<SvREFCNT_inc_void_NN>, SvROK X<SvROK>, SvROK_off X<SvROK_off>, SvROK_on X<SvROK_on>, SvRV X<SvRV>, SvRV_set X<SvRV_set>, SvSTASH X<SvSTASH>, SvSTASH_set X<SvSTASH_set>, SvTAINT X<SvTAINT>, SvTAINTED X<SvTAINTED>, SvTAINTED_off X<SvTAINTED_off>, SvTAINTED_on X<SvTAINTED_on>, SvTRUE X<SvTRUE>, SvTRUE_nomg X<SvTRUE_nomg>, SvTYPE X<SvTYPE>, SvUOK X<SvUOK>, SvUPGRADE X<SvUPGRADE>, SvUTF8 X<SvUTF8>, SvUTF8_off X<SvUTF8_off>, SvUTF8_on X<SvUTF8_on>, SvUV X<SvUV>, SvUVX X<SvUVX>, SvUVx X<SvUVx>, SvUV_nomg X<SvUV_nomg>, SvUV_set X<SvUV_set>, SvVOK X<SvVOK>, sv_catpvn_nomg X<sv_catpvn_nomg>, sv_catpv_nomg X<sv_catpv_nomg>, sv_catsv_nomg X<sv_catsv_nomg>, sv_derived_from X<sv_derived_from>, sv_derived_from_pv X<sv_derived_from_pv>, sv_derived_from_pvn X<sv_derived_from_pvn>, sv_derived_from_sv X<sv_derived_from_sv>, sv_does X<sv_does>, sv_does_pv X<sv_does_pv>, sv_does_pvn X<sv_does_pvn>, sv_does_sv X<sv_does_sv>, sv_report_used X<sv_report_used>, sv_setsv_nomg X<sv_setsv_nomg>, sv_utf8_upgrade_nomg X<sv_utf8_upgrade_nomg> =item SV-Body Allocation looks_like_number X<looks_like_number>, newRV_noinc X<newRV_noinc>, newSV X<newSV>, newSVhek X<newSVhek>, newSViv X<newSViv>, newSVnv X<newSVnv>, newSVpv X<newSVpv>, newSVpvf X<newSVpvf>, newSVpvn X<newSVpvn>, newSVpvn_flags X<newSVpvn_flags>, newSVpvn_share X<newSVpvn_share>, newSVpvs X<newSVpvs>, newSVpvs_flags X<newSVpvs_flags>, newSVpvs_share X<newSVpvs_share>, newSVpv_share X<newSVpv_share>, newSVrv X<newSVrv>, newSVsv X<newSVsv>, newSVuv X<newSVuv>, newSV_type X<newSV_type>, sv_2bool X<sv_2bool>, sv_2bool_flags X<sv_2bool_flags>, sv_2cv X<sv_2cv>, sv_2io X<sv_2io>, sv_2iv_flags X<sv_2iv_flags>, sv_2mortal X<sv_2mortal>, sv_2nv_flags X<sv_2nv_flags>, sv_2pvbyte X<sv_2pvbyte>, sv_2pvutf8 X<sv_2pvutf8>, sv_2pv_flags X<sv_2pv_flags>, sv_2uv_flags X<sv_2uv_flags>, sv_backoff X<sv_backoff>, sv_bless X<sv_bless>, sv_catpv X<sv_catpv>, sv_catpvf X<sv_catpvf>, sv_catpvf_mg X<sv_catpvf_mg>, sv_catpvn X<sv_catpvn>, sv_catpvn_flags X<sv_catpvn_flags>, sv_catpvs X<sv_catpvs>, sv_catpvs_flags X<sv_catpvs_flags>, sv_catpvs_mg X<sv_catpvs_mg>, sv_catpvs_nomg X<sv_catpvs_nomg>, sv_catpv_flags X<sv_catpv_flags>, sv_catpv_mg X<sv_catpv_mg>, sv_catsv X<sv_catsv>, sv_catsv_flags X<sv_catsv_flags>, sv_chop X<sv_chop>, sv_clear X<sv_clear>, sv_cmp X<sv_cmp>, sv_cmp_flags X<sv_cmp_flags>, sv_cmp_locale X<sv_cmp_locale>, sv_cmp_locale_flags X<sv_cmp_locale_flags>, sv_collxfrm X<sv_collxfrm>, sv_collxfrm_flags X<sv_collxfrm_flags>, sv_copypv X<sv_copypv>, sv_dec X<sv_dec>, sv_dec_nomg X<sv_dec_nomg>, sv_eq X<sv_eq>, sv_eq_flags X<sv_eq_flags>, sv_force_normal_flags X<sv_force_normal_flags>, sv_free X<sv_free>, sv_gets X<sv_gets>, sv_grow X<sv_grow>, sv_inc X<sv_inc>, sv_inc_nomg X<sv_inc_nomg>, sv_insert X<sv_insert>, sv_insert_flags X<sv_insert_flags>, sv_isa X<sv_isa>, sv_isobject X<sv_isobject>, sv_len X<sv_len>, sv_len_utf8 X<sv_len_utf8>, sv_magic X<sv_magic>, sv_magicext X<sv_magicext>, sv_mortalcopy X<sv_mortalcopy>, sv_newmortal X<sv_newmortal>, sv_newref X<sv_newref>, sv_pos_b2u X<sv_pos_b2u>, sv_pos_u2b X<sv_pos_u2b>, sv_pos_u2b_flags X<sv_pos_u2b_flags>, sv_pvbyten_force X<sv_pvbyten_force>, sv_pvn_force X<sv_pvn_force>, sv_pvn_force_flags X<sv_pvn_force_flags>, sv_pvutf8n_force X<sv_pvutf8n_force>, sv_reftype X<sv_reftype>, sv_replace X<sv_replace>, sv_reset X<sv_reset>, sv_rvweaken X<sv_rvweaken>, sv_setiv X<sv_setiv>, sv_setiv_mg X<sv_setiv_mg>, sv_setnv X<sv_setnv>, sv_setnv_mg X<sv_setnv_mg>, sv_setpv X<sv_setpv>, sv_setpvf X<sv_setpvf>, sv_setpvf_mg X<sv_setpvf_mg>, sv_setpviv X<sv_setpviv>, sv_setpviv_mg X<sv_setpviv_mg>, sv_setpvn X<sv_setpvn>, sv_setpvn_mg X<sv_setpvn_mg>, sv_setpvs X<sv_setpvs>, sv_setpvs_mg X<sv_setpvs_mg>, sv_setpv_mg X<sv_setpv_mg>, sv_setref_iv X<sv_setref_iv>, sv_setref_nv X<sv_setref_nv>, sv_setref_pv X<sv_setref_pv>, sv_setref_pvn X<sv_setref_pvn>, sv_setref_pvs X<sv_setref_pvs>, sv_setref_uv X<sv_setref_uv>, sv_setsv X<sv_setsv>, sv_setsv_flags X<sv_setsv_flags>, sv_setsv_mg X<sv_setsv_mg>, sv_setuv X<sv_setuv>, sv_setuv_mg X<sv_setuv_mg>, sv_tainted X<sv_tainted>, sv_true X<sv_true>, sv_unmagic X<sv_unmagic>, sv_unmagicext X<sv_unmagicext>, sv_unref_flags X<sv_unref_flags>, sv_untaint X<sv_untaint>, sv_upgrade X<sv_upgrade>, sv_usepvn_flags X<sv_usepvn_flags>, sv_utf8_decode X<sv_utf8_decode>, sv_utf8_downgrade X<sv_utf8_downgrade>, sv_utf8_encode X<sv_utf8_encode>, sv_utf8_upgrade X<sv_utf8_upgrade>, sv_utf8_upgrade_flags X<sv_utf8_upgrade_flags>, sv_utf8_upgrade_nomg X<sv_utf8_upgrade_nomg>, sv_vcatpvf X<sv_vcatpvf>, sv_vcatpvfn X<sv_vcatpvfn>, sv_vcatpvf_mg X<sv_vcatpvf_mg>, sv_vsetpvf X<sv_vsetpvf>, sv_vsetpvfn X<sv_vsetpvfn>, sv_vsetpvf_mg X<sv_vsetpvf_mg> =item Unicode Support bytes_cmp_utf8 X<bytes_cmp_utf8>, bytes_from_utf8 X<bytes_from_utf8>, bytes_to_utf8 X<bytes_to_utf8>, foldEQ_utf8 X<foldEQ_utf8>, is_ascii_string X<is_ascii_string>, is_utf8_char X<is_utf8_char>, is_utf8_char_buf X<is_utf8_char_buf>, is_utf8_string X<is_utf8_string>, is_utf8_string_loc X<is_utf8_string_loc>, is_utf8_string_loclen X<is_utf8_string_loclen>, pv_uni_display X<pv_uni_display>, sv_cat_decode X<sv_cat_decode>, sv_recode_to_utf8 X<sv_recode_to_utf8>, sv_uni_display X<sv_uni_display>, to_utf8_case X<to_utf8_case>, to_utf8_fold X<to_utf8_fold>, to_utf8_lower X<to_utf8_lower>, to_utf8_title X<to_utf8_title>, to_utf8_upper X<to_utf8_upper>, utf8n_to_uvchr X<utf8n_to_uvchr>, utf8n_to_uvuni X<utf8n_to_uvuni>, utf8_distance X<utf8_distance>, utf8_hop X<utf8_hop>, utf8_length X<utf8_length>, utf8_to_bytes X<utf8_to_bytes>, utf8_to_uvchr X<utf8_to_uvchr>, utf8_to_uvchr_buf X<utf8_to_uvchr_buf>, utf8_to_uvuni X<utf8_to_uvuni>, utf8_to_uvuni_buf X<utf8_to_uvuni_buf>, uvchr_to_utf8 X<uvchr_to_utf8>, uvuni_to_utf8_flags X<uvuni_to_utf8_flags> =item Variables created by C<xsubpp> and C<xsubpp> internal functions ax X<ax>, CLASS X<CLASS>, dAX X<dAX>, dAXMARK X<dAXMARK>, dITEMS X<dITEMS>, dUNDERBAR X<dUNDERBAR>, dXSARGS X<dXSARGS>, dXSI32 X<dXSI32>, items X<items>, ix X<ix>, newXSproto X<newXSproto>, RETVAL X<RETVAL>, ST X<ST>, THIS X<THIS>, UNDERBAR X<UNDERBAR>, XS X<XS>, XS_APIVERSION_BOOTCHECK X<XS_APIVERSION_BOOTCHECK>, XS_EXTERNAL X<XS_EXTERNAL>, XS_INTERNAL X<XS_INTERNAL>, XS_VERSION X<XS_VERSION>, XS_VERSION_BOOTCHECK X<XS_VERSION_BOOTCHECK> =item Warning and Dieing croak X<croak>, croak_no_modify X<croak_no_modify>, croak_sv X<croak_sv>, die X<die>, die_sv X<die_sv>, vcroak X<vcroak>, vwarn X<vwarn>, warn X<warn>, warn_sv X<warn_sv> =item Undocumented functions GetVars X<GetVars>, Gv_AMupdate X<Gv_AMupdate>, PerlIO_clearerr X<PerlIO_clearerr>, PerlIO_close X<PerlIO_close>, PerlIO_context_layers X<PerlIO_context_layers>, PerlIO_eof X<PerlIO_eof>, PerlIO_error X<PerlIO_error>, PerlIO_fileno X<PerlIO_fileno>, PerlIO_fill X<PerlIO_fill>, PerlIO_flush X<PerlIO_flush>, PerlIO_get_base X<PerlIO_get_base>, PerlIO_get_bufsiz X<PerlIO_get_bufsiz>, PerlIO_get_cnt X<PerlIO_get_cnt>, PerlIO_get_ptr X<PerlIO_get_ptr>, PerlIO_read X<PerlIO_read>, PerlIO_seek X<PerlIO_seek>, PerlIO_set_cnt X<PerlIO_set_cnt>, PerlIO_set_ptrcnt X<PerlIO_set_ptrcnt>, PerlIO_setlinebuf X<PerlIO_setlinebuf>, PerlIO_stderr X<PerlIO_stderr>, PerlIO_stdin X<PerlIO_stdin>, PerlIO_stdout X<PerlIO_stdout>, PerlIO_tell X<PerlIO_tell>, PerlIO_unread X<PerlIO_unread>, PerlIO_write X<PerlIO_write>, Slab_Alloc X<Slab_Alloc>, Slab_Free X<Slab_Free>, _is_utf8_quotemeta X<_is_utf8_quotemeta>, amagic_call X<amagic_call>, amagic_deref_call X<amagic_deref_call>, any_dup X<any_dup>, atfork_lock X<atfork_lock>, atfork_unlock X<atfork_unlock>, av_arylen_p X<av_arylen_p>, av_iter_p X<av_iter_p>, block_gimme X<block_gimme>, call_atexit X<call_atexit>, call_list X<call_list>, calloc X<calloc>, cast_i32 X<cast_i32>, cast_iv X<cast_iv>, cast_ulong X<cast_ulong>, cast_uv X<cast_uv>, ck_warner X<ck_warner>, ck_warner_d X<ck_warner_d>, ckwarn X<ckwarn>, ckwarn_d X<ckwarn_d>, clone_params_del X<clone_params_del>, clone_params_new X<clone_params_new>, croak_nocontext X<croak_nocontext>, csighandler X<csighandler>, cx_dump X<cx_dump>, cx_dup X<cx_dup>, cxinc X<cxinc>, deb X<deb>, deb_nocontext X<deb_nocontext>, debop X<debop>, debprofdump X<debprofdump>, debstack X<debstack>, debstackptrs X<debstackptrs>, delimcpy X<delimcpy>, despatch_signals X<despatch_signals>, die_nocontext X<die_nocontext>, dirp_dup X<dirp_dup>, do_aspawn X<do_aspawn>, do_binmode X<do_binmode>, do_close X<do_close>, do_gv_dump X<do_gv_dump>, do_gvgv_dump X<do_gvgv_dump>, do_hv_dump X<do_hv_dump>, do_join X<do_join>, do_magic_dump X<do_magic_dump>, do_op_dump X<do_op_dump>, do_open X<do_open>, do_open9 X<do_open9>, do_openn X<do_openn>, do_pmop_dump X<do_pmop_dump>, do_spawn X<do_spawn>, do_spawn_nowait X<do_spawn_nowait>, do_sprintf X<do_sprintf>, do_sv_dump X<do_sv_dump>, doing_taint X<doing_taint>, doref X<doref>, dounwind X<dounwind>, dowantarray X<dowantarray>, dump_all X<dump_all>, dump_eval X<dump_eval>, dump_fds X<dump_fds>, dump_form X<dump_form>, dump_indent X<dump_indent>, dump_mstats X<dump_mstats>, dump_packsubs X<dump_packsubs>, dump_sub X<dump_sub>, dump_vindent X<dump_vindent>, filter_add X<filter_add>, filter_del X<filter_del>, filter_read X<filter_read>, foldEQ_latin1 X<foldEQ_latin1>, form_nocontext X<form_nocontext>, fp_dup X<fp_dup>, fprintf_nocontext X<fprintf_nocontext>, free_global_struct X<free_global_struct>, free_tmps X<free_tmps>, get_context X<get_context>, get_mstats X<get_mstats>, get_op_descs X<get_op_descs>, get_op_names X<get_op_names>, get_ppaddr X<get_ppaddr>, get_vtbl X<get_vtbl>, gp_dup X<gp_dup>, gp_free X<gp_free>, gp_ref X<gp_ref>, gv_AVadd X<gv_AVadd>, gv_HVadd X<gv_HVadd>, gv_IOadd X<gv_IOadd>, gv_SVadd X<gv_SVadd>, gv_add_by_type X<gv_add_by_type>, gv_autoload4 X<gv_autoload4>, gv_autoload_pv X<gv_autoload_pv>, gv_autoload_pvn X<gv_autoload_pvn>, gv_autoload_sv X<gv_autoload_sv>, gv_check X<gv_check>, gv_dump X<gv_dump>, gv_efullname X<gv_efullname>, gv_efullname3 X<gv_efullname3>, gv_efullname4 X<gv_efullname4>, gv_fetchfile X<gv_fetchfile>, gv_fetchfile_flags X<gv_fetchfile_flags>, gv_fetchpv X<gv_fetchpv>, gv_fetchpvn_flags X<gv_fetchpvn_flags>, gv_fetchsv X<gv_fetchsv>, gv_fullname X<gv_fullname>, gv_fullname3 X<gv_fullname3>, gv_fullname4 X<gv_fullname4>, gv_handler X<gv_handler>, gv_name_set X<gv_name_set>, he_dup X<he_dup>, hek_dup X<hek_dup>, hv_common X<hv_common>, hv_common_key_len X<hv_common_key_len>, hv_delayfree_ent X<hv_delayfree_ent>, hv_eiter_p X<hv_eiter_p>, hv_eiter_set X<hv_eiter_set>, hv_free_ent X<hv_free_ent>, hv_ksplit X<hv_ksplit>, hv_name_set X<hv_name_set>, hv_placeholders_get X<hv_placeholders_get>, hv_placeholders_p X<hv_placeholders_p>, hv_placeholders_set X<hv_placeholders_set>, hv_riter_p X<hv_riter_p>, hv_riter_set X<hv_riter_set>, init_global_struct X<init_global_struct>, init_i18nl10n X<init_i18nl10n>, init_i18nl14n X<init_i18nl14n>, init_stacks X<init_stacks>, init_tm X<init_tm>, instr X<instr>, is_lvalue_sub X<is_lvalue_sub>, is_uni_alnum X<is_uni_alnum>, is_uni_alnum_lc X<is_uni_alnum_lc>, is_uni_alpha X<is_uni_alpha>, is_uni_alpha_lc X<is_uni_alpha_lc>, is_uni_ascii X<is_uni_ascii>, is_uni_ascii_lc X<is_uni_ascii_lc>, is_uni_cntrl X<is_uni_cntrl>, is_uni_cntrl_lc X<is_uni_cntrl_lc>, is_uni_digit X<is_uni_digit>, is_uni_digit_lc X<is_uni_digit_lc>, is_uni_graph X<is_uni_graph>, is_uni_graph_lc X<is_uni_graph_lc>, is_uni_idfirst X<is_uni_idfirst>, is_uni_idfirst_lc X<is_uni_idfirst_lc>, is_uni_lower X<is_uni_lower>, is_uni_lower_lc X<is_uni_lower_lc>, is_uni_print X<is_uni_print>, is_uni_print_lc X<is_uni_print_lc>, is_uni_punct X<is_uni_punct>, is_uni_punct_lc X<is_uni_punct_lc>, is_uni_space X<is_uni_space>, is_uni_space_lc X<is_uni_space_lc>, is_uni_upper X<is_uni_upper>, is_uni_upper_lc X<is_uni_upper_lc>, is_uni_xdigit X<is_uni_xdigit>, is_uni_xdigit_lc X<is_uni_xdigit_lc>, is_utf8_alnum X<is_utf8_alnum>, is_utf8_alpha X<is_utf8_alpha>, is_utf8_ascii X<is_utf8_ascii>, is_utf8_cntrl X<is_utf8_cntrl>, is_utf8_digit X<is_utf8_digit>, is_utf8_graph X<is_utf8_graph>, is_utf8_idcont X<is_utf8_idcont>, is_utf8_idfirst X<is_utf8_idfirst>, is_utf8_lower X<is_utf8_lower>, is_utf8_mark X<is_utf8_mark>, is_utf8_perl_space X<is_utf8_perl_space>, is_utf8_perl_word X<is_utf8_perl_word>, is_utf8_posix_digit X<is_utf8_posix_digit>, is_utf8_print X<is_utf8_print>, is_utf8_punct X<is_utf8_punct>, is_utf8_space X<is_utf8_space>, is_utf8_upper X<is_utf8_upper>, is_utf8_xdigit X<is_utf8_xdigit>, is_utf8_xidcont X<is_utf8_xidcont>, is_utf8_xidfirst X<is_utf8_xidfirst>, leave_scope X<leave_scope>, load_module_nocontext X<load_module_nocontext>, magic_dump X<magic_dump>, malloc X<malloc>, markstack_grow X<markstack_grow>, mess_nocontext X<mess_nocontext>, mfree X<mfree>, mg_dup X<mg_dup>, mg_size X<mg_size>, mini_mktime X<mini_mktime>, moreswitches X<moreswitches>, mro_get_from_name X<mro_get_from_name>, mro_get_private_data X<mro_get_private_data>, mro_set_mro X<mro_set_mro>, mro_set_private_data X<mro_set_private_data>, my_atof X<my_atof>, my_atof2 X<my_atof2>, my_bcopy X<my_bcopy>, my_bzero X<my_bzero>, my_chsize X<my_chsize>, my_cxt_index X<my_cxt_index>, my_cxt_init X<my_cxt_init>, my_dirfd X<my_dirfd>, my_exit X<my_exit>, my_failure_exit X<my_failure_exit>, my_fflush_all X<my_fflush_all>, my_fork X<my_fork>, my_htonl X<my_htonl>, my_lstat X<my_lstat>, my_memcmp X<my_memcmp>, my_memset X<my_memset>, my_ntohl X<my_ntohl>, my_pclose X<my_pclose>, my_popen X<my_popen>, my_popen_list X<my_popen_list>, my_setenv X<my_setenv>, my_socketpair X<my_socketpair>, my_stat X<my_stat>, my_strftime X<my_strftime>, my_strlcat X<my_strlcat>, my_strlcpy X<my_strlcpy>, my_swap X<my_swap>, newANONATTRSUB X<newANONATTRSUB>, newANONHASH X<newANONHASH>, newANONLIST X<newANONLIST>, newANONSUB X<newANONSUB>, newATTRSUB X<newATTRSUB>, newAVREF X<newAVREF>, newCVREF X<newCVREF>, newFORM X<newFORM>, newGVREF X<newGVREF>, newGVgen X<newGVgen>, newGVgen_flags X<newGVgen_flags>, newHVREF X<newHVREF>, newHVhv X<newHVhv>, newIO X<newIO>, newMYSUB X<newMYSUB>, newPROG X<newPROG>, newRV X<newRV>, newSUB X<newSUB>, newSVREF X<newSVREF>, newSVpvf_nocontext X<newSVpvf_nocontext>, new_collate X<new_collate>, new_ctype X<new_ctype>, new_numeric X<new_numeric>, new_stackinfo X<new_stackinfo>, ninstr X<ninstr>, op_dump X<op_dump>, op_free X<op_free>, op_null X<op_null>, op_refcnt_lock X<op_refcnt_lock>, op_refcnt_unlock X<op_refcnt_unlock>, parser_dup X<parser_dup>, perl_alloc_using X<perl_alloc_using>, perl_clone_using X<perl_clone_using>, pmop_dump X<pmop_dump>, pop_scope X<pop_scope>, pregcomp X<pregcomp>, pregexec X<pregexec>, pregfree X<pregfree>, pregfree2 X<pregfree2>, printf_nocontext X<printf_nocontext>, ptr_table_clear X<ptr_table_clear>, ptr_table_fetch X<ptr_table_fetch>, ptr_table_free X<ptr_table_free>, ptr_table_new X<ptr_table_new>, ptr_table_split X<ptr_table_split>, ptr_table_store X<ptr_table_store>, push_scope X<push_scope>, re_compile X<re_compile>, re_dup_guts X<re_dup_guts>, re_intuit_start X<re_intuit_start>, re_intuit_string X<re_intuit_string>, realloc X<realloc>, reentrant_free X<reentrant_free>, reentrant_init X<reentrant_init>, reentrant_retry X<reentrant_retry>, reentrant_size X<reentrant_size>, ref X<ref>, reg_named_buff_all X<reg_named_buff_all>, reg_named_buff_exists X<reg_named_buff_exists>, reg_named_buff_fetch X<reg_named_buff_fetch>, reg_named_buff_firstkey X<reg_named_buff_firstkey>, reg_named_buff_nextkey X<reg_named_buff_nextkey>, reg_named_buff_scalar X<reg_named_buff_scalar>, regclass_swash X<regclass_swash>, regdump X<regdump>, regdupe_internal X<regdupe_internal>, regexec_flags X<regexec_flags>, regfree_internal X<regfree_internal>, reginitcolors X<reginitcolors>, regnext X<regnext>, repeatcpy X<repeatcpy>, rninstr X<rninstr>, rsignal X<rsignal>, rsignal_state X<rsignal_state>, runops_debug X<runops_debug>, runops_standard X<runops_standard>, rvpv_dup X<rvpv_dup>, safesyscalloc X<safesyscalloc>, safesysfree X<safesysfree>, safesysmalloc X<safesysmalloc>, safesysrealloc X<safesysrealloc>, save_I16 X<save_I16>, save_I32 X<save_I32>, save_I8 X<save_I8>, save_adelete X<save_adelete>, save_aelem X<save_aelem>, save_aelem_flags X<save_aelem_flags>, save_alloc X<save_alloc>, save_aptr X<save_aptr>, save_ary X<save_ary>, save_bool X<save_bool>, save_clearsv X<save_clearsv>, save_delete X<save_delete>, save_destructor X<save_destructor>, save_destructor_x X<save_destructor_x>, save_freeop X<save_freeop>, save_freepv X<save_freepv>, save_freesv X<save_freesv>, save_generic_pvref X<save_generic_pvref>, save_generic_svref X<save_generic_svref>, save_gp X<save_gp>, save_hash X<save_hash>, save_hdelete X<save_hdelete>, save_helem X<save_helem>, save_helem_flags X<save_helem_flags>, save_hints X<save_hints>, save_hptr X<save_hptr>, save_int X<save_int>, save_item X<save_item>, save_iv X<save_iv>, save_list X<save_list>, save_long X<save_long>, save_mortalizesv X<save_mortalizesv>, save_nogv X<save_nogv>, save_op X<save_op>, save_padsv_and_mortalize X<save_padsv_and_mortalize>, save_pptr X<save_pptr>, save_pushi32ptr X<save_pushi32ptr>, save_pushptr X<save_pushptr>, save_pushptrptr X<save_pushptrptr>, save_re_context X<save_re_context>, save_scalar X<save_scalar>, save_set_svflags X<save_set_svflags>, save_shared_pvref X<save_shared_pvref>, save_sptr X<save_sptr>, save_svref X<save_svref>, save_vptr X<save_vptr>, savestack_grow X<savestack_grow>, savestack_grow_cnt X<savestack_grow_cnt>, scan_num X<scan_num>, scan_vstring X<scan_vstring>, screaminstr X<screaminstr>, seed X<seed>, set_context X<set_context>, set_numeric_local X<set_numeric_local>, set_numeric_radix X<set_numeric_radix>, set_numeric_standard X<set_numeric_standard>, share_hek X<share_hek>, si_dup X<si_dup>, ss_dup X<ss_dup>, stack_grow X<stack_grow>, start_subparse X<start_subparse>, stashpv_hvname_match X<stashpv_hvname_match>, str_to_version X<str_to_version>, sv_2iv X<sv_2iv>, sv_2pv X<sv_2pv>, sv_2uv X<sv_2uv>, sv_catpvf_mg_nocontext X<sv_catpvf_mg_nocontext>, sv_catpvf_nocontext X<sv_catpvf_nocontext>, sv_compile_2op X<sv_compile_2op>, sv_dump X<sv_dump>, sv_dup X<sv_dup>, sv_dup_inc X<sv_dup_inc>, sv_peek X<sv_peek>, sv_pvn_nomg X<sv_pvn_nomg>, sv_setpvf_mg_nocontext X<sv_setpvf_mg_nocontext>, sv_setpvf_nocontext X<sv_setpvf_nocontext>, sv_utf8_upgrade_flags_grow X<sv_utf8_upgrade_flags_grow>, swash_fetch X<swash_fetch>, swash_init X<swash_init>, sys_init X<sys_init>, sys_init3 X<sys_init3>, sys_intern_clear X<sys_intern_clear>, sys_intern_dup X<sys_intern_dup>, sys_intern_init X<sys_intern_init>, sys_term X<sys_term>, taint_env X<taint_env>, taint_proper X<taint_proper>, tmps_grow X<tmps_grow>, to_uni_fold X<to_uni_fold>, to_uni_lower X<to_uni_lower>, to_uni_lower_lc X<to_uni_lower_lc>, to_uni_title X<to_uni_title>, to_uni_title_lc X<to_uni_title_lc>, to_uni_upper X<to_uni_upper>, to_uni_upper_lc X<to_uni_upper_lc>, unlnk X<unlnk>, unsharepvn X<unsharepvn>, utf16_to_utf8 X<utf16_to_utf8>, utf16_to_utf8_reversed X<utf16_to_utf8_reversed>, uvchr_to_utf8_flags X<uvchr_to_utf8_flags>, uvuni_to_utf8 X<uvuni_to_utf8>, vdeb X<vdeb>, vform X<vform>, vload_module X<vload_module>, vnewSVpvf X<vnewSVpvf>, vwarner X<vwarner>, warn_nocontext X<warn_nocontext>, warner X<warner>, warner_nocontext X<warner_nocontext>, whichsig X<whichsig>, whichsig_pv X<whichsig_pv>, whichsig_pvn X<whichsig_pvn>, whichsig_sv X<whichsig_sv> =item AUTHORS =item SEE ALSO =back =head2 perlintern - autogenerated documentation of purely B<internal> Perl functions =over 4 =item DESCRIPTION X<internal Perl functions> X<interpreter functions> =item Compile-time scope hooks BhkENTRY X<BhkENTRY>, BhkFLAGS X<BhkFLAGS>, CALL_BLOCK_HOOKS X<CALL_BLOCK_HOOKS> =item CV reference counts and CvOUTSIDE CvWEAKOUTSIDE X<CvWEAKOUTSIDE> =item Embedding Functions cv_dump X<cv_dump>, do_dump_pad X<do_dump_pad>, intro_my X<intro_my>, padlist_dup X<padlist_dup>, pad_alloc_name X<pad_alloc_name>, pad_block_start X<pad_block_start>, pad_check_dup X<pad_check_dup>, pad_findlex X<pad_findlex>, pad_fixup_inner_anons X<pad_fixup_inner_anons>, pad_free X<pad_free>, pad_leavemy X<pad_leavemy>, pad_push X<pad_push>, pad_reset X<pad_reset>, pad_swipe X<pad_swipe> =item Functions in file op.c core_prototype X<core_prototype> =item Functions in file pp_ctl.c docatch X<docatch> =item GV Functions gv_try_downgrade X<gv_try_downgrade> =item Hash Manipulation Functions hv_ename_add X<hv_ename_add>, hv_ename_delete X<hv_ename_delete>, refcounted_he_chain_2hv X<refcounted_he_chain_2hv>, refcounted_he_fetch_pv X<refcounted_he_fetch_pv>, refcounted_he_fetch_pvn X<refcounted_he_fetch_pvn>, refcounted_he_fetch_pvs X<refcounted_he_fetch_pvs>, refcounted_he_fetch_sv X<refcounted_he_fetch_sv>, refcounted_he_free X<refcounted_he_free>, refcounted_he_inc X<refcounted_he_inc>, refcounted_he_new_pv X<refcounted_he_new_pv>, refcounted_he_new_pvn X<refcounted_he_new_pvn>, refcounted_he_new_pvs X<refcounted_he_new_pvs>, refcounted_he_new_sv X<refcounted_he_new_sv> =item IO Functions start_glob X<start_glob> =item Magical Functions magic_clearhint X<magic_clearhint>, magic_clearhints X<magic_clearhints>, magic_methcall X<magic_methcall>, magic_sethint X<magic_sethint>, mg_localize X<mg_localize> =item MRO Functions mro_get_linear_isa_dfs X<mro_get_linear_isa_dfs>, mro_isa_changed_in X<mro_isa_changed_in>, mro_package_moved X<mro_package_moved> =item Optree Manipulation Functions finalize_optree X<finalize_optree> =item Pad Data Structures CX_CURPAD_SAVE X<CX_CURPAD_SAVE>, CX_CURPAD_SV X<CX_CURPAD_SV>, PAD_BASE_SV X<PAD_BASE_SV>, PAD_CLONE_VARS X<PAD_CLONE_VARS>, PAD_COMPNAME_FLAGS X<PAD_COMPNAME_FLAGS>, PAD_COMPNAME_GEN X<PAD_COMPNAME_GEN>, PAD_COMPNAME_GEN_set X<PAD_COMPNAME_GEN_set>, PAD_COMPNAME_OURSTASH X<PAD_COMPNAME_OURSTASH>, PAD_COMPNAME_PV X<PAD_COMPNAME_PV>, PAD_COMPNAME_TYPE X<PAD_COMPNAME_TYPE>, pad_peg X<pad_peg>, PAD_RESTORE_LOCAL X<PAD_RESTORE_LOCAL>, PAD_SAVE_LOCAL X<PAD_SAVE_LOCAL>, PAD_SAVE_SETNULLPAD X<PAD_SAVE_SETNULLPAD>, PAD_SETSV X<PAD_SETSV>, PAD_SET_CUR X<PAD_SET_CUR>, PAD_SET_CUR_NOSAVE X<PAD_SET_CUR_NOSAVE>, PAD_SV X<PAD_SV>, PAD_SVl X<PAD_SVl>, SAVECLEARSV X<SAVECLEARSV>, SAVECOMPPAD X<SAVECOMPPAD>, SAVEPADSV X<SAVEPADSV> =item Per-Interpreter Variables PL_DBsingle X<PL_DBsingle>, PL_DBsub X<PL_DBsub>, PL_DBtrace X<PL_DBtrace>, PL_dowarn X<PL_dowarn>, PL_last_in_gv X<PL_last_in_gv>, PL_ofsgv X<PL_ofsgv>, PL_rs X<PL_rs> =item Stack Manipulation Macros djSP X<djSP>, LVRET X<LVRET> =item SV Manipulation Functions sv_add_arena X<sv_add_arena>, sv_clean_all X<sv_clean_all>, sv_clean_objs X<sv_clean_objs>, sv_free_arenas X<sv_free_arenas> =item SV-Body Allocation sv_2num X<sv_2num>, sv_ref X<sv_ref> =item Unicode Support find_uninit_var X<find_uninit_var>, report_uninit X<report_uninit> =item Undocumented functions _add_range_to_invlist X<_add_range_to_invlist>, _core_swash_init X<_core_swash_init>, _invlist_array_init X<_invlist_array_init>, _invlist_contents X<_invlist_contents>, _invlist_intersection X<_invlist_intersection>, _invlist_intersection_maybe_complement_2nd X<_invlist_intersection_maybe_complement_2nd>, _invlist_invert X<_invlist_invert>, _invlist_invert_prop X<_invlist_invert_prop>, _invlist_populate_swatch X<_invlist_populate_swatch>, _invlist_subtract X<_invlist_subtract>, _invlist_union X<_invlist_union>, _invlist_union_maybe_complement_2nd X<_invlist_union_maybe_complement_2nd>, _is_utf8__perl_idstart X<_is_utf8__perl_idstart>, _new_invlist X<_new_invlist>, _swash_inversion_hash X<_swash_inversion_hash>, _swash_to_invlist X<_swash_to_invlist>, _to_fold_latin1 X<_to_fold_latin1>, _to_upper_title_latin1 X<_to_upper_title_latin1>, aassign_common_vars X<aassign_common_vars>, add_cp_to_invlist X<add_cp_to_invlist>, addmad X<addmad>, allocmy X<allocmy>, amagic_is_enabled X<amagic_is_enabled>, append_madprops X<append_madprops>, apply X<apply>, av_reify X<av_reify>, bind_match X<bind_match>, block_end X<block_end>, block_start X<block_start>, boot_core_PerlIO X<boot_core_PerlIO>, boot_core_UNIVERSAL X<boot_core_UNIVERSAL>, boot_core_mro X<boot_core_mro>, cando X<cando>, check_utf8_print X<check_utf8_print>, ck_entersub_args_core X<ck_entersub_args_core>, convert X<convert>, coresub_op X<coresub_op>, create_eval_scope X<create_eval_scope>, cv_ckproto_len_flags X<cv_ckproto_len_flags>, cvgv_set X<cvgv_set>, cvstash_set X<cvstash_set>, deb_stack_all X<deb_stack_all>, delete_eval_scope X<delete_eval_scope>, die_unwind X<die_unwind>, do_aexec X<do_aexec>, do_aexec5 X<do_aexec5>, do_eof X<do_eof>, do_exec X<do_exec>, do_exec3 X<do_exec3>, do_execfree X<do_execfree>, do_ipcctl X<do_ipcctl>, do_ipcget X<do_ipcget>, do_msgrcv X<do_msgrcv>, do_msgsnd X<do_msgsnd>, do_ncmp X<do_ncmp>, do_op_xmldump X<do_op_xmldump>, do_pmop_xmldump X<do_pmop_xmldump>, do_print X<do_print>, do_readline X<do_readline>, do_seek X<do_seek>, do_semop X<do_semop>, do_shmio X<do_shmio>, do_sysseek X<do_sysseek>, do_tell X<do_tell>, do_trans X<do_trans>, do_vecget X<do_vecget>, do_vecset X<do_vecset>, do_vop X<do_vop>, dofile X<dofile>, dump_all_perl X<dump_all_perl>, dump_packsubs_perl X<dump_packsubs_perl>, dump_sub_perl X<dump_sub_perl>, dump_sv_child X<dump_sv_child>, emulate_cop_io X<emulate_cop_io>, feature_is_enabled X<feature_is_enabled>, find_rundefsv2 X<find_rundefsv2>, find_script X<find_script>, free_tied_hv_pool X<free_tied_hv_pool>, get_db_sub X<get_db_sub>, get_debug_opts X<get_debug_opts>, get_hash_seed X<get_hash_seed>, get_invlist_iter_addr X<get_invlist_iter_addr>, get_invlist_len_addr X<get_invlist_len_addr>, get_invlist_version_id_addr X<get_invlist_version_id_addr>, get_invlist_zero_addr X<get_invlist_zero_addr>, get_no_modify X<get_no_modify>, get_opargs X<get_opargs>, get_re_arg X<get_re_arg>, getenv_len X<getenv_len>, hfree_next_entry X<hfree_next_entry>, hv_backreferences_p X<hv_backreferences_p>, hv_kill_backrefs X<hv_kill_backrefs>, hv_undef_flags X<hv_undef_flags>, init_argv_symbols X<init_argv_symbols>, init_dbargs X<init_dbargs>, init_debugger X<init_debugger>, invert X<invert>, invlist_array X<invlist_array>, invlist_clone X<invlist_clone>, invlist_iterinit X<invlist_iterinit>, invlist_len X<invlist_len>, invlist_max X<invlist_max>, invlist_set_len X<invlist_set_len>, invlist_trim X<invlist_trim>, io_close X<io_close>, is_utf8_X_L X<is_utf8_X_L>, is_utf8_X_LV X<is_utf8_X_LV>, is_utf8_X_LVT X<is_utf8_X_LVT>, is_utf8_X_LV_LVT_V X<is_utf8_X_LV_LVT_V>, is_utf8_X_T X<is_utf8_X_T>, is_utf8_X_V X<is_utf8_X_V>, is_utf8_X_begin X<is_utf8_X_begin>, is_utf8_X_extend X<is_utf8_X_extend>, is_utf8_X_non_hangul X<is_utf8_X_non_hangul>, is_utf8_X_prepend X<is_utf8_X_prepend>, jmaybe X<jmaybe>, keyword X<keyword>, keyword_plugin_standard X<keyword_plugin_standard>, list X<list>, localize X<localize>, mad_free X<mad_free>, madlex X<madlex>, madparse X<madparse>, magic_clear_all_env X<magic_clear_all_env>, magic_clearenv X<magic_clearenv>, magic_clearisa X<magic_clearisa>, magic_clearpack X<magic_clearpack>, magic_clearsig X<magic_clearsig>, magic_existspack X<magic_existspack>, magic_freearylen_p X<magic_freearylen_p>, magic_freeovrld X<magic_freeovrld>, magic_get X<magic_get>, magic_getarylen X<magic_getarylen>, magic_getdefelem X<magic_getdefelem>, magic_getnkeys X<magic_getnkeys>, magic_getpack X<magic_getpack>, magic_getpos X<magic_getpos>, magic_getsig X<magic_getsig>, magic_getsubstr X<magic_getsubstr>, magic_gettaint X<magic_gettaint>, magic_getuvar X<magic_getuvar>, magic_getvec X<magic_getvec>, magic_killbackrefs X<magic_killbackrefs>, magic_len X<magic_len>, magic_nextpack X<magic_nextpack>, magic_regdata_cnt X<magic_regdata_cnt>, magic_regdatum_get X<magic_regdatum_get>, magic_regdatum_set X<magic_regdatum_set>, magic_scalarpack X<magic_scalarpack>, magic_set X<magic_set>, magic_set_all_env X<magic_set_all_env>, magic_setamagic X<magic_setamagic>, magic_setarylen X<magic_setarylen>, magic_setcollxfrm X<magic_setcollxfrm>, magic_setdbline X<magic_setdbline>, magic_setdefelem X<magic_setdefelem>, magic_setenv X<magic_setenv>, magic_setisa X<magic_setisa>, magic_setmglob X<magic_setmglob>, magic_setnkeys X<magic_setnkeys>, magic_setpack X<magic_setpack>, magic_setpos X<magic_setpos>, magic_setregexp X<magic_setregexp>, magic_setsig X<magic_setsig>, magic_setsubstr X<magic_setsubstr>, magic_settaint X<magic_settaint>, magic_setutf8 X<magic_setutf8>, magic_setuvar X<magic_setuvar>, magic_setvec X<magic_setvec>, magic_setvstring X<magic_setvstring>, magic_sizepack X<magic_sizepack>, magic_wipepack X<magic_wipepack>, malloc_good_size X<malloc_good_size>, malloced_size X<malloced_size>, mem_collxfrm X<mem_collxfrm>, mode_from_discipline X<mode_from_discipline>, more_bodies X<more_bodies>, mro_meta_dup X<mro_meta_dup>, mro_meta_init X<mro_meta_init>, munge_qwlist_to_paren_list X<munge_qwlist_to_paren_list>, my_attrs X<my_attrs>, my_betoh16 X<my_betoh16>, my_betoh32 X<my_betoh32>, my_betoh64 X<my_betoh64>, my_betohi X<my_betohi>, my_betohl X<my_betohl>, my_betohs X<my_betohs>, my_clearenv X<my_clearenv>, my_htobe16 X<my_htobe16>, my_htobe32 X<my_htobe32>, my_htobe64 X<my_htobe64>, my_htobei X<my_htobei>, my_htobel X<my_htobel>, my_htobes X<my_htobes>, my_htole16 X<my_htole16>, my_htole32 X<my_htole32>, my_htole64 X<my_htole64>, my_htolei X<my_htolei>, my_htolel X<my_htolel>, my_htoles X<my_htoles>, my_letoh16 X<my_letoh16>, my_letoh32 X<my_letoh32>, my_letoh64 X<my_letoh64>, my_letohi X<my_letohi>, my_letohl X<my_letohl>, my_letohs X<my_letohs>, my_lstat_flags X<my_lstat_flags>, my_stat_flags X<my_stat_flags>, my_swabn X<my_swabn>, my_unexec X<my_unexec>, newATTRSUB_flags X<newATTRSUB_flags>, newGP X<newGP>, newMADPROP X<newMADPROP>, newMADsv X<newMADsv>, newTOKEN X<newTOKEN>, newXS_len_flags X<newXS_len_flags>, new_warnings_bitfield X<new_warnings_bitfield>, nextargv X<nextargv>, oopsAV X<oopsAV>, oopsHV X<oopsHV>, op_clear X<op_clear>, op_const_sv X<op_const_sv>, op_getmad X<op_getmad>, op_getmad_weak X<op_getmad_weak>, op_integerize X<op_integerize>, op_lvalue_flags X<op_lvalue_flags>, op_refcnt_dec X<op_refcnt_dec>, op_refcnt_inc X<op_refcnt_inc>, op_std_init X<op_std_init>, op_xmldump X<op_xmldump>, package X<package>, package_version X<package_version>, parse_unicode_opts X<parse_unicode_opts>, parser_free X<parser_free>, peep X<peep>, pending_Slabs_to_ro X<pending_Slabs_to_ro>, pmop_xmldump X<pmop_xmldump>, pmruntime X<pmruntime>, populate_isa X<populate_isa>, prepend_madprops X<prepend_madprops>, qerror X<qerror>, reg_named_buff X<reg_named_buff>, reg_named_buff_iter X<reg_named_buff_iter>, reg_numbered_buff_fetch X<reg_numbered_buff_fetch>, reg_numbered_buff_length X<reg_numbered_buff_length>, reg_numbered_buff_store X<reg_numbered_buff_store>, reg_qr_package X<reg_qr_package>, reg_temp_copy X<reg_temp_copy>, regcurly X<regcurly>, regprop X<regprop>, report_evil_fh X<report_evil_fh>, report_redefined_cv X<report_redefined_cv>, report_wrongway_fh X<report_wrongway_fh>, rpeep X<rpeep>, rsignal_restore X<rsignal_restore>, rsignal_save X<rsignal_save>, rxres_save X<rxres_save>, same_dirent X<same_dirent>, sawparens X<sawparens>, scalar X<scalar>, scalarvoid X<scalarvoid>, set_regclass_bit X<set_regclass_bit>, sighandler X<sighandler>, softref2xv X<softref2xv>, sub_crush_depth X<sub_crush_depth>, sv_add_backref X<sv_add_backref>, sv_catxmlpv X<sv_catxmlpv>, sv_catxmlpvn X<sv_catxmlpvn>, sv_catxmlsv X<sv_catxmlsv>, sv_compile_2op_is_broken X<sv_compile_2op_is_broken>, sv_del_backref X<sv_del_backref>, sv_free2 X<sv_free2>, sv_kill_backrefs X<sv_kill_backrefs>, sv_sethek X<sv_sethek>, sv_setsv_cow X<sv_setsv_cow>, sv_unglob X<sv_unglob>, sv_xmlpeek X<sv_xmlpeek>, tied_method X<tied_method>, token_free X<token_free>, token_getmad X<token_getmad>, translate_substr_offsets X<translate_substr_offsets>, try_amagic_bin X<try_amagic_bin>, try_amagic_un X<try_amagic_un>, unshare_hek X<unshare_hek>, utilize X<utilize>, varname X<varname>, vivify_defelem X<vivify_defelem>, vivify_ref X<vivify_ref>, wait4pid X<wait4pid>, was_lvalue_sub X<was_lvalue_sub>, watch X<watch>, write_to_stderr X<write_to_stderr>, xmldump_all X<xmldump_all>, xmldump_all_perl X<xmldump_all_perl>, xmldump_eval X<xmldump_eval>, xmldump_form X<xmldump_form>, xmldump_indent X<xmldump_indent>, xmldump_packsubs X<xmldump_packsubs>, xmldump_packsubs_perl X<xmldump_packsubs_perl>, xmldump_sub X<xmldump_sub>, xmldump_sub_perl X<xmldump_sub_perl>, xmldump_vindent X<xmldump_vindent>, xs_apiversion_bootcheck X<xs_apiversion_bootcheck>, xs_version_bootcheck X<xs_version_bootcheck>, yyerror X<yyerror>, yyerror_pv X<yyerror_pv>, yyerror_pvn X<yyerror_pvn>, yylex X<yylex>, yyparse X<yyparse>, yyunlex X<yyunlex> =item AUTHORS =item SEE ALSO =back =head2 perliol - C API for Perl's implementation of IO in Layers. =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item History and Background =item Basic Structure =item Layers vs Disciplines =item Data Structures =item Functions and Attributes =item Per-instance Data =item Layers in action. =item Per-instance flag bits PERLIO_F_EOF, PERLIO_F_CANWRITE, PERLIO_F_CANREAD, PERLIO_F_ERROR, PERLIO_F_TRUNCATE, PERLIO_F_APPEND, PERLIO_F_CRLF, PERLIO_F_UTF8, PERLIO_F_UNBUF, PERLIO_F_WRBUF, PERLIO_F_RDBUF, PERLIO_F_LINEBUF, PERLIO_F_TEMP, PERLIO_F_OPEN, PERLIO_F_FASTGETS =item Methods in Detail fsize, name, size, kind, PERLIO_K_BUFFERED, PERLIO_K_RAW, PERLIO_K_CANCRLF, PERLIO_K_FASTGETS, PERLIO_K_MULTIARG, Pushed, Popped, Open, Binmode, Getarg, Fileno, Dup, Read, Write, Seek, Tell, Close, Flush, Fill, Eof, Error, Clearerr, Setlinebuf, Get_base, Get_bufsiz, Get_ptr, Get_cnt, Set_ptrcnt =item Utilities =item Implementing PerlIO Layers C implementations, Perl implementations =item Core Layers "unix", "perlio", "stdio", "crlf", "mmap", "pending", "raw", "utf8" =item Extension Layers ":encoding", ":scalar", ":via" =back =item TODO =back =head2 perlapio - perl's IO abstraction interface. =over 4 =item SYNOPSIS =item DESCRIPTION 1. USE_STDIO, 2. USE_SFIO, 3. USE_PERLIO, B<PerlIO_stdin()>, B<PerlIO_stdout()>, B<PerlIO_stderr()>, B<PerlIO_open(path, mode)>, B<PerlIO_fdopen(fd,mode)>, B<PerlIO_reopen(path,mode,f)>, B<PerlIO_printf(f,fmt,...)>, B<PerlIO_vprintf(f,fmt,a)>, B<PerlIO_stdoutf(fmt,...)>, B<PerlIO_read(f,buf,count)>, B<PerlIO_write(f,buf,count)>, B<PerlIO_close(f)>, B<PerlIO_puts(f,s)>, B<PerlIO_putc(f,c)>, B<PerlIO_ungetc(f,c)>, B<PerlIO_getc(f)>, B<PerlIO_eof(f)>, B<PerlIO_error(f)>, B<PerlIO_fileno(f)>, B<PerlIO_clearerr(f)>, B<PerlIO_flush(f)>, B<PerlIO_seek(f,offset,whence)>, B<PerlIO_tell(f)>, B<PerlIO_getpos(f,p)>, B<PerlIO_setpos(f,p)>, B<PerlIO_rewind(f)>, B<PerlIO_tmpfile()>, B<PerlIO_setlinebuf(f)> =over 4 =item Co-existence with stdio B<PerlIO_importFILE(f,mode)>, B<PerlIO_exportFILE(f,mode)>, B<PerlIO_releaseFILE(p,f)>, B<PerlIO_findFILE(f)> =item "Fast gets" Functions B<PerlIO_fast_gets(f)>, B<PerlIO_has_cntptr(f)>, B<PerlIO_get_cnt(f)>, B<PerlIO_get_ptr(f)>, B<PerlIO_set_ptrcnt(f,p,c)>, B<PerlIO_canset_cnt(f)>, B<PerlIO_set_cnt(f,c)>, B<PerlIO_has_base(f)>, B<PerlIO_get_base(f)>, B<PerlIO_get_bufsiz(f)> =item Other Functions PerlIO_apply_layers(f,mode,layers), PerlIO_binmode(f,ptype,imode,layers), 'E<lt>' read, 'E<gt>' write, '+' read/write, PerlIO_debug(fmt,...) =back =back =head2 perlhack - How to hack on Perl =over 4 =item DESCRIPTION =item SUPER QUICK PATCH GUIDE Check out the source repository, Make your change, Test your change, Commit your change, Send your change to perlbug, Thank you =item BUG REPORTING =item PERL 5 PORTERS =over 4 =item perl-changes mailing list =item #p5p on IRC =back =item GETTING THE PERL SOURCE =over 4 =item Read access via Git =item Read access via the web =item Read access via rsync =item Write access via git =back =item PATCHING PERL =over 4 =item Submitting patches =item Getting your patch accepted Why, What, How =item Patching a core module =item Updating perldelta =item What makes for a good patch? =back =item TESTING F<t/base> and F<t/comp>, F<t/cmd>, F<t/run>, F<t/io> and F<t/op>, Everything else =over 4 =item Special C<make test> targets test_porting, coretest, test.deparse, test.taintwarn, minitest, test.valgrind check.valgrind utest.valgrind ucheck.valgrind, test.torture torturetest, utest ucheck test.utf8 check.utf8, minitest.utf16 test.utf16, test_harness, test-notty test_notty =item Parallel tests =item Running tests by hand =item Using F<t/harness> for testing -v, -torture, -re=PATTERN, -re LIST OF PATTERNS, PERL_CORE=1, PERL_DESTRUCT_LEVEL=2, PERL, PERL_SKIP_TTY_TEST, PERL_TEST_Net_Ping, PERL_TEST_NOVREXX, PERL_TEST_NUMCONVERTS =back =item MORE READING FOR GUTS HACKERS L<perlsource>, L<perlinterp>, L<perlhacktut>, L<perlhacktips>, L<perlguts>, L<perlxstut> and L<perlxs>, L<perlapi>, F<Porting/pumpkin.pod>, The perl5-porters FAQ =item CPAN TESTERS AND PERL SMOKERS =item WHAT NEXT? =over 4 =item "The Road goes ever on and on, down from the door where it began." =item Metaphoric Quotations =back =item AUTHOR =back =head2 perlsource - A guide to the Perl source tree =over 4 =item DESCRIPTION =item FINDING YOUR WAY AROUND =over 4 =item C code =item Core modules F<lib/>, F<ext/>, F<dist/>, F<cpan/> =item Tests Module tests, F<t/base/>, F<t/cmd/>, F<t/comp/>, F<t/io/>, F<t/mro/>, F<t/op/>, F<t/re/>, F<t/run/>, F<t/uni/>, F<t/win32/>, F<t/porting/>, F<t/lib/>, F<t/x2p> =item Documentation =item Hacking tools and documentation F<check*>, F<Maintainers>, F<Maintainers.pl>, and F<Maintainers.pm>, F<podtidy> =item Build system =item F<AUTHORS> =item F<MANIFEST> =back =back =head2 perlinterp - An overview of the Perl interpreter =over 4 =item DESCRIPTION =item ELEMENTS OF THE INTERPRETER =over 4 =item Startup =item Parsing =item Optimization =item Running =item Exception handing =item INTERNAL VARIABLE TYPES =back =item OP TREES =item STACKS =over 4 =item Argument stack =item Mark stack =item Save stack =back =item MILLIONS OF MACROS =item FURTHER READING =back =head2 perlhacktut - Walk through the creation of a simple C code patch =over 4 =item DESCRIPTION =item EXAMPLE OF A SIMPLE PATCH =over 4 =item Writing the patch =item Testing the patch =item Documenting the patch =item Submit =back =item AUTHOR =back =head2 perlhacktips - Tips for Perl core C code hacking =over 4 =item DESCRIPTION =item COMMON PROBLEMS =over 4 =item Perl environment problems =item Portability problems =item Problematic System Interfaces =item Security problems =back =item DEBUGGING =over 4 =item Poking at Perl =item Using a source-level debugger run [args], break function_name, break source.c:xxx, step, next, continue, finish, 'enter', print =item gdb macro support =item Dumping Perl Data Structures =back =item SOURCE CODE STATIC ANALYSIS =over 4 =item lint, splint =item Coverity =item cpd (cut-and-paste detector) =item gcc warnings =item Warnings of other C compilers =back =item MEMORY DEBUGGERS =over 4 =item Rational Software's Purify -Accflags=-DPURIFY, -Doptimize='-g', -Uusemymalloc, -Dusemultiplicity, DEFINES, USE_MULTI = define, #PERL_MALLOC = define, CFG = Debug =item valgrind =back =item PROFILING =over 4 =item Gprof Profiling -a, -b, -e routine, -f routine, -s, -z =item GCC gcov Profiling =back =item MISCELLANEOUS TRICKS =over 4 =item PERL_DESTRUCT_LEVEL =item PERL_MEM_LOG =item DDD over gdb =item Poison =item Read-only optrees =item The .i Targets =back =item AUTHOR =back =head2 perlpolicy - Various and sundry policies and commitments related to the Perl core =over 4 =item DESCRIPTION =item GOVERNANCE =over 4 =item Perl 5 Porters =back =item MAINTENANCE AND SUPPORT =item BACKWARD COMPATIBILITY AND DEPRECATION =over 4 =item Terminology experimental, deprecated, discouraged, removed =back =item MAINTENANCE BRANCHES =over 4 =item Getting changes into a maint branch =back =item CONTRIBUTED MODULES =over 4 =item A Social Contract about Artistic Control =back =item DOCUMENTATION =item CREDITS =back =head2 perlgit - Detailed information about git and the Perl repository =over 4 =item DESCRIPTION =item CLONING THE REPOSITORY =item WORKING WITH THE REPOSITORY =over 4 =item Finding out your status =item Patch workflow =item Committing your changes =item Using git to send patch emails =item A note on derived files =item Cleaning a working directory =item Bisecting =back =item Topic branches and rewriting history =over 4 =item Grafts =back =item WRITE ACCESS TO THE GIT REPOSITORY =item Accepting a patch =over 4 =item Committing to blead =item Committing to maintenance versions =item Merging from a branch via GitHub =item A note on camel and dromedary =back =back =head2 perlbook - Books about and related to Perl =over 4 =item DESCRIPTION =over 4 =item The most popular books I<Programming Perl> (the "Camel Book"):, I<The Perl Cookbook> (the "Ram Book"):, I<Learning Perl> (the "Llama Book"), I<Intermediate Perl> (the "Alpaca Book") =item References I<Perl 5 Pocket Reference>, I<Perl Debugger Pocket Reference>, I<Regular Expression Pocket Reference> =item Tutorials I<Beginning Perl>, I<Learning Perl>, I<Intermediate Perl> (the "Alpaca Book"), I<Mastering Perl>, I<Effective Perl Programming> =item Task-Oriented I<Writing Perl Modules for CPAN>, I<The Perl Cookbook>, I<Automating System Administration with Perl>, I<Real World SQL Server Administration with Perl> =item Special Topics I<Regular Expressions Cookbook>, I<Programming the Perl DBI>, I<Perl Best Practices>, I<Higher-Order Perl>, I<Mastering Regular Expressions>, I<Network Programming with Perl>, I<Perl Template Toolkit>, I<Object Oriented Perl>, I<Data Munging with Perl>, I<Mastering Perl/Tk>, I<Extending and Embedding Perl>, I<Pro Perl Debugging> =item Free (as in beer) books =item Other interesting, non-Perl books I<Programming Pearls>, I<More Programming Pearls> =item A note on freshness =item Get your book listed =back =back =head2 perlcommunity - a brief overview of the Perl community =over 4 =item DESCRIPTION =over 4 =item Where to Find the Community =item Mailing Lists and Newsgroups =item IRC =item Websites L<http://perl.com/>, L<http://use.perl.org/>, L<http://www.perlmonks.org/> =item User Groups =item Workshops =item Hackathons =item Conventions =item Calendar of Perl Events =back =item AUTHOR =back =head2 perldoc - Look up Perl documentation in Pod format. =over 4 =item SYNOPSIS =item DESCRIPTION =item OPTIONS B<-h>, B<-D>, B<-t>, B<-u>, B<-m> I<module>, B<-l>, B<-F>, B<-f> I<perlfunc>, B<-q> I<perlfaq-search-regexp>, B<-v> I<perlvar>, B<-T>, B<-d> I<destination-filename>, B<-o> I<output-formatname>, B<-M> I<module-name>, B<-w> I<option:value> or B<-w> I<option>, B<-X>, B<-L> I<language_code>, B<PageName|ModuleName|ProgramName|URL>, B<-n> I<some-formatter>, B<-r>, B<-i>, B<-V> =item SECURITY =item ENVIRONMENT =item CHANGES =item SEE ALSO =item AUTHOR =back =head2 perlhist - the Perl history records =over 4 =item DESCRIPTION =item INTRODUCTION =item THE KEEPERS OF THE PUMPKIN =over 4 =item PUMPKIN? =back =item THE RECORDS =over 4 =item SELECTED RELEASE SIZES =item SELECTED PATCH SIZES =back =item THE KEEPERS OF THE RECORDS =back =head2 perldelta - what is new for perl v5.16.3 =over 4 =item DESCRIPTION =item Core Enhancements =item Security =over 4 =item CVE-2013-1667: memory exhaustion with arbitrary hash keys =item wrap-around with IO on long strings =item memory leak in Encode =back =item Incompatible Changes =item Deprecations =item Modules and Pragmata =over 4 =item Updated Modules and Pragmata =back =item Known Problems =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5163delta, perldelta - what is new for perl v5.16.3 =over 4 =item DESCRIPTION =item Core Enhancements =item Security =over 4 =item CVE-2013-1667: memory exhaustion with arbitrary hash keys =item wrap-around with IO on long strings =item memory leak in Encode =back =item Incompatible Changes =item Deprecations =item Modules and Pragmata =over 4 =item Updated Modules and Pragmata =back =item Known Problems =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5162delta - what is new for perl v5.16.2 =over 4 =item DESCRIPTION =item Incompatible Changes =item Modules and Pragmata =over 4 =item Updated Modules and Pragmata =back =item Configuration and Compilation configuration should no longer be confused by ls colorization =item Platform Support =over 4 =item Platform-Specific Notes AIX =back =item Selected Bug Fixes fix /\h/ equivalence with /[\h]/ =item Known Problems =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5161delta - what is new for perl v5.16.1 =over 4 =item DESCRIPTION =item Security =over 4 =item an off-by-two error in Scalar-List-Util has been fixed =back =item Incompatible Changes =item Modules and Pragmata =over 4 =item Updated Modules and Pragmata =back =item Configuration and Compilation =item Platform Support =over 4 =item Platform-Specific Notes VMS =back =item Selected Bug Fixes =item Known Problems =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5160delta - what is new for perl v5.16.0 =over 4 =item DESCRIPTION =item Notice =item Core Enhancements =over 4 =item C<use I<VERSION>> =item C<__SUB__> =item New and Improved Built-ins =item Unicode Support =item XS Changes =item Changes to Special Variables =item Debugger Changes =item The C<CORE> Namespace =item Other Changes =back =item Security =over 4 =item Use C<is_utf8_char_buf()> and not C<is_utf8_char()> =item Malformed UTF-8 input could cause attempts to read beyond the end of the buffer =item C<File::Glob::bsd_glob()> memory error with GLOB_ALTDIRFUNC (CVE-2011-2728). =item Privileges are now set correctly when assigning to C<$(> =back =item Deprecations =over 4 =item Don't read the Unicode data base files in F<lib/unicore> =item XS functions C<is_utf8_char()>, C<utf8_to_uvchr()> and C<utf8_to_uvuni()> =back =item Future Deprecations =over 4 =item Core Modules =item Platforms with no supporting programmers: =item Other Future Deprecations =back =item Incompatible Changes =over 4 =item Special blocks called in void context =item The C<overloading> pragma and regexp objects =item Two XS typemap Entries removed =item Unicode 6.1 has incompatibilities with Unicode 6.0 =item Borland compiler =item Certain deprecated Unicode properties are no longer supported by default =item Dereferencing IO thingies as typeglobs =item User-defined case-changing operations =item XSUBs are now 'static' =item Weakening read-only references =item Tying scalars that hold typeglobs =item IPC::Open3 no longer provides C<xfork()>, C<xclose_on_exec()> and C<xpipe_anon()> =item C<$$> no longer caches PID =item C<$$> and C<getppid()> no longer emulate POSIX semantics under LinuxThreads =item C<< $< >>, C<< $> >>, C<$(> and C<$)> are no longer cached =item Which Non-ASCII characters get quoted by C<quotemeta> and C<\Q> has changed =back =item Performance Enhancements =item Modules and Pragmata =over 4 =item Deprecated Modules L<Version::Requirements> =item New Modules and Pragmata =item Updated Modules and Pragmata =item Removed Modules and Pragmata =back =item Documentation =over 4 =item New Documentation =item Changes to Existing Documentation =item Removed Documentation =back =item Diagnostics =over 4 =item New Diagnostics =item Removed Errors =item Changes to Existing Diagnostics =back =item Utility Changes =item Configuration and Compilation =item Platform Support =over 4 =item Platform-Specific Notes =back =item Internal Changes =item Selected Bug Fixes =over 4 =item Array and hash =item C API fixes =item Compile-time hints =item Copy-on-write scalars =item The debugger =item Dereferencing operators =item Filehandle, last-accessed =item Filetests and C<stat> =item Formats =item C<given> and C<when> =item The C<glob> operator =item Lvalue subroutines =item Overloading =item Prototypes of built-in keywords =item Regular expressions =item Smartmatching =item The C<sort> operator =item The C<substr> operator =item Support for embedded nulls =item Threading bugs =item Tied variables =item Version objects and vstrings =item Warnings, redefinition =item Warnings, "Uninitialized" =item Weak references =item Other notable fixes =back =item Known Problems =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5160delta - what is new for perl v5.16.0 =over 4 =item DESCRIPTION =item Notice =item Core Enhancements =over 4 =item C<use I<VERSION>> =item C<__SUB__> =item New and Improved Built-ins =item Unicode Support =item XS Changes =item Changes to Special Variables =item Debugger Changes =item The C<CORE> Namespace =item Other Changes =back =item Security =over 4 =item Use C<is_utf8_char_buf()> and not C<is_utf8_char()> =item Malformed UTF-8 input could cause attempts to read beyond the end of the buffer =item C<File::Glob::bsd_glob()> memory error with GLOB_ALTDIRFUNC (CVE-2011-2728). =item Privileges are now set correctly when assigning to C<$(> =back =item Deprecations =over 4 =item Don't read the Unicode data base files in F<lib/unicore> =item XS functions C<is_utf8_char()>, C<utf8_to_uvchr()> and C<utf8_to_uvuni()> =back =item Future Deprecations =over 4 =item Core Modules =item Platforms with no supporting programmers: =item Other Future Deprecations =back =item Incompatible Changes =over 4 =item Special blocks called in void context =item The C<overloading> pragma and regexp objects =item Two XS typemap Entries removed =item Unicode 6.1 has incompatibilities with Unicode 6.0 =item Borland compiler =item Certain deprecated Unicode properties are no longer supported by default =item Dereferencing IO thingies as typeglobs =item User-defined case-changing operations =item XSUBs are now 'static' =item Weakening read-only references =item Tying scalars that hold typeglobs =item IPC::Open3 no longer provides C<xfork()>, C<xclose_on_exec()> and C<xpipe_anon()> =item C<$$> no longer caches PID =item C<$$> and C<getppid()> no longer emulate POSIX semantics under LinuxThreads =item C<< $< >>, C<< $> >>, C<$(> and C<$)> are no longer cached =item Which Non-ASCII characters get quoted by C<quotemeta> and C<\Q> has changed =back =item Performance Enhancements =item Modules and Pragmata =over 4 =item Deprecated Modules L<Version::Requirements> =item New Modules and Pragmata =item Updated Modules and Pragmata =item Removed Modules and Pragmata =back =item Documentation =over 4 =item New Documentation =item Changes to Existing Documentation =item Removed Documentation =back =item Diagnostics =over 4 =item New Diagnostics =item Removed Errors =item Changes to Existing Diagnostics =back =item Utility Changes =item Configuration and Compilation =item Platform Support =over 4 =item Platform-Specific Notes =back =item Internal Changes =item Selected Bug Fixes =over 4 =item Array and hash =item C API fixes =item Compile-time hints =item Copy-on-write scalars =item The debugger =item Dereferencing operators =item Filehandle, last-accessed =item Filetests and C<stat> =item Formats =item C<given> and C<when> =item The C<glob> operator =item Lvalue subroutines =item Overloading =item Prototypes of built-in keywords =item Regular expressions =item Smartmatching =item The C<sort> operator =item The C<substr> operator =item Support for embedded nulls =item Threading bugs =item Tied variables =item Version objects and vstrings =item Warnings, redefinition =item Warnings, "Uninitialized" =item Weak references =item Other notable fixes =back =item Known Problems =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5143delta - what is new for perl v5.14.3 =over 4 =item DESCRIPTION =item Core Enhancements =item Security =over 4 =item C<Digest> unsafe use of eval (CVE-2011-3597) =item Heap buffer overrun in 'x' string repeat operator (CVE-2012-5195) =back =item Incompatible Changes =item Deprecations =item Modules and Pragmata =over 4 =item New Modules and Pragmata =item Updated Modules and Pragmata =item Removed Modules and Pragmata =back =item Documentation =over 4 =item New Documentation =item Changes to Existing Documentation =back =item Configuration and Compilation =item Platform Support =over 4 =item New Platforms =item Discontinued Platforms =item Platform-Specific Notes FreeBSD, Solaris and NetBSD, HP-UX, Linux, Mac OS X, GNU/Hurd, NetBSD =back =item Bug Fixes =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5142delta - what is new for perl v5.14.2 =over 4 =item DESCRIPTION =item Core Enhancements =item Security =over 4 =item C<File::Glob::bsd_glob()> memory error with GLOB_ALTDIRFUNC (CVE-2011-2728). =item C<Encode> decode_xs n-byte heap-overflow (CVE-2011-2939) =back =item Incompatible Changes =item Deprecations =item Modules and Pragmata =over 4 =item New Modules and Pragmata =item Updated Modules and Pragmata =item Removed Modules and Pragmata =back =item Platform Support =over 4 =item New Platforms =item Discontinued Platforms =item Platform-Specific Notes HP-UX PA-RISC/64 now supports gcc-4.x, Building on OS X 10.7 Lion and Xcode 4 works again =back =item Bug Fixes =item Known Problems =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5141delta - what is new for perl v5.14.1 =over 4 =item DESCRIPTION =item Core Enhancements =item Security =item Incompatible Changes =item Deprecations =item Modules and Pragmata =over 4 =item New Modules and Pragmata =item Updated Modules and Pragmata =item Removed Modules and Pragmata =back =item Documentation =over 4 =item New Documentation =item Changes to Existing Documentation =back =item Diagnostics =over 4 =item New Diagnostics =item Changes to Existing Diagnostics =back =item Utility Changes =item Configuration and Compilation =item Testing =item Platform Support =over 4 =item New Platforms =item Discontinued Platforms =item Platform-Specific Notes =back =item Internal Changes =item Bug Fixes =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5140delta - what is new for perl v5.14.0 =over 4 =item DESCRIPTION =item Notice =item Core Enhancements =over 4 =item Unicode =item Regular Expressions =item Syntactical Enhancements =item Exception Handling =item Other Enhancements C<-d:-foo>, C<-d:-foo=bar> =item New C APIs =back =item Security =over 4 =item User-defined regular expression properties =back =item Incompatible Changes =over 4 =item Regular Expressions and String Escapes =item Stashes and Package Variables =item Changes to Syntax or to Perl Operators =item Threads and Processes =item Configuration =back =item Deprecations =over 4 =item Omitting a space between a regular expression and subsequent word =item C<\cI<X>> =item C<"\b{"> and C<"\B{"> =item Perl 4-era .pl libraries =item List assignment to C<$[> =item Use of qw(...) as parentheses =item C<\N{BELL}> =item C<?PATTERN?> =item Tie functions on scalars holding typeglobs =item User-defined case-mapping =item Deprecated modules L<Devel::DProf> =back =item Performance Enhancements =over 4 =item "Safe signals" optimisation =item Optimisation of shift() and pop() calls without arguments =item Optimisation of regexp engine string comparison work =item Regular expression compilation speed-up =item String appending is 100 times faster =item Eliminate C<PL_*> accessor functions under ithreads =item Freeing weak references =item Lexical array and hash assignments =item C<@_> uses less memory =item Size optimisations to SV and HV structures =item Memory consumption improvements to Exporter =item Memory savings for weak references =item C<%+> and C<%-> use less memory =item Multiple small improvements to threads =item Adjacent pairs of nextstate opcodes are now optimized away =back =item Modules and Pragmata =over 4 =item New Modules and Pragmata =item Updated Modules and Pragma much less configuration dialog hassle, support for F<META/MYMETA.json>, support for L<local::lib>, support for L<HTTP::Tiny> to reduce the dependency on FTP sites, automatic mirror selection, iron out all known bugs in configure_requires, support for distributions compressed with L<bzip2(1)>, allow F<Foo/Bar.pm> on the command line to mean C<Foo::Bar>, charinfo(), charscript(), charblock() =item Removed Modules and Pragmata =back =item Documentation =over 4 =item New Documentation =item Changes to Existing Documentation =back =item Diagnostics =over 4 =item New Diagnostics Closure prototype called, Insecure user-defined property %s, panic: gp_free failed to free glob pointer - something is repeatedly re-creating entries, Parsing code internal error (%s), refcnt: fd %d%s, Regexp modifier "/%c" may not appear twice, Regexp modifiers "/%c" and "/%c" are mutually exclusive, Using !~ with %s doesn't make sense, "\b{" is deprecated; use "\b\{" instead, "\B{" is deprecated; use "\B\{" instead, Operation "%s" returns its argument for .., Use of qw(...) as parentheses is deprecated =item Changes to Existing Diagnostics =back =item Utility Changes =item Configuration and Compilation =item Platform Support =over 4 =item New Platforms AIX =item Discontinued Platforms Apollo DomainOS, MacOS Classic =item Platform-Specific Notes =back =item Internal Changes =over 4 =item New APIs =item C API Changes =item Deprecated C APIs C<Perl_ptr_table_clear>, C<sv_compile_2op>, C<find_rundefsvoffset>, C<CALL_FPTR> and C<CPERLscope> =item Other Internal Changes =back =item Selected Bug Fixes =over 4 =item I/O =item Regular Expression Bug Fixes =item Syntax/Parsing Bugs =item Stashes, Globs and Method Lookup Aliasing packages by assigning to globs [perl #77358], Deleting packages by deleting their containing stash elements, Undefining the glob containing a package (C<undef *Foo::>), Undefining an ISA glob (C<undef *Foo::ISA>), Deleting an ISA stash element (C<delete $Foo::{ISA}>), Sharing @ISA arrays between classes (via C<*Foo::ISA = \@Bar::ISA> or C<*Foo::ISA = *Bar::ISA>) [perl #77238] =item Unicode =item Ties, Overloading and Other Magic =item The Debugger =item Threads =item Scoping and Subroutines =item Signals =item Miscellaneous Memory Leaks =item Memory Corruption and Crashes =item Fixes to Various Perl Operators =item Bugs Relating to the C API =back =item Known Problems =item Errata =over 4 =item keys(), values(), and each() work on arrays =item split() and C<@_> =back =item Obituary =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5124delta - what is new for perl v5.12.4 =over 4 =item DESCRIPTION =item Incompatible Changes =item Selected Bug Fixes =item Modules and Pragmata =item Testing =item Documentation =item Platform Specific Notes Linux =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5123delta - what is new for perl v5.12.3 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =over 4 =item C<keys>, C<values> work on arrays =back =item Bug Fixes =item Platform Specific Notes Solaris, VMS, VOS =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5122delta - what is new for perl v5.12.2 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =item Modules and Pragmata =over 4 =item New Modules and Pragmata =item Pragmata Changes =item Updated Modules C<Carp>, C<CPANPLUS>, C<File::Glob>, C<File::Copy>, C<File::Spec> =back =item Utility Changes =item Changes to Existing Documentation =item Installation and Configuration Improvements =over 4 =item Configuration improvements =item Compilation improvements =back =item Selected Bug Fixes =item Platform Specific Notes =over 4 =item AIX =item Windows =item VMS =back =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5121delta - what is new for perl v5.12.1 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =item Modules and Pragmata =over 4 =item Pragmata Changes =item Updated Modules =back =item Changes to Existing Documentation =item Testing =over 4 =item Testing Improvements =back =item Installation and Configuration Improvements =over 4 =item Configuration improvements =back =item Bug Fixes =item Platform Specific Notes =over 4 =item HP-UX =item AIX =item FreeBSD 7 =item VMS =back =item Known Problems =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5120delta - what is new for perl v5.12.0 =over 4 =item DESCRIPTION =item Core Enhancements =over 4 =item New C<package NAME VERSION> syntax =item The C<...> operator =item Implicit strictures =item Unicode improvements =item Y2038 compliance =item qr overloading =item Pluggable keywords =item APIs for more internals =item Overridable function lookup =item A proper interface for pluggable Method Resolution Orders =item C<\N> experimental regex escape =item DTrace support =item Support for C<configure_requires> in CPAN module metadata =item C<each>, C<keys>, C<values> are now more flexible =item C<when> as a statement modifier =item C<$,> flexibility =item // in when clauses =item Enabling warnings from your shell environment =item C<delete local> =item New support for Abstract namespace sockets =item 32-bit limit on substr arguments removed =back =item Potentially Incompatible Changes =over 4 =item Deprecations warn by default =item Version number formats =item @INC reorganization =item REGEXPs are now first class =item Switch statement changes flip-flop operators, defined-or operator =item Smart match changes =item Other potentially incompatible changes =back =item Deprecations suidperl, Use of C<:=> to mean an empty attribute list, C<< UNIVERSAL->import() >>, Use of "goto" to jump into a construct, Custom character names in \N{name} that don't look like names, Deprecated Modules, L<Class::ISA>, L<Pod::Plainer>, L<Shell>, L<Switch>, Assignment to $[, Use of the attribute :locked on subroutines, Use of "locked" with the attributes pragma, Use of "unique" with the attributes pragma, Perl_pmflag, Numerous Perl 4-era libraries =item Unicode overhaul =item Modules and Pragmata =over 4 =item New Modules and Pragmata C<autodie>, C<Compress::Raw::Bzip2>, C<overloading>, C<parent>, C<Parse::CPAN::Meta>, C<VMS::DCLsym>, C<VMS::Stdio>, C<XS::APItest::KeywordRPN> =item Updated Pragmata C<base>, C<bignum>, C<charnames>, C<constant>, C<diagnostics>, C<feature>, C<less>, C<lib>, C<mro>, C<overload>, C<threads>, C<threads::shared>, C<version>, C<warnings> =item Updated Modules C<Archive::Extract>, C<Archive::Tar>, C<Attribute::Handlers>, C<AutoLoader>, C<B::Concise>, C<B::Debug>, C<B::Deparse>, C<B::Lint>, C<CGI>, C<Class::ISA>, C<Compress::Raw::Zlib>, C<CPAN>, C<CPANPLUS>, C<CPANPLUS::Dist::Build>, C<Data::Dumper>, C<DB_File>, C<Devel::PPPort>, C<Digest>, C<Digest::MD5>, C<Digest::SHA>, C<Encode>, C<Exporter>, C<ExtUtils::CBuilder>, C<ExtUtils::Command>, C<ExtUtils::Constant>, C<ExtUtils::Install>, C<ExtUtils::MakeMaker>, C<ExtUtils::Manifest>, C<ExtUtils::ParseXS>, C<File::Fetch>, C<File::Path>, C<File::Temp>, C<Filter::Simple>, C<Filter::Util::Call>, C<Getopt::Long>, C<IO>, C<IO::Zlib>, C<IPC::Cmd>, C<IPC::SysV>, C<Locale::Maketext>, C<Locale::Maketext::Simple>, C<Log::Message>, C<Log::Message::Simple>, C<Math::BigInt>, C<Math::BigInt::FastCalc>, C<Math::BigRat>, C<Math::Complex>, C<Memoize>, C<MIME::Base64>, C<Module::Build>, C<Module::CoreList>, C<Module::Load>, C<Module::Load::Conditional>, C<Module::Loaded>, C<Module::Pluggable>, C<Net::Ping>, C<NEXT>, C<Object::Accessor>, C<Package::Constants>, C<PerlIO>, C<Pod::Parser>, C<Pod::Perldoc>, C<Pod::Plainer>, C<Pod::Simple>, C<Safe>, C<SelfLoader>, C<Storable>, C<Switch>, C<Sys::Syslog>, C<Term::ANSIColor>, C<Term::UI>, C<Test>, C<Test::Harness>, C<Test::Simple>, C<Text::Balanced>, C<Text::ParseWords>, C<Text::Soundex>, C<Thread::Queue>, C<Thread::Semaphore>, C<Tie::RefHash>, C<Time::HiRes>, C<Time::Local>, C<Time::Piece>, C<Unicode::Collate>, C<Unicode::Normalize>, C<Win32>, C<Win32API::File>, C<XSLoader> =item Removed Modules and Pragmata C<attrs>, C<CPAN::API::HOWTO>, C<CPAN::DeferedCode>, C<CPANPLUS::inc>, C<DCLsym>, C<ExtUtils::MakeMaker::bytes>, C<ExtUtils::MakeMaker::vmsish>, C<Stdio>, C<Test::Harness::Assert>, C<Test::Harness::Iterator>, C<Test::Harness::Point>, C<Test::Harness::Results>, C<Test::Harness::Straps>, C<Test::Harness::Util>, C<XSSymSet> =item Deprecated Modules and Pragmata =back =item Documentation =over 4 =item New Documentation =item Changes to Existing Documentation =back =item Selected Performance Enhancements =item Installation and Configuration Improvements =item Internal Changes =item Testing =over 4 =item Testing improvements Parallel tests, Test harness flexibility, Test watchdog =item New Tests =back =item New or Changed Diagnostics =over 4 =item New Diagnostics =item Changed Diagnostics C<Illegal character in prototype for %s : %s>, C<Prototype after '%c' for %s : %s> =back =item Utility Changes =item Selected Bug Fixes =item Platform Specific Changes =over 4 =item New Platforms Haiku, MirOS BSD =item Discontinued Platforms Domain/OS, MiNT, Tenon MachTen =item Updated Platforms AIX, Cygwin, Darwin (Mac OS X), DragonFly BSD, FreeBSD, Irix, NetBSD, OpenVMS, Stratus VOS, Symbian, Windows =back =item Known Problems =item Errata =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5101delta - what is new for perl v5.10.1 =over 4 =item DESCRIPTION =item Incompatible Changes =over 4 =item Switch statement changes flip-flop operators, defined-or operator =item Smart match changes =item Other incompatible changes =back =item Core Enhancements =over 4 =item Unicode Character Database 5.1.0 =item A proper interface for pluggable Method Resolution Orders =item The C<overloading> pragma =item Parallel tests =item DTrace support =item Support for C<configure_requires> in CPAN module metadata =back =item Modules and Pragmata =over 4 =item New Modules and Pragmata C<autodie>, C<Compress::Raw::Bzip2>, C<parent>, C<Parse::CPAN::Meta> =item Pragmata Changes C<attributes>, C<attrs>, C<base>, C<bigint>, C<bignum>, C<bigrat>, C<charnames>, C<constant>, C<feature>, C<fields>, C<lib>, C<open>, C<overload>, C<overloading>, C<version> =item Updated Modules C<Archive::Extract>, C<Archive::Tar>, C<Attribute::Handlers>, C<AutoLoader>, C<AutoSplit>, C<B>, C<B::Debug>, C<B::Deparse>, C<B::Lint>, C<B::Xref>, C<Benchmark>, C<Carp>, C<CGI>, C<Compress::Zlib>, C<CPAN>, C<CPANPLUS>, C<CPANPLUS::Dist::Build>, C<Cwd>, C<Data::Dumper>, C<DB>, C<DB_File>, C<Devel::PPPort>, C<Digest::MD5>, C<Digest::SHA>, C<DirHandle>, C<Dumpvalue>, C<DynaLoader>, C<Encode>, C<Errno>, C<Exporter>, C<ExtUtils::CBuilder>, C<ExtUtils::Command>, C<ExtUtils::Constant>, C<ExtUtils::Embed>, C<ExtUtils::Install>, C<ExtUtils::MakeMaker>, C<ExtUtils::Manifest>, C<ExtUtils::ParseXS>, C<Fatal>, C<File::Basename>, C<File::Compare>, C<File::Copy>, C<File::Fetch>, C<File::Find>, C<File::Path>, C<File::Spec>, C<File::stat>, C<File::Temp>, C<FileCache>, C<FileHandle>, C<Filter::Simple>, C<Filter::Util::Call>, C<FindBin>, C<GDBM_File>, C<Getopt::Long>, C<Hash::Util::FieldHash>, C<I18N::Collate>, C<IO>, C<IO::Compress::*>, C<IO::Dir>, C<IO::Handle>, C<IO::Socket>, C<IO::Zlib>, C<IPC::Cmd>, C<IPC::Open3>, C<IPC::SysV>, C<lib>, C<List::Util>, C<Locale::MakeText>, C<Log::Message>, C<Math::BigFloat>, C<Math::BigInt>, C<Math::BigInt::FastCalc>, C<Math::BigRat>, C<Math::Complex>, C<Math::Trig>, C<Memoize>, C<Module::Build>, C<Module::CoreList>, C<Module::Load>, C<Module::Load::Conditional>, C<Module::Loaded>, C<Module::Pluggable>, C<NDBM_File>, C<Net::Ping>, C<NEXT>, C<Object::Accessor>, C<OS2::REXX>, C<Package::Constants>, C<PerlIO>, C<PerlIO::via>, C<Pod::Man>, C<Pod::Parser>, C<Pod::Simple>, C<Pod::Text>, C<POSIX>, C<Safe>, C<Scalar::Util>, C<SelectSaver>, C<SelfLoader>, C<Socket>, C<Storable>, C<Switch>, C<Symbol>, C<Sys::Syslog>, C<Term::ANSIColor>, C<Term::ReadLine>, C<Term::UI>, C<Test::Harness>, C<Test::Simple>, C<Text::ParseWords>, C<Text::Tabs>, C<Text::Wrap>, C<Thread::Queue>, C<Thread::Semaphore>, C<threads>, C<threads::shared>, C<Tie::RefHash>, C<Tie::StdHandle>, C<Time::HiRes>, C<Time::Local>, C<Time::Piece>, C<Unicode::Normalize>, C<Unicode::UCD>, C<UNIVERSAL>, C<Win32>, C<Win32API::File>, C<XSLoader> =back =item Utility Changes F<h2ph>, F<h2xs>, F<perl5db.pl>, F<perlthanks> =item New Documentation L<perlhaiku>, L<perlmroapi>, L<perlperf>, L<perlrepository>, L<perlthanks> =item Changes to Existing Documentation =item Performance Enhancements =item Installation and Configuration Improvements =over 4 =item F<ext/> reorganisation =item Configuration improvements =item Compilation improvements =item Platform Specific Changes AIX, Cygwin, FreeBSD, Irix, Haiku, MirOS BSD, NetBSD, Stratus VOS, Symbian, Win32, VMS =back =item Selected Bug Fixes =item New or Changed Diagnostics C<panic: sv_chop %s>, C<Can't locate package %s for the parents of %s>, C<v-string in use/require is non-portable>, C<Deep recursion on subroutine "%s"> =item Changed Internals C<SVf_UTF8>, C<SVs_TEMP> =item New Tests t/comp/retainedlines.t, t/io/perlio_fail.t, t/io/perlio_leaks.t, t/io/perlio_open.t, t/io/perlio.t, t/io/pvbm.t, t/mro/package_aliases.t, t/op/dbm.t, t/op/index_thr.t, t/op/pat_thr.t, t/op/qr_gc.t, t/op/reg_email_thr.t, t/op/regexp_qr_embed_thr.t, t/op/regexp_unicode_prop.t, t/op/regexp_unicode_prop_thr.t, t/op/reg_nc_tie.t, t/op/reg_posixcc.t, t/op/re.t, t/op/setpgrpstack.t, t/op/substr_thr.t, t/op/upgrade.t, t/uni/lex_utf8.t, t/uni/tie.t =item Known Problems =item Deprecations =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl5100delta - what is new for perl 5.10.0 =over 4 =item DESCRIPTION =item Core Enhancements =over 4 =item The C<feature> pragma =item New B<-E> command-line switch =item Defined-or operator =item Switch and Smart Match operator =item Regular expressions Recursive Patterns, Named Capture Buffers, Possessive Quantifiers, Backtracking control verbs, Relative backreferences, C<\K> escape, Vertical and horizontal whitespace, and linebreak =item C<say()> =item Lexical C<$_> =item The C<_> prototype =item UNITCHECK blocks =item New Pragma, C<mro> =item readdir() may return a "short filename" on Windows =item readpipe() is now overridable =item Default argument for readline() =item state() variables =item Stacked filetest operators =item UNIVERSAL::DOES() =item Formats =item Byte-order modifiers for pack() and unpack() =item C<no VERSION> =item C<chdir>, C<chmod> and C<chown> on filehandles =item OS groups =item Recursive sort subs =item Exceptions in constant folding =item Source filters in @INC =item New internal variables C<${^RE_DEBUG_FLAGS}>, C<${^CHILD_ERROR_NATIVE}>, C<${^RE_TRIE_MAXBUF}>, C<${^WIN32_SLOPPY_STAT}> =item Miscellaneous =item UCD 5.0.0 =item MAD =item kill() on Windows =back =item Incompatible Changes =over 4 =item Packing and UTF-8 strings =item Byte/character count feature in unpack() =item The C<$*> and C<$#> variables have been removed =item substr() lvalues are no longer fixed-length =item Parsing of C<-f _> =item C<:unique> =item Effect of pragmas in eval =item chdir FOO =item Handling of .pmc files =item $^V is now a C<version> object instead of a v-string =item @- and @+ in patterns =item $AUTOLOAD can now be tainted =item Tainting and printf =item undef and signal handlers =item strictures and dereferencing in defined() =item C<(?p{})> has been removed =item Pseudo-hashes have been removed =item Removal of the bytecode compiler and of perlcc =item Removal of the JPL =item Recursive inheritance detected earlier =item warnings::enabled and warnings::warnif changed to favor users of modules =back =item Modules and Pragmata =over 4 =item Upgrading individual core modules =item Pragmata Changes C<feature>, C<mro>, Scoping of the C<sort> pragma, Scoping of C<bignum>, C<bigint>, C<bigrat>, C<base>, C<strict> and C<warnings>, C<version>, C<warnings>, C<less> =item New modules =item Selected Changes to Core Modules C<Attribute::Handlers>, C<B::Lint>, C<B>, C<Thread> =back =item Utility Changes perl -d, ptar, ptardiff, shasum, corelist, h2ph and h2xs, perlivp, find2perl, config_data, cpanp, cpan2dist, pod2html =item New Documentation =item Performance Enhancements =over 4 =item In-place sorting =item Lexical array access =item XS-assisted SWASHGET =item Constant subroutines =item C<PERL_DONT_CREATE_GVSV> =item Weak references are cheaper =item sort() enhancements =item Memory optimisations =item UTF-8 cache optimisation =item Sloppy stat on Windows =item Regular expressions optimisations Engine de-recursivised, Single char char-classes treated as literals, Trie optimisation of literal string alternations, Aho-Corasick start-point optimisation =back =item Installation and Configuration Improvements =over 4 =item Configuration improvements C<-Dusesitecustomize>, Relocatable installations, strlcat() and strlcpy(), C<d_pseudofork> and C<d_printf_format_null>, Configure help =item Compilation improvements Parallel build, Borland's compilers support, Static build on Windows, ppport.h files, C++ compatibility, Support for Microsoft 64-bit compiler, Visual C++, Win32 builds =item Installation improvements Module auxiliary files =item New Or Improved Platforms =back =item Selected Bug Fixes strictures in regexp-eval blocks, Calling CORE::require(), Subscripts of slices, C<no warnings 'category'> works correctly with -w, threads improvements, chr() and negative values, PERL5SHELL and tainting, Using *FILE{IO}, Overloading and reblessing, Overloading and UTF-8, eval memory leaks fixed, Random device on Windows, PERLIO_DEBUG, PerlIO::scalar and read-only scalars, study() and UTF-8, Critical signals, @INC-hook fix, C<-t> switch fix, Duping UTF-8 filehandles, Localisation of hash elements =item New or Changed Diagnostics Use of uninitialized value, Deprecated use of my() in false conditional, !=~ should be !~, Newline in left-justified string, Too late for "-T" option, "%s" variable %s masks earlier declaration, readdir()/closedir()/etc. attempted on invalid dirhandle, Opening dirhandle/filehandle %s also as a file/directory, Use of -P is deprecated, v-string in use/require is non-portable, perl -V =item Changed Internals =over 4 =item Reordering of SVt_* constants =item Elimination of SVt_PVBM =item New type SVt_BIND =item Removal of CPP symbols =item Less space is used by ops =item New parser =item Use of C<const> =item Mathoms =item C<AvFLAGS> has been removed =item C<av_*> changes =item $^H and %^H =item B:: modules inheritance changed =item Anonymous hash and array constructors =back =item Known Problems =over 4 =item UTF-8 problems =back =item Platform Specific Problems =item Reporting Bugs =item SEE ALSO =back =head2 perl589delta - what is new for perl v5.8.9 =over 4 =item DESCRIPTION =item Notice =item Incompatible Changes =item Core Enhancements =over 4 =item Unicode Character Database 5.1.0. =item stat and -X on directory handles =item Source filters in @INC =item Exceptions in constant folding =item C<no VERSION> =item Improved internal UTF-8 caching code =item Runtime relocatable installations =item New internal variables C<${^CHILD_ERROR_NATIVE}>, C<${^UTF8CACHE}> =item C<readpipe> is now overridable =item simple exception handling macros =item -D option enhancements =item XS-assisted SWASHGET =item Constant subroutines =back =item New Platforms =item Modules and Pragmata =over 4 =item New Modules =item Updated Modules =back =item Utility Changes =over 4 =item debugger upgraded to version 1.31 =item F<perlthanks> =item F<perlbug> =item F<h2xs> =item F<h2ph> =back =item New Documentation =item Changes to Existing Documentation =item Performance Enhancements =item Installation and Configuration Improvements =over 4 =item Relocatable installations =item Configuration improvements =item Compilation improvements =item Installation improvements. =item Platform Specific Changes =back =item Selected Bug Fixes =over 4 =item Unicode =item PerlIO =item Magic =item Reblessing overloaded objects now works =item C<strict> now propagates correctly into string evals =item Other fixes =item Platform Specific Fixes =item Smaller fixes =back =item New or Changed Diagnostics =over 4 =item panic: sv_chop %s =item Maximal count of pending signals (%s) exceeded =item panic: attempt to call %s in %s =item FETCHSIZE returned a negative value =item Can't upgrade %s (%d) to %d =item %s argument is not a HASH or ARRAY element or a subroutine =item Cannot make the non-overridable builtin %s fatal =item Unrecognized character '%s' in column %d =item Offset outside string =item Invalid escape in the specified encoding in regexp; marked by <-- HERE in m/%s/ =item Your machine doesn't support dump/undump. =back =item Changed Internals =over 4 =item Macro cleanups =back =item New Tests ext/DynaLoader/t/DynaLoader.t, t/comp/fold.t, t/io/pvbm.t, t/lib/proxy_constant_subs.t, t/op/attrhand.t, t/op/dbm.t, t/op/inccode-tie.t, t/op/incfilter.t, t/op/kill0.t, t/op/qrstack.t, t/op/qr.t, t/op/regexp_qr_embed.t, t/op/regexp_qr.t, t/op/rxcode.t, t/op/studytied.t, t/op/substT.t, t/op/symbolcache.t, t/op/upgrade.t, t/mro/package_aliases.t, t/pod/twice.t, t/run/cloexec.t, t/uni/cache.t, t/uni/chr.t, t/uni/greek.t, t/uni/latin2.t, t/uni/overload.t, t/uni/tie.t =item Known Problems =item Platform Specific Notes =over 4 =item Win32 =item OS/2 =item VMS =back =item Obituary =item Acknowledgements =item Reporting Bugs =item SEE ALSO =back =head2 perl588delta - what is new for perl v5.8.8 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =item Modules and Pragmata =item Utility Changes =over 4 =item C<h2xs> enhancements =item C<perlivp> enhancements =back =item New Documentation =item Performance Enhancements =item Installation and Configuration Improvements =item Selected Bug Fixes =over 4 =item no warnings 'category' works correctly with -w =item Remove over-optimisation =item sprintf() fixes =item Debugger and Unicode slowdown =item Smaller fixes =back =item New or Changed Diagnostics =over 4 =item Attempt to set length of freed array =item Non-string passed as bitmask =item Search pattern not terminated or ternary operator parsed as search pattern =back =item Changed Internals =item Platform Specific Problems =item Reporting Bugs =item SEE ALSO =back =head2 perl587delta - what is new for perl v5.8.7 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =over 4 =item Unicode Character Database 4.1.0 =item suidperl less insecure =item Optional site customization script =item C<Config.pm> is now much smaller. =back =item Modules and Pragmata =item Utility Changes =over 4 =item find2perl enhancements =back =item Performance Enhancements =item Installation and Configuration Improvements =item Selected Bug Fixes =item New or Changed Diagnostics =item Changed Internals =item Known Problems =item Platform Specific Problems =item Reporting Bugs =item SEE ALSO =back =head2 perl586delta - what is new for perl v5.8.6 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =item Modules and Pragmata =item Utility Changes =item Performance Enhancements =item Selected Bug Fixes =item New or Changed Diagnostics =item Changed Internals =item New Tests =item Reporting Bugs =item SEE ALSO =back =head2 perl585delta - what is new for perl v5.8.5 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =item Modules and Pragmata =item Utility Changes =over 4 =item Perl's debugger =item h2ph =back =item Installation and Configuration Improvements =item Selected Bug Fixes =item New or Changed Diagnostics =item Changed Internals =item Known Problems =item Platform Specific Problems =item Reporting Bugs =item SEE ALSO =back =head2 perl584delta - what is new for perl v5.8.4 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =over 4 =item Malloc wrapping =item Unicode Character Database 4.0.1 =item suidperl less insecure =item format =back =item Modules and Pragmata =over 4 =item Updated modules Attribute::Handlers, B, Benchmark, CGI, Carp, Cwd, Exporter, File::Find, IO, IPC::Open3, Local::Maketext, Math::BigFloat, Math::BigInt, Math::BigRat, MIME::Base64, ODBM_File, POSIX, Shell, Socket, Storable, Switch, Sys::Syslog, Term::ANSIColor, Time::HiRes, Unicode::UCD, Win32, base, open, threads, utf8 =back =item Performance Enhancements =item Utility Changes =item Installation and Configuration Improvements =item Selected Bug Fixes =item New or Changed Diagnostics =item Changed Internals =item Future Directions =item Platform Specific Problems =item Reporting Bugs =item SEE ALSO =back =head2 perl583delta - what is new for perl v5.8.3 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =item Modules and Pragmata CGI, Cwd, Digest, Digest::MD5, Encode, File::Spec, FindBin, List::Util, Math::BigInt, PodParser, Pod::Perldoc, POSIX, Unicode::Collate, Unicode::Normalize, Test::Harness, threads::shared =item Utility Changes =item New Documentation =item Installation and Configuration Improvements =item Selected Bug Fixes =item New or Changed Diagnostics =item Changed Internals =item Configuration and Building =item Platform Specific Problems =item Known Problems =item Future Directions =item Obituary =item Reporting Bugs =item SEE ALSO =back =head2 perl582delta - what is new for perl v5.8.2 =over 4 =item DESCRIPTION =item Incompatible Changes =item Core Enhancements =over 4 =item Hash Randomisation =item Threading =back =item Modules and Pragmata =over 4 =item Updated Modules And Pragmata Devel::PPPort, Digest::MD5, I18N::LangTags, libnet, MIME::Base64, Pod::Perldoc, strict, Tie::Hash, Time::HiRes, Unicode::Collate, Unicode::Normalize, UNIVERSAL =back =item Selected Bug Fixes =item Changed Internals =item Platform Specific Problems =item Future Directions =item Reporting Bugs =item SEE ALSO =back =head2 perl581delta - what is new for perl v5.8.1 =over 4 =item DESCRIPTION =item Incompatible Changes =over 4 =item Hash Randomisation =item UTF-8 On Filehandles No Longer Activated By Locale =item Single-number v-strings are no longer v-strings before "=>" =item (Win32) The -C Switch Has Been Repurposed =item (Win32) The /d Switch Of cmd.exe =back =item Core Enhancements =over 4 =item UTF-8 no longer default under UTF-8 locales =item Unsafe signals again available =item Tied Arrays with Negative Array Indices =item local ${$x} =item Unicode Character Database 4.0.0 =item Deprecation Warnings =item Miscellaneous Enhancements =back =item Modules and Pragmata =over 4 =item Updated Modules And Pragmata base, B::Bytecode, B::Concise, B::Deparse, Benchmark, ByteLoader, bytes, CGI, charnames, CPAN, Data::Dumper, DB_File, Devel::PPPort, Digest::MD5, Encode, fields, libnet, Math::BigInt, MIME::Base64, NEXT, Net::Ping, PerlIO::scalar, podlators, Pod::LaTeX, PodParsers, Pod::Perldoc, Scalar::Util, Storable, strict, Term::ANSIcolor, Test::Harness, Test::More, Test::Simple, Text::Balanced, Time::HiRes, threads, threads::shared, Unicode::Collate, Unicode::Normalize, Win32::GetFolderPath, Win32::GetOSVersion =back =item Utility Changes =item New Documentation =item Installation and Configuration Improvements =over 4 =item Platform-specific enhancements =back =item Selected Bug Fixes =over 4 =item Closures, eval and lexicals =item Generic fixes =item Platform-specific fixes =back =item New or Changed Diagnostics =over 4 =item Changed "A thread exited while %d threads were running" =item Removed "Attempt to clear a restricted hash" =item New "Illegal declaration of anonymous subroutine" =item Changed "Invalid range "%s" in transliteration operator" =item New "Missing control char name in \c" =item New "Newline in left-justified string for %s" =item New "Possible precedence problem on bitwise %c operator" =item New "Pseudo-hashes are deprecated" =item New "read() on %s filehandle %s" =item New "5.005 threads are deprecated" =item New "Tied variable freed while still in use" =item New "To%s: illegal mapping '%s'" =item New "Use of freed value in iteration" =back =item Changed Internals =item New Tests =item Known Problems =over 4 =item Tied hashes in scalar context =item Net::Ping 450_service and 510_ping_udp failures =item B::C =back =item Platform Specific Problems =over 4 =item EBCDIC Platforms =item Cygwin 1.5 problems =item HP-UX: HP cc warnings about sendfile and sendpath =item IRIX: t/uni/tr_7jis.t falsely failing =item Mac OS X: no usemymalloc =item Tru64: No threaded builds with GNU cc (gcc) =item Win32: sysopen, sysread, syswrite =back =item Future Directions =item Reporting Bugs =item SEE ALSO =back =head2 perl58delta - what is new for perl v5.8.0 =over 4 =item DESCRIPTION =item Highlights In 5.8.0 =item Incompatible Changes =over 4 =item Binary Incompatibility =item 64-bit platforms and malloc =item AIX Dynaloading =item Attributes for C<my> variables now handled at run-time =item Socket Extension Dynamic in VMS =item IEEE-format Floating Point Default on OpenVMS Alpha =item New Unicode Semantics (no more C<use utf8>, almost) =item New Unicode Properties =item REF(...) Instead Of SCALAR(...) =item pack/unpack D/F recycled =item glob() now returns filenames in alphabetical order =item Deprecations =back =item Core Enhancements =over 4 =item Unicode Overhaul =item PerlIO is Now The Default =item ithreads =item Restricted Hashes =item Safe Signals =item Understanding of Numbers =item Arrays now always interpolate into double-quoted strings [561] =item Miscellaneous Changes =back =item Modules and Pragmata =over 4 =item New Modules and Pragmata =item Updated And Improved Modules and Pragmata =back =item Utility Changes =item New Documentation =item Performance Enhancements =item Installation and Configuration Improvements =over 4 =item Generic Improvements =item New Or Improved Platforms =back =item Selected Bug Fixes =over 4 =item Platform Specific Changes and Fixes =back =item New or Changed Diagnostics =item Changed Internals =item Security Vulnerability Closed [561] =item New Tests =item Known Problems =over 4 =item The Compiler Suite Is Still Very Experimental =item Localising Tied Arrays and Hashes Is Broken =item Building Extensions Can Fail Because Of Largefiles =item Modifying $_ Inside for(..) =item mod_perl 1.26 Doesn't Build With Threaded Perl =item lib/ftmp-security tests warn 'system possibly insecure' =item libwww-perl (LWP) fails base/date #51 =item PDL failing some tests =item Perl_get_sv =item Self-tying Problems =item ext/threads/t/libc =item Failure of Thread (5.005-style) tests =item Timing problems =item Tied/Magical Array/Hash Elements Do Not Autovivify =item Unicode in package/class and subroutine names does not work =back =item Platform Specific Problems =over 4 =item AIX =item Alpha systems with old gccs fail several tests =item AmigaOS =item BeOS =item Cygwin "unable to remap" =item Cygwin ndbm tests fail on FAT =item DJGPP Failures =item FreeBSD built with ithreads coredumps reading large directories =item FreeBSD Failing locale Test 117 For ISO 8859-15 Locales =item IRIX fails ext/List/Util/t/shuffle.t or Digest::MD5 =item HP-UX lib/posix Subtest 9 Fails When LP64-Configured =item Linux with glibc 2.2.5 fails t/op/int subtest #6 with -Duse64bitint =item Linux With Sfio Fails op/misc Test 48 =item Mac OS X =item Mac OS X dyld undefined symbols =item OS/2 Test Failures =item op/sprintf tests 91, 129, and 130 =item SCO =item Solaris 2.5 =item Solaris x86 Fails Tests With -Duse64bitint =item SUPER-UX (NEC SX) =item Term::ReadKey not working on Win32 =item UNICOS/mk =item UTS =item VOS (Stratus) =item VMS =item Win32 =item XML::Parser not working =item z/OS (OS/390) =item Unicode Support on EBCDIC Still Spotty =item Seen In Perl 5.7 But Gone Now =back =item Reporting Bugs =item SEE ALSO =item HISTORY =back =head2 perl561delta - what's new for perl v5.6.1 =over 4 =item DESCRIPTION =item Summary of changes between 5.6.0 and 5.6.1 =over 4 =item Security Issues =item Core bug fixes C<UNIVERSAL::isa()>, Memory leaks, Numeric conversions, qw(a\\b), caller(), Bugs in regular expressions, "slurp" mode, Autovivification of symbolic references to special variables, Lexical warnings, Spurious warnings and errors, glob(), Tainting, sort(), #line directives, Subroutine prototypes, map(), Debugger, PERL5OPT, chop(), Unicode support, 64-bit support, Compiler, Lvalue subroutines, IO::Socket, File::Find, xsubpp, C<no Module;>, Tests =item Core features =item Configuration issues =item Documentation =item Bundled modules B::Concise, File::Temp, Pod::LaTeX, Pod::Text::Overstrike, CGI, CPAN, Class::Struct, DB_File, Devel::Peek, File::Find, Getopt::Long, IO::Poll, IPC::Open3, Math::BigFloat, Math::Complex, Net::Ping, Opcode, Pod::Parser, Pod::Text, SDBM_File, Sys::Syslog, Tie::RefHash, Tie::SubstrHash =item Platform-specific improvements NCR MP-RAS, NonStop-UX =back =item Core Enhancements =over 4 =item Interpreter cloning, threads, and concurrency =item Lexically scoped warning categories =item Unicode and UTF-8 support =item Support for interpolating named characters =item "our" declarations =item Support for strings represented as a vector of ordinals =item Improved Perl version numbering system =item New syntax for declaring subroutine attributes =item File and directory handles can be autovivified =item open() with more than two arguments =item 64-bit support =item Large file support =item Long doubles =item "more bits" =item Enhanced support for sort() subroutines =item C<sort $coderef @foo> allowed =item File globbing implemented internally =item Support for CHECK blocks =item POSIX character class syntax [: :] supported =item Better pseudo-random number generator =item Improved C<qw//> operator =item Better worst-case behavior of hashes =item pack() format 'Z' supported =item pack() format modifier '!' supported =item pack() and unpack() support counted strings =item Comments in pack() templates =item Weak references =item Binary numbers supported =item Lvalue subroutines =item Some arrows may be omitted in calls through references =item Boolean assignment operators are legal lvalues =item exists() is supported on subroutine names =item exists() and delete() are supported on array elements =item Pseudo-hashes work better =item Automatic flushing of output buffers =item Better diagnostics on meaningless filehandle operations =item Where possible, buffered data discarded from duped input filehandle =item eof() has the same old magic as <> =item binmode() can be used to set :crlf and :raw modes =item C<-T> filetest recognizes UTF-8 encoded files as "text" =item system(), backticks and pipe open now reflect exec() failure =item Improved diagnostics =item Diagnostics follow STDERR =item More consistent close-on-exec behavior =item syswrite() ease-of-use =item Better syntax checks on parenthesized unary operators =item Bit operators support full native integer width =item Improved security features =item More functional bareword prototype (*) =item C<require> and C<do> may be overridden =item $^X variables may now have names longer than one character =item New variable $^C reflects C<-c> switch =item New variable $^V contains Perl version as a string =item Optional Y2K warnings =item Arrays now always interpolate into double-quoted strings =item @- and @+ provide starting/ending offsets of regex submatches =back =item Modules and Pragmata =over 4 =item Modules attributes, B, Benchmark, ByteLoader, constant, charnames, Data::Dumper, DB, DB_File, Devel::DProf, Devel::Peek, Dumpvalue, DynaLoader, English, Env, Fcntl, File::Compare, File::Find, File::Glob, File::Spec, File::Spec::Functions, Getopt::Long, IO, JPL, lib, Math::BigInt, Math::Complex, Math::Trig, Pod::Parser, Pod::InputObjects, Pod::Checker, podchecker, Pod::ParseUtils, Pod::Find, Pod::Select, podselect, Pod::Usage, pod2usage, Pod::Text and Pod::Man, SDBM_File, Sys::Syslog, Sys::Hostname, Term::ANSIColor, Time::Local, Win32, XSLoader, DBM Filters =item Pragmata =back =item Utility Changes =over 4 =item dprofpp =item find2perl =item h2xs =item perlcc =item perldoc =item The Perl Debugger =back =item Improved Documentation perlapi.pod, perlboot.pod, perlcompile.pod, perldbmfilter.pod, perldebug.pod, perldebguts.pod, perlfork.pod, perlfilter.pod, perlhack.pod, perlintern.pod, perllexwarn.pod, perlnumber.pod, perlopentut.pod, perlreftut.pod, perltootc.pod, perltodo.pod, perlunicode.pod =item Performance enhancements =over 4 =item Simple sort() using { $a <=> $b } and the like are optimized =item Optimized assignments to lexical variables =item Faster subroutine calls =item delete(), each(), values() and hash iteration are faster =back =item Installation and Configuration Improvements =over 4 =item -Dusethreads means something different =item New Configure flags =item Threadedness and 64-bitness now more daring =item Long Doubles =item -Dusemorebits =item -Duselargefiles =item installusrbinperl =item SOCKS support =item C<-A> flag =item Enhanced Installation Directories =item gcc automatically tried if 'cc' does not seem to be working =back =item Platform specific changes =over 4 =item Supported platforms =item DOS =item OS390 (OpenEdition MVS) =item VMS =item Win32 =back =item Significant bug fixes =over 4 =item <HANDLE> on empty files =item C<eval '...'> improvements =item All compilation errors are true errors =item Implicitly closed filehandles are safer =item Behavior of list slices is more consistent =item C<(\$)> prototype and C<$foo{a}> =item C<goto &sub> and AUTOLOAD =item C<-bareword> allowed under C<use integer> =item Failures in DESTROY() =item Locale bugs fixed =item Memory leaks =item Spurious subroutine stubs after failed subroutine calls =item Taint failures under C<-U> =item END blocks and the C<-c> switch =item Potential to leak DATA filehandles =back =item New or Changed Diagnostics "%s" variable %s masks earlier declaration in same %s, "my sub" not yet implemented, "our" variable %s redeclared, '!' allowed only after types %s, / cannot take a count, / must be followed by a, A or Z, / must be followed by a*, A* or Z*, / must follow a numeric type, /%s/: Unrecognized escape \\%c passed through, /%s/: Unrecognized escape \\%c in character class passed through, /%s/ should probably be written as "%s", %s() called too early to check prototype, %s argument is not a HASH or ARRAY element, %s argument is not a HASH or ARRAY element or slice, %s argument is not a subroutine name, %s package attribute may clash with future reserved word: %s, (in cleanup) %s, <> should be quotes, Attempt to join self, Bad evalled substitution pattern, Bad realloc() ignored, Bareword found in conditional, Binary number > 0b11111111111111111111111111111111 non-portable, Bit vector size > 32 non-portable, Buffer overflow in prime_env_iter: %s, Can't check filesystem of script "%s", Can't declare class for non-scalar %s in "%s", Can't declare %s in "%s", Can't ignore signal CHLD, forcing to default, Can't modify non-lvalue subroutine call, Can't read CRTL environ, Can't remove %s: %s, skipping file, Can't return %s from lvalue subroutine, Can't weaken a nonreference, Character class [:%s:] unknown, Character class syntax [%s] belongs inside character classes, Constant is not %s reference, constant(%s): %s, CORE::%s is not a keyword, defined(@array) is deprecated, defined(%hash) is deprecated, Did not produce a valid header, (Did you mean "local" instead of "our"?), Document contains no data, entering effective %s failed, false [] range "%s" in regexp, Filehandle %s opened only for output, flock() on closed filehandle %s, Global symbol "%s" requires explicit package name, Hexadecimal number > 0xffffffff non-portable, Ill-formed CRTL environ value "%s", Ill-formed message in prime_env_iter: |%s|, Illegal binary digit %s, Illegal binary digit %s ignored, Illegal number of bits in vec, Integer overflow in %s number, Invalid %s attribute: %s, Invalid %s attributes: %s, invalid [] range "%s" in regexp, Invalid separator character %s in attribute list, Invalid separator character %s in subroutine attribute list, leaving effective %s failed, Lvalue subs returning %s not implemented yet, Method %s not permitted, Missing %sbrace%s on \N{}, Missing command in piped open, Missing name in "my sub", No %s specified for -%c, No package name allowed for variable %s in "our", No space allowed after -%c, no UTC offset information; assuming local time is UTC, Octal number > 037777777777 non-portable, panic: del_backref, panic: kid popen errno read, panic: magic_killbackrefs, Parentheses missing around "%s" list, Possible unintended interpolation of %s in string, Possible Y2K bug: %s, pragma "attrs" is deprecated, use "sub NAME : ATTRS" instead, Premature end of script headers, Repeat count in pack overflows, Repeat count in unpack overflows, realloc() of freed memory ignored, Reference is already weak, setpgrp can't take arguments, Strange *+?{} on zero-length expression, switching effective %s is not implemented, This Perl can't reset CRTL environ elements (%s), This Perl can't set CRTL environ elements (%s=%s), Too late to run %s block, Unknown open() mode '%s', Unknown process %x sent message to prime_env_iter: %s, Unrecognized escape \\%c passed through, Unterminated attribute parameter in attribute list, Unterminated attribute list, Unterminated attribute parameter in subroutine attribute list, Unterminated subroutine attribute list, Value of CLI symbol "%s" too long, Version number must be a constant number =item New tests =item Incompatible Changes =over 4 =item Perl Source Incompatibilities CHECK is a new keyword, Treatment of list slices of undef has changed, Format of $English::PERL_VERSION is different, Literals of the form C<1.2.3> parse differently, Possibly changed pseudo-random number generator, Hashing function for hash keys has changed, C<undef> fails on read only values, Close-on-exec bit may be set on pipe and socket handles, Writing C<"$$1"> to mean C<"${$}1"> is unsupported, delete(), each(), values() and C<\(%h)>, vec(EXPR,OFFSET,BITS) enforces powers-of-two BITS, Text of some diagnostic output has changed, C<%@> has been removed, Parenthesized not() behaves like a list operator, Semantics of bareword prototype C<(*)> have changed, Semantics of bit operators may have changed on 64-bit platforms, More builtins taint their results =item C Source Incompatibilities C<PERL_POLLUTE>, C<PERL_IMPLICIT_CONTEXT>, C<PERL_POLLUTE_MALLOC> =item Compatible C Source API Changes C<PATCHLEVEL> is now C<PERL_VERSION> =item Binary Incompatibilities =back =item Known Problems =over 4 =item Localizing a tied hash element may leak memory =item Known test failures =item EBCDIC platforms not fully supported =item UNICOS/mk CC failures during Configure run =item Arrow operator and arrays =item Experimental features Threads, Unicode, 64-bit support, Lvalue subroutines, Weak references, The pseudo-hash data type, The Compiler suite, Internal implementation of file globbing, The DB module, The regular expression code constructs: =back =item Obsolete Diagnostics Character class syntax [: :] is reserved for future extensions, Ill-formed logical name |%s| in prime_env_iter, In string, @%s now must be written as \@%s, Probable precedence problem on %s, regexp too big, Use of "$$<digit>" to mean "${$}<digit>" is deprecated =item Reporting Bugs =item SEE ALSO =item HISTORY =back =head2 perl56delta - what's new for perl v5.6.0 =over 4 =item DESCRIPTION =item Core Enhancements =over 4 =item Interpreter cloning, threads, and concurrency =item Lexically scoped warning categories =item Unicode and UTF-8 support =item Support for interpolating named characters =item "our" declarations =item Support for strings represented as a vector of ordinals =item Improved Perl version numbering system =item New syntax for declaring subroutine attributes =item File and directory handles can be autovivified =item open() with more than two arguments =item 64-bit support =item Large file support =item Long doubles =item "more bits" =item Enhanced support for sort() subroutines =item C<sort $coderef @foo> allowed =item File globbing implemented internally =item Support for CHECK blocks =item POSIX character class syntax [: :] supported =item Better pseudo-random number generator =item Improved C<qw//> operator =item Better worst-case behavior of hashes =item pack() format 'Z' supported =item pack() format modifier '!' supported =item pack() and unpack() support counted strings =item Comments in pack() templates =item Weak references =item Binary numbers supported =item Lvalue subroutines =item Some arrows may be omitted in calls through references =item Boolean assignment operators are legal lvalues =item exists() is supported on subroutine names =item exists() and delete() are supported on array elements =item Pseudo-hashes work better =item Automatic flushing of output buffers =item Better diagnostics on meaningless filehandle operations =item Where possible, buffered data discarded from duped input filehandle =item eof() has the same old magic as <> =item binmode() can be used to set :crlf and :raw modes =item C<-T> filetest recognizes UTF-8 encoded files as "text" =item system(), backticks and pipe open now reflect exec() failure =item Improved diagnostics =item Diagnostics follow STDERR =item More consistent close-on-exec behavior =item syswrite() ease-of-use =item Better syntax checks on parenthesized unary operators =item Bit operators support full native integer width =item Improved security features =item More functional bareword prototype (*) =item C<require> and C<do> may be overridden =item $^X variables may now have names longer than one character =item New variable $^C reflects C<-c> switch =item New variable $^V contains Perl version as a string =item Optional Y2K warnings =item Arrays now always interpolate into double-quoted strings =item @- and @+ provide starting/ending offsets of regex matches =back =item Modules and Pragmata =over 4 =item Modules attributes, B, Benchmark, ByteLoader, constant, charnames, Data::Dumper, DB, DB_File, Devel::DProf, Devel::Peek, Dumpvalue, DynaLoader, English, Env, Fcntl, File::Compare, File::Find, File::Glob, File::Spec, File::Spec::Functions, Getopt::Long, IO, JPL, lib, Math::BigInt, Math::Complex, Math::Trig, Pod::Parser, Pod::InputObjects, Pod::Checker, podchecker, Pod::ParseUtils, Pod::Find, Pod::Select, podselect, Pod::Usage, pod2usage, Pod::Text and Pod::Man, SDBM_File, Sys::Syslog, Sys::Hostname, Term::ANSIColor, Time::Local, Win32, XSLoader, DBM Filters =item Pragmata =back =item Utility Changes =over 4 =item dprofpp =item find2perl =item h2xs =item perlcc =item perldoc =item The Perl Debugger =back =item Improved Documentation perlapi.pod, perlboot.pod, perlcompile.pod, perldbmfilter.pod, perldebug.pod, perldebguts.pod, perlfork.pod, perlfilter.pod, perlhack.pod, perlintern.pod, perllexwarn.pod, perlnumber.pod, perlopentut.pod, perlreftut.pod, perltootc.pod, perltodo.pod, perlunicode.pod =item Performance enhancements =over 4 =item Simple sort() using { $a <=> $b } and the like are optimized =item Optimized assignments to lexical variables =item Faster subroutine calls =item delete(), each(), values() and hash iteration are faster =back =item Installation and Configuration Improvements =over 4 =item -Dusethreads means something different =item New Configure flags =item Threadedness and 64-bitness now more daring =item Long Doubles =item -Dusemorebits =item -Duselargefiles =item installusrbinperl =item SOCKS support =item C<-A> flag =item Enhanced Installation Directories =back =item Platform specific changes =over 4 =item Supported platforms =item DOS =item OS390 (OpenEdition MVS) =item VMS =item Win32 =back =item Significant bug fixes =over 4 =item <HANDLE> on empty files =item C<eval '...'> improvements =item All compilation errors are true errors =item Implicitly closed filehandles are safer =item Behavior of list slices is more consistent =item C<(\$)> prototype and C<$foo{a}> =item C<goto &sub> and AUTOLOAD =item C<-bareword> allowed under C<use integer> =item Failures in DESTROY() =item Locale bugs fixed =item Memory leaks =item Spurious subroutine stubs after failed subroutine calls =item Taint failures under C<-U> =item END blocks and the C<-c> switch =item Potential to leak DATA filehandles =back =item New or Changed Diagnostics "%s" variable %s masks earlier declaration in same %s, "my sub" not yet implemented, "our" variable %s redeclared, '!' allowed only after types %s, / cannot take a count, / must be followed by a, A or Z, / must be followed by a*, A* or Z*, / must follow a numeric type, /%s/: Unrecognized escape \\%c passed through, /%s/: Unrecognized escape \\%c in character class passed through, /%s/ should probably be written as "%s", %s() called too early to check prototype, %s argument is not a HASH or ARRAY element, %s argument is not a HASH or ARRAY element or slice, %s argument is not a subroutine name, %s package attribute may clash with future reserved word: %s, (in cleanup) %s, <> should be quotes, Attempt to join self, Bad evalled substitution pattern, Bad realloc() ignored, Bareword found in conditional, Binary number > 0b11111111111111111111111111111111 non-portable, Bit vector size > 32 non-portable, Buffer overflow in prime_env_iter: %s, Can't check filesystem of script "%s", Can't declare class for non-scalar %s in "%s", Can't declare %s in "%s", Can't ignore signal CHLD, forcing to default, Can't modify non-lvalue subroutine call, Can't read CRTL environ, Can't remove %s: %s, skipping file, Can't return %s from lvalue subroutine, Can't weaken a nonreference, Character class [:%s:] unknown, Character class syntax [%s] belongs inside character classes, Constant is not %s reference, constant(%s): %s, CORE::%s is not a keyword, defined(@array) is deprecated, defined(%hash) is deprecated, Did not produce a valid header, (Did you mean "local" instead of "our"?), Document contains no data, entering effective %s failed, false [] range "%s" in regexp, Filehandle %s opened only for output, flock() on closed filehandle %s, Global symbol "%s" requires explicit package name, Hexadecimal number > 0xffffffff non-portable, Ill-formed CRTL environ value "%s", Ill-formed message in prime_env_iter: |%s|, Illegal binary digit %s, Illegal binary digit %s ignored, Illegal number of bits in vec, Integer overflow in %s number, Invalid %s attribute: %s, Invalid %s attributes: %s, invalid [] range "%s" in regexp, Invalid separator character %s in attribute list, Invalid separator character %s in subroutine attribute list, leaving effective %s failed, Lvalue subs returning %s not implemented yet, Method %s not permitted, Missing %sbrace%s on \N{}, Missing command in piped open, Missing name in "my sub", No %s specified for -%c, No package name allowed for variable %s in "our", No space allowed after -%c, no UTC offset information; assuming local time is UTC, Octal number > 037777777777 non-portable, panic: del_backref, panic: kid popen errno read, panic: magic_killbackrefs, Parentheses missing around "%s" list, Possible unintended interpolation of %s in string, Possible Y2K bug: %s, pragma "attrs" is deprecated, use "sub NAME : ATTRS" instead, Premature end of script headers, Repeat count in pack overflows, Repeat count in unpack overflows, realloc() of freed memory ignored, Reference is already weak, setpgrp can't take arguments, Strange *+?{} on zero-length expression, switching effective %s is not implemented, This Perl can't reset CRTL environ elements (%s), This Perl can't set CRTL environ elements (%s=%s), Too late to run %s block, Unknown open() mode '%s', Unknown process %x sent message to prime_env_iter: %s, Unrecognized escape \\%c passed through, Unterminated attribute parameter in attribute list, Unterminated attribute list, Unterminated attribute parameter in subroutine attribute list, Unterminated subroutine attribute list, Value of CLI symbol "%s" too long, Version number must be a constant number =item New tests =item Incompatible Changes =over 4 =item Perl Source Incompatibilities CHECK is a new keyword, Treatment of list slices of undef has changed, Format of $English::PERL_VERSION is different, Literals of the form C<1.2.3> parse differently, Possibly changed pseudo-random number generator, Hashing function for hash keys has changed, C<undef> fails on read only values, Close-on-exec bit may be set on pipe and socket handles, Writing C<"$$1"> to mean C<"${$}1"> is unsupported, delete(), each(), values() and C<\(%h)>, vec(EXPR,OFFSET,BITS) enforces powers-of-two BITS, Text of some diagnostic output has changed, C<%@> has been removed, Parenthesized not() behaves like a list operator, Semantics of bareword prototype C<(*)> have changed, Semantics of bit operators may have changed on 64-bit platforms, More builtins taint their results =item C Source Incompatibilities C<PERL_POLLUTE>, C<PERL_IMPLICIT_CONTEXT>, C<PERL_POLLUTE_MALLOC> =item Compatible C Source API Changes C<PATCHLEVEL> is now C<PERL_VERSION> =item Binary Incompatibilities =back =item Known Problems =over 4 =item Thread test failures =item EBCDIC platforms not supported =item In 64-bit HP-UX the lib/io_multihomed test may hang =item NEXTSTEP 3.3 POSIX test failure =item Tru64 (aka Digital UNIX, aka DEC OSF/1) lib/sdbm test failure with gcc =item UNICOS/mk CC failures during Configure run =item Arrow operator and arrays =item Experimental features Threads, Unicode, 64-bit support, Lvalue subroutines, Weak references, The pseudo-hash data type, The Compiler suite, Internal implementation of file globbing, The DB module, The regular expression code constructs: =back =item Obsolete Diagnostics Character class syntax [: :] is reserved for future extensions, Ill-formed logical name |%s| in prime_env_iter, In string, @%s now must be written as \@%s, Probable precedence problem on %s, regexp too big, Use of "$$<digit>" to mean "${$}<digit>" is deprecated =item Reporting Bugs =item SEE ALSO =item HISTORY =back =head2 perl5005delta - what's new for perl5.005 =over 4 =item DESCRIPTION =item About the new versioning system =item Incompatible Changes =over 4 =item WARNING: This version is not binary compatible with Perl 5.004. =item Default installation structure has changed =item Perl Source Compatibility =item C Source Compatibility =item Binary Compatibility =item Security fixes may affect compatibility =item Relaxed new mandatory warnings introduced in 5.004 =item Licensing =back =item Core Changes =over 4 =item Threads =item Compiler =item Regular Expressions Many new and improved optimizations, Many bug fixes, New regular expression constructs, New operator for precompiled regular expressions, Other improvements, Incompatible changes =item Improved malloc() =item Quicksort is internally implemented =item Reliable signals =item Reliable stack pointers =item More generous treatment of carriage returns =item Memory leaks =item Better support for multiple interpreters =item Behavior of local() on array and hash elements is now well-defined =item C<%!> is transparently tied to the L<Errno> module =item Pseudo-hashes are supported =item C<EXPR foreach EXPR> is supported =item Keywords can be globally overridden =item C<$^E> is meaningful on Win32 =item C<foreach (1..1000000)> optimized =item C<Foo::> can be used as implicitly quoted package name =item C<exists $Foo::{Bar::}> tests existence of a package =item Better locale support =item Experimental support for 64-bit platforms =item prototype() returns useful results on builtins =item Extended support for exception handling =item Re-blessing in DESTROY() supported for chaining DESTROY() methods =item All C<printf> format conversions are handled internally =item New C<INIT> keyword =item New C<lock> keyword =item New C<qr//> operator =item C<our> is now a reserved word =item Tied arrays are now fully supported =item Tied handles support is better =item 4th argument to substr =item Negative LENGTH argument to splice =item Magic lvalues are now more magical =item <> now reads in records =back =item Supported Platforms =over 4 =item New Platforms =item Changes in existing support =back =item Modules and Pragmata =over 4 =item New Modules B, Data::Dumper, Dumpvalue, Errno, File::Spec, ExtUtils::Installed, ExtUtils::Packlist, Fatal, IPC::SysV, Test, Tie::Array, Tie::Handle, Thread, attrs, fields, re =item Changes in existing modules Benchmark, Carp, CGI, Fcntl, Math::Complex, Math::Trig, POSIX, DB_File, MakeMaker, CPAN, Cwd =back =item Utility Changes =item Documentation Changes =item New Diagnostics Ambiguous call resolved as CORE::%s(), qualify as such or use &, Bad index while coercing array into hash, Bareword "%s" refers to nonexistent package, Can't call method "%s" on an undefined value, Can't check filesystem of script "%s" for nosuid, Can't coerce array into hash, Can't goto subroutine from an eval-string, Can't localize pseudo-hash element, Can't use %%! because Errno.pm is not available, Cannot find an opnumber for "%s", Character class syntax [. .] is reserved for future extensions, Character class syntax [: :] is reserved for future extensions, Character class syntax [= =] is reserved for future extensions, %s: Eval-group in insecure regular expression, %s: Eval-group not allowed, use re 'eval', %s: Eval-group not allowed at run time, Explicit blessing to '' (assuming package main), Illegal hex digit ignored, No such array field, No such field "%s" in variable %s of type %s, Out of memory during ridiculously large request, Range iterator outside integer range, Recursive inheritance detected while looking for method '%s' %s, Reference found where even-sized list expected, Undefined value assigned to typeglob, Use of reserved word "%s" is deprecated, perl: warning: Setting locale failed =item Obsolete Diagnostics Can't mktemp(), Can't write to temp file for B<-e>: %s, Cannot open temporary file, regexp too big =item Configuration Changes =item BUGS =item SEE ALSO =item HISTORY =back =head2 perl5004delta - what's new for perl5.004 =over 4 =item DESCRIPTION =item Supported Environments =item Core Changes =over 4 =item List assignment to %ENV works =item Change to "Can't locate Foo.pm in @INC" error =item Compilation option: Binary compatibility with 5.003 =item $PERL5OPT environment variable =item Limitations on B<-M>, B<-m>, and B<-T> options =item More precise warnings =item Deprecated: Inherited C<AUTOLOAD> for non-methods =item Previously deprecated %OVERLOAD is no longer usable =item Subroutine arguments created only when they're modified =item Group vector changeable with C<$)> =item Fixed parsing of $$<digit>, &$<digit>, etc. =item Fixed localization of $<digit>, $&, etc. =item No resetting of $. on implicit close =item C<wantarray> may return undef =item C<eval EXPR> determines value of EXPR in scalar context =item Changes to tainting checks No glob() or <*>, No spawning if tainted $CDPATH, $ENV, $BASH_ENV, No spawning if tainted $TERM doesn't look like a terminal name =item New Opcode module and revised Safe module =item Embedding improvements =item Internal change: FileHandle class based on IO::* classes =item Internal change: PerlIO abstraction interface =item New and changed syntax $coderef->(PARAMS) =item New and changed builtin constants __PACKAGE__ =item New and changed builtin variables $^E, $^H, $^M =item New and changed builtin functions delete on slices, flock, printf and sprintf, keys as an lvalue, my() in Control Structures, pack() and unpack(), sysseek(), use VERSION, use Module VERSION LIST, prototype(FUNCTION), srand, $_ as Default, C<m//gc> does not reset search position on failure, C<m//x> ignores whitespace before ?*+{}, nested C<sub{}> closures work now, formats work right on changing lexicals =item New builtin methods isa(CLASS), can(METHOD), VERSION( [NEED] ) =item TIEHANDLE now supported TIEHANDLE classname, LIST, PRINT this, LIST, PRINTF this, LIST, READ this LIST, READLINE this, GETC this, DESTROY this =item Malloc enhancements -DPERL_EMERGENCY_SBRK, -DPACK_MALLOC, -DTWO_POT_OPTIMIZE =item Miscellaneous efficiency enhancements =back =item Support for More Operating Systems =over 4 =item Win32 =item Plan 9 =item QNX =item AmigaOS =back =item Pragmata use autouse MODULE => qw(sub1 sub2 sub3), use blib, use blib 'dir', use constant NAME => VALUE, use locale, use ops, use vmsish =item Modules =over 4 =item Required Updates =item Installation directories =item Module information summary =item Fcntl =item IO =item Math::Complex =item Math::Trig =item DB_File =item Net::Ping =item Object-oriented overrides for builtin operators =back =item Utility Changes =over 4 =item pod2html Sends converted HTML to standard output =item xsubpp C<void> XSUBs now default to returning nothing =back =item C Language API Changes C<gv_fetchmethod> and C<perl_call_sv>, C<perl_eval_pv>, Extended API for manipulating hashes =item Documentation Changes L<perldelta>, L<perlfaq>, L<perllocale>, L<perltoot>, L<perlapio>, L<perlmodlib>, L<perldebug>, L<perlsec> =item New Diagnostics "my" variable %s masks earlier declaration in same scope, %s argument is not a HASH element or slice, Allocation too large: %lx, Allocation too large, Applying %s to %s will act on scalar(%s), Attempt to free nonexistent shared string, Attempt to use reference as lvalue in substr, Bareword "%s" refers to nonexistent package, Can't redefine active sort subroutine %s, Can't use bareword ("%s") as %s ref while "strict refs" in use, Cannot resolve method `%s' overloading `%s' in package `%s', Constant subroutine %s redefined, Constant subroutine %s undefined, Copy method did not return a reference, Died, Exiting pseudo-block via %s, Identifier too long, Illegal character %s (carriage return), Illegal switch in PERL5OPT: %s, Integer overflow in hex number, Integer overflow in octal number, internal error: glob failed, Invalid conversion in %s: "%s", Invalid type in pack: '%s', Invalid type in unpack: '%s', Name "%s::%s" used only once: possible typo, Null picture in formline, Offset outside string, Out of memory!, Out of memory during request for %s, panic: frexp, Possible attempt to put comments in qw() list, Possible attempt to separate words with commas, Scalar value @%s{%s} better written as $%s{%s}, Stub found while resolving method `%s' overloading `%s' in %s, Too late for "B<-T>" option, untie attempted while %d inner references still exist, Unrecognized character %s, Unsupported function fork, Use of "$$<digit>" to mean "${$}<digit>" is deprecated, Value of %s can be "0"; test with defined(), Variable "%s" may be unavailable, Variable "%s" will not stay shared, Warning: something's wrong, Ill-formed logical name |%s| in prime_env_iter, Got an error from DosAllocMem, Malformed PERLLIB_PREFIX, PERL_SH_DIR too long, Process terminated by SIG%s =item BUGS =item SEE ALSO =item HISTORY =back =head2 perlexperiment - A listing of experimental features in Perl =over 4 =item DESCRIPTION =over 4 =item Current experiments fork() emulation, Weak references, Internal file glob, 64-bit support, die accepts a reference, Unicode support, -Dusemultiplicity -Dusethreads, Long Doubles Still Don't Work In Solaris, GetOpt::Long Options can now take multiple values at once (experimental), 5.005-style threading, Test::Harness::Straps, perlcc, C<our> can now have an experimental optional attribute C<unique>, Assertions, Linux abstract Unix domain sockets, L<Pod::HTML2Pod|Pod::HTML2Pod>, L<Pod::PXML|Pod::PXML>, threads, The <:pop> IO pseudolayer, The <:win32> IO pseudolayer, MLDBM, internal functions with M flag, lex_start API, internal API for C<%H>, av_create_and_push, av_create_and_unshift_one, av_create_and_unshift_one, PL_keyword_plugin, hv_iternext_flags, lex_bufutf8, lex_discard_to, lex_grow_linestr, lex_next_chunk, lex_peek_unichar, lex_read_space, lex_read_to, lex_read_unichar, lex_stuff_pv, lex_stuff_pvn, lex_stuff_pvs, lex_stuff_sv, lex_unstuff, parse_fullstmt, parse_stmtseq, PL_parser-E<gt>bufend, PL_parser-E<gt>bufptr, PL_parser-E<gt>linestart, PL_parser-E<gt>linestr, Perl_signbit, pad_findmy, sv_utf8_decode, sv_utf8_downgrade, bytes_from_utf8, bytes_to_utf8, utf8_to_bytes, DB module, The pseudo-hash data type, Lvalue subroutines, There is an C<installhtml> target in the Makefile, Unicode in Perl on EBCDIC, C<(?{code})>, C<(??{ code })>, Backtracking control verbs, Code expressions, conditional expressions, and independent expressions in regexes, The C<\N> regex character class, gv_try_downgrade, Experimental Support for Sun Studio Compilers for Linux OS, Pluggable keywords =item Accepted features (none yet identified) =item Removed features C<legacy> =back =item AUTHORS =item COPYRIGHT =item LICENSE =back =head2 perlartistic - the Perl Artistic License =over 4 =item SYNOPSIS =item DESCRIPTION =item The "Artistic License" =over 4 =item Preamble =item Definitions "Package", "Standard Version", "Copyright Holder", "You", "Reasonable copying fee", "Freely Available" =item Conditions a), b), c), d), a), b), c), d) =back =back =head2 perlgpl - the GNU General Public License, version 1 =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item GNU GENERAL PUBLIC LICENSE =back =head2 perlaix - Perl version 5 on IBM AIX (UNIX) systems =over 4 =item DESCRIPTION =over 4 =item Compiling Perl 5 on AIX =item Supported Compilers =item Incompatibility with AIX Toolbox lib gdbm =item Perl 5 was successfully compiled and tested on: =item Building Dynamic Extensions on AIX =item Using Large Files with Perl =item Threaded Perl =item 64-bit Perl =item Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (threaded/32-bit) =item Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (32-bit) =item Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (threaded/64-bit) =item Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (64-bit) =item Compiling Perl 5 on older AIX versions up to 4.3.3 =item OS level =item Building Dynamic Extensions on AIX E<lt> 5L =item The IBM ANSI C Compiler =item The usenm option =item Using GNU's gcc for building Perl =item Using Large Files with Perl E<lt> 5L =item Threaded Perl E<lt> 5L =item 64-bit Perl E<lt> 5L =item AIX 4.2 and extensions using C++ with statics =back =item AUTHORS =back =head2 perlamiga - Perl under Amiga OS =over 4 =item NOTE =item SYNOPSIS =back =over 4 =item DESCRIPTION =over 4 =item Prerequisites for Compiling Perl on AmigaOS B<Unix emulation for AmigaOS: ixemul.library>, B<Version of Amiga OS> =item Starting Perl programs under AmigaOS =item Shortcomings of Perl under AmigaOS =back =item INSTALLATION =item Accessing documentation =over 4 =item Manpages for Perl on AmigaOS =item Perl HTML Documentation on AmigaOS =item Perl GNU Info Files on AmigaOS =item Perl LaTeX Documentation on AmigaOS =back =item BUILDING PERL ON AMIGAOS =over 4 =item Build Prerequisites for Perl on AmigaOS =item Getting the Perl Source for AmigaOS =item Making Perl on AmigaOS =item Testing Perl on AmigaOS =item Installing the built Perl on AmigaOS =back =item PERL 5.8.0 BROKEN IN AMIGAOS =item AUTHORS =item SEE ALSO =back =head2 perlbeos - Perl version 5.8+ on BeOS =over 4 =item DESCRIPTION =item BUILD AND INSTALL =over 4 =item Requirements =item Configure =item Build =item Install =back =item KNOWN PROBLEMS =item CONTACT =back =head2 perlbs2000 - building and installing Perl for BS2000. =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item gzip on BS2000 =item bison on BS2000 =item Unpacking Perl Distribution on BS2000 =item Compiling Perl on BS2000 =item Testing Perl on BS2000 =item Installing Perl on BS2000 =item Using Perl in the Posix-Shell of BS2000 =item Using Perl in "native" BS2000 =item Floating point anomalies on BS2000 =item Using PerlIO and different encodings on ASCII and EBCDIC partitions =back =item AUTHORS =item SEE ALSO =over 4 =item Mailing list =back =item HISTORY =back =head2 perlce - Perl for WinCE =over 4 =item Building Perl for WinCE =over 4 =item DESCRIPTION =item General explanations on cross-compiling WinCE =item BUILD Microsoft Embedded Visual Tools, Microsoft Visual C++, Rainer Keuchel's celib-sources, Rainer Keuchel's console-sources, go to F<./win32> subdirectory, edit file F<./win32/ce-helpers/compile.bat>, run compile.bat, run compile.bat dist =back =item Using Perl on WinCE =over 4 =item DESCRIPTION =item LIMITATIONS =item ENVIRONMENT PERL5LIB, PATH, TMP, UNIXROOTPATH, ROWS/COLS, HOME, CONSOLEFONTSIZE =item REGISTRY =item XS =item BUGS =item INSTALLATION =back =item ACKNOWLEDGEMENTS =item History of WinCE port =item AUTHORS Rainer Keuchel <coyxc@rainer-keuchel.de>, Vadim Konovalov =back =head2 perlcygwin - Perl for Cygwin =over 4 =item SYNOPSIS =item PREREQUISITES FOR COMPILING PERL ON CYGWIN =over 4 =item Cygwin = GNU+Cygnus+Windows (Don't leave UNIX without it) =item Cygwin Configuration C<PATH>, I<nroff> =back =item CONFIGURE PERL ON CYGWIN =over 4 =item Stripping Perl Binaries on Cygwin =item Optional Libraries for Perl on Cygwin C<-lcrypt>, C<-lgdbm_compat> (C<use GDBM_File>), C<-ldb> (C<use DB_File>), C<cygserver> (C<use IPC::SysV>), C<-lutil> =item Configure-time Options for Perl on Cygwin C<-Uusedl>, C<-Dusemymalloc>, C<-Uuseperlio>, C<-Dusemultiplicity>, C<-Uuse64bitint>, C<-Duselongdouble>, C<-Uuseithreads>, C<-Duselargefiles>, C<-Dmksymlinks> =item Suspicious Warnings on Cygwin Win9x and C<d_eofnblk>, Compiler/Preprocessor defines =back =item MAKE ON CYGWIN =item TEST ON CYGWIN =over 4 =item File Permissions on Cygwin =item NDBM_File and ODBM_File do not work on FAT filesystems =item C<fork()> failures in io_* tests =back =item Specific features of the Cygwin port =over 4 =item Script Portability on Cygwin Pathnames, Text/Binary, PerlIO, F<.exe>, Cygwin vs. Windows process ids, Cygwin vs. Windows errors, rebase errors on fork or system, C<chown()>, Miscellaneous =item Prebuilt methods: C<Cwd::cwd>, C<Cygwin::pid_to_winpid>, C<Cygwin::winpid_to_pid>, C<Cygwin::win_to_posix_path>, C<Cygwin::posix_to_win_path>, C<Cygwin::mount_table()>, C<Cygwin::mount_flags>, C<Cygwin::is_binmount>, C<Cygwin::sync_winenv> =back =item INSTALL PERL ON CYGWIN =item MANIFEST ON CYGWIN Documentation, Build, Configure, Make, Install, Tests, Compiled Perl Source, Compiled Module Source, Perl Modules/Scripts, Perl Module Tests =item BUGS ON CYGWIN =item AUTHORS =item HISTORY =back =head2 perldgux - Perl under DG/UX. =over 4 =item SYNOPSIS =back =over 4 =item DESCRIPTION =item BUILDING PERL ON DG/UX =over 4 =item Non-threaded Perl on DG/UX =item Threaded Perl on DG/UX =item Testing Perl on DG/UX =item Installing the built perl on DG/UX =back =item AUTHOR =item SEE ALSO =back =head2 perldos - Perl under DOS, W31, W95. =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Prerequisites for Compiling Perl on DOS DJGPP, Pthreads =item Shortcomings of Perl under DOS =item Building Perl on DOS =item Testing Perl on DOS =item Installation of Perl on DOS =back =item BUILDING AND INSTALLING MODULES ON DOS =over 4 =item Building Prerequisites for Perl on DOS =item Unpacking CPAN Modules on DOS =item Building Non-XS Modules on DOS =item Building XS Modules on DOS =back =item AUTHOR =item SEE ALSO =back =head2 perlepoc - Perl for EPOC =over 4 =item SYNOPSIS =item INTRODUCTION =item INSTALLING PERL ON EPOC =item STARTING PERL ON EPOC =over 4 =item Features of Perl on Epoc =item Restrictions of Perl on Epoc =item Compiling Perl 5 on the EPOC cross compiling environment =back =item SUPPORT STATUS OF PERL ON EPOC =item AUTHOR =item LAST UPDATE =back =head2 perlfreebsd - Perl version 5 on FreeBSD systems =over 4 =item DESCRIPTION =over 4 =item FreeBSD core dumps from readdir_r with ithreads =item $^X doesn't always contain a full path in FreeBSD =back =item AUTHOR =back =head2 perlhaiku - Perl version 5.10+ on Haiku =over 4 =item DESCRIPTION =item BUILD AND INSTALL =item KNOWN PROBLEMS =item CONTACT =back =head2 perlhpux - Perl version 5 on Hewlett-Packard Unix (HP-UX) systems =over 4 =item DESCRIPTION =over 4 =item Using perl as shipped with HP-UX =item Using perl from HP's porting centre =item Compiling Perl 5 on HP-UX =item PA-RISC =item Portability Between PA-RISC Versions =item PA-RISC 1.0 =item PA-RISC 1.1 =item PA-RISC 2.0 =item Itanium Processor Family (IPF) and HP-UX =item Itanium, Itanium 2 & Madison 6 =item HP-UX versions =item Building Dynamic Extensions on HP-UX =item The HP ANSI C Compiler =item The GNU C Compiler =item Using Large Files with Perl on HP-UX =item Threaded Perl on HP-UX =item 64-bit Perl on HP-UX =item Oracle on HP-UX =item GDBM and Threads on HP-UX =item NFS filesystems and utime(2) on HP-UX =item HP-UX Kernel Parameters (maxdsiz) for Compiling Perl =back =item nss_delete core dump from op/pwent or op/grent =item error: pasting ")" and "l" does not give a valid preprocessing token =item Miscellaneous =item AUTHOR =back =head2 perlhurd - Perl version 5 on Hurd =over 4 =item DESCRIPTION =over 4 =item Known Problems with Perl on Hurd =back =item AUTHOR =back =head2 perlirix - Perl version 5 on Irix systems =over 4 =item DESCRIPTION =over 4 =item Building 32-bit Perl in Irix =item Building 64-bit Perl in Irix =item About Compiler Versions of Irix =item Linker Problems in Irix =item Malloc in Irix =item Building with threads in Irix =item Irix 5.3 =back =item AUTHOR =back =head2 perllinux - Perl version 5 on Linux systems =over 4 =item DESCRIPTION =over 4 =item Experimental Support for Sun Studio Compilers for Linux OS =back =item AUTHOR =back =head2 perlmacos - Perl under Mac OS (Classic) =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR =back =head2 perlmacosx - Perl under Mac OS X =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Installation Prefix =item SDK support =item Universal Binary support =item 64-bit PPC support =item libperl and Prebinding =item Updating Apple's Perl =item Known problems =item Cocoa =back =item Starting From Scratch =item AUTHOR =item DATE =back =head2 perlmpeix - Perl/iX for HP e3000 MPE =over 4 =item SYNOPSIS =item NOTE =item What's New in Perl for MPE/iX =item Welcome to Perl/iX =item System Requirements for Perl/iX =item How to Obtain Perl/iX =item Perl/iX Distribution Contents Highlights README, INSTALL, LIBSHP3K, PERL, .cpan/, lib/, man/, public_html/feedback.cgi, src/perl-5.6.0-mpe =item How to Compile Perl/iX 4, 6 =item Getting Started with Perl/iX =item MPE/iX Implementation Considerations =item Known Perl/iX Bugs Under Investigation =item Perl/iX To-Do List =item Perl/iX Change History =item AUTHOR =back =head2 perlnetware - Perl for NetWare =over 4 =item DESCRIPTION =item BUILD =over 4 =item Tools & SDK =item Setup SetNWBld.bat, Buildtype.bat =item Make =item Interpreter =item Extensions =back =item INSTALL =item BUILD NEW EXTENSIONS =item ACKNOWLEDGEMENTS =item AUTHORS =item DATE =back =head2 perlopenbsd - Perl version 5 on OpenBSD systems =over 4 =item DESCRIPTION =over 4 =item OpenBSD core dumps from getprotobyname_r and getservbyname_r with ithreads =back =item AUTHOR =back =head2 perlos2 - Perl under OS/2, DOS, Win0.3*, Win0.95 and WinNT. =over 4 =item SYNOPSIS =back =over 4 =item DESCRIPTION =over 4 =item Target =item Other OSes =item Prerequisites EMX, RSX, HPFS, pdksh =item Starting Perl programs under OS/2 (and DOS and...) =item Starting OS/2 (and DOS) programs under Perl =back =item Frequently asked questions =over 4 =item "It does not work" =item I cannot run external programs =item I cannot embed perl into my program, or use F<perl.dll> from my program. Is your program EMX-compiled with C<-Zmt -Zcrtdll>?, Did you use L<ExtUtils::Embed>? =item C<``> and pipe-C<open> do not work under DOS. =item Cannot start C<find.exe "pattern" file> =back =item INSTALLATION =over 4 =item Automatic binary installation C<PERL_BADLANG>, C<PERL_BADFREE>, F<Config.pm> =item Manual binary installation Perl VIO and PM executables (dynamically linked), Perl_ VIO executable (statically linked), Executables for Perl utilities, Main Perl library, Additional Perl modules, Tools to compile Perl modules, Manpages for Perl and utilities, Manpages for Perl modules, Source for Perl documentation, Perl manual in F<.INF> format, Pdksh =item B<Warning> =back =item Accessing documentation =over 4 =item OS/2 F<.INF> file =item Plain text =item Manpages =item HTML =item GNU C<info> files =item F<PDF> files =item C<LaTeX> docs =back =item BUILD =over 4 =item The short story =item Prerequisites =item Getting perl source =item Application of the patches =item Hand-editing =item Making =item Testing A lot of C<bad free>, Process terminated by SIGTERM/SIGINT, F<op/fs.t>, F<op/stat.t> =item Installing the built perl =item C<a.out>-style build =back =item Building a binary distribution =item Building custom F<.EXE> files =over 4 =item Making executables with a custom collection of statically loaded extensions =item Making executables with a custom search-paths =back =item Build FAQ =over 4 =item Some C</> became C<\> in pdksh. =item C<'errno'> - unresolved external =item Problems with tr or sed =item Some problem (forget which ;-) =item Library ... not found =item Segfault in make =item op/sprintf test failure =back =item Specific (mis)features of OS/2 port =over 4 =item C<setpriority>, C<getpriority> =item C<system()> =item C<extproc> on the first line =item Additional modules: =item Prebuilt methods: C<File::Copy::syscopy>, C<DynaLoader::mod2fname>, C<Cwd::current_drive()>, C<Cwd::sys_chdir(name)>, C<Cwd::change_drive(name)>, C<Cwd::sys_is_absolute(name)>, C<Cwd::sys_is_rooted(name)>, C<Cwd::sys_is_relative(name)>, C<Cwd::sys_cwd(name)>, C<Cwd::sys_abspath(name, dir)>, C<Cwd::extLibpath([type])>, C<Cwd::extLibpath_set( path [, type ] )>, C<OS2::Error(do_harderror,do_exception)>, C<OS2::Errors2Drive(drive)>, OS2::SysInfo(), OS2::BootDrive(), C<OS2::MorphPM(serve)>, C<OS2::UnMorphPM(serve)>, C<OS2::Serve_Messages(force)>, C<OS2::Process_Messages(force [, cnt])>, C<OS2::_control87(new,mask)>, OS2::get_control87(), C<OS2::set_control87_em(new=MCW_EM,mask=MCW_EM)>, C<OS2::DLLname([how [, \&xsub]])> =item Prebuilt variables: $OS2::emx_rev, $OS2::emx_env, $OS2::os_ver, $OS2::is_aout, $OS2::can_fork, $OS2::nsyserror =item Misfeatures =item Modifications C<popen>, C<tmpnam>, C<tmpfile>, C<ctermid>, C<stat>, C<mkdir>, C<rmdir>, C<flock> =item Identifying DLLs =item Centralized management of resources C<HAB>, C<HMQ>, Treating errors reported by OS/2 API, C<CheckOSError(expr)>, C<CheckWinError(expr)>, C<SaveWinError(expr)>, C<SaveCroakWinError(expr,die,name1,name2)>, C<WinError_2_Perl_rc>, C<FillWinError>, C<FillOSError(rc)>, Loading DLLs and ordinals in DLLs =back =item Perl flavors =over 4 =item F<perl.exe> =item F<perl_.exe> =item F<perl__.exe> =item F<perl___.exe> =item Why strange names? =item Why dynamic linking? =item Why chimera build? =back =item ENVIRONMENT =over 4 =item C<PERLLIB_PREFIX> =item C<PERL_BADLANG> =item C<PERL_BADFREE> =item C<PERL_SH_DIR> =item C<USE_PERL_FLOCK> =item C<TMP> or C<TEMP> =back =item Evolution =over 4 =item Text-mode filehandles =item Priorities =item DLL name mangling: pre 5.6.2 =item DLL name mangling: 5.6.2 and beyond Global DLLs, specific DLLs, C<BEGINLIBPATH> and C<ENDLIBPATH>, F<.> from C<LIBPATH> =item DLL forwarder generation =item Threading =item Calls to external programs =item Memory allocation =item Threads C<COND_WAIT>, F<os2.c> =back =item BUGS =back =over 4 =item AUTHOR =item SEE ALSO =back =head2 perlos390 - building and installing Perl for OS/390 and z/OS =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Tools =item Unpacking Perl distribution on OS/390 =item Setup and utilities for Perl on OS/390 =item Configure Perl on OS/390 =item Build, Test, Install Perl on OS/390 =item Build Anomalies with Perl on OS/390 =item Testing Anomalies with Perl on OS/390 =item Installation Anomalies with Perl on OS/390 =item Usage Hints for Perl on OS/390 =item Floating Point Anomalies with Perl on OS/390 =item Modules and Extensions for Perl on OS/390 =back =item AUTHORS =item SEE ALSO =over 4 =item Mailing list for Perl on OS/390 =back =item HISTORY =back =head2 perlos400 - Perl version 5 on OS/400 =over 4 =item DESCRIPTION =over 4 =item Compiling Perl for OS/400 PASE =item Installing Perl in OS/400 PASE =item Using Perl in OS/400 PASE =item Known Problems =item Perl on ILE =back =item AUTHORS =back =head2 perlplan9 - Plan 9-specific documentation for Perl =over 4 =item DESCRIPTION =over 4 =item Invoking Perl =item What's in Plan 9 Perl =item What's not in Plan 9 Perl =item Perl5 Functions not currently supported in Plan 9 Perl =item Signals in Plan 9 Perl =back =item COMPILING AND INSTALLING PERL ON PLAN 9 =over 4 =item Installing Perl Documentation on Plan 9 =back =item BUGS =item Revision date =item AUTHOR =back =head2 perlqnx - Perl version 5 on QNX =over 4 =item DESCRIPTION =over 4 =item Required Software for Compiling Perl on QNX4 /bin/sh, ar, nm, cpp, make =item Outstanding Issues with Perl on QNX4 =item QNX auxiliary files qnx/ar, qnx/cpp =item Outstanding issues with perl under QNX6 =back =item AUTHOR =back =head2 perlriscos - Perl version 5 for RISC OS =over 4 =item DESCRIPTION =item BUILD =item AUTHOR =back =head2 perlsolaris - Perl version 5 on Solaris systems =over 4 =item DESCRIPTION =over 4 =item Solaris Version Numbers. =back =item RESOURCES Solaris FAQ, Precompiled Binaries, Solaris Documentation =item SETTING UP =over 4 =item File Extraction Problems on Solaris. =item Compiler and Related Tools on Solaris. =item Environment for Compiling perl on Solaris =back =item RUN CONFIGURE. =over 4 =item 64-bit perl on Solaris. =item Threads in perl on Solaris. =item Malloc Issues with perl on Solaris. =back =item MAKE PROBLEMS. Dynamic Loading Problems With GNU as and GNU ld, ld.so.1: ./perl: fatal: relocation error:, dlopen: stub interception failed, #error "No DATAMODEL_NATIVE specified", sh: ar: not found =item MAKE TEST =over 4 =item op/stat.t test 4 in Solaris =item nss_delete core dump from op/pwent or op/grent =back =item PREBUILT BINARIES OF PERL FOR SOLARIS. =item RUNTIME ISSUES FOR PERL ON SOLARIS. =over 4 =item Limits on Numbers of Open Files on Solaris. =back =item SOLARIS-SPECIFIC MODULES. =item SOLARIS-SPECIFIC PROBLEMS WITH MODULES. =over 4 =item Proc::ProcessTable on Solaris =item BSD::Resource on Solaris =item Net::SSLeay on Solaris =back =item SunOS 4.x =item AUTHOR =back =head2 perlsymbian - Perl version 5 on Symbian OS =over 4 =item DESCRIPTION =over 4 =item Compiling Perl on Symbian =item Compilation problems =item PerlApp =item sisify.pl =item Using Perl in Symbian =back =item TO DO =item WARNING =item NOTE =item AUTHOR =item COPYRIGHT =item LICENSE =item HISTORY =back =head2 perltru64 - Perl version 5 on Tru64 (formerly known as Digital UNIX formerly known as DEC OSF/1) systems =over 4 =item DESCRIPTION =over 4 =item Compiling Perl 5 on Tru64 =item Using Large Files with Perl on Tru64 =item Threaded Perl on Tru64 =item Long Doubles on Tru64 =item DB_File tests failing on Tru64 =item 64-bit Perl on Tru64 =item Warnings about floating-point overflow when compiling Perl on Tru64 =back =item Testing Perl on Tru64 =item ext/ODBM_File/odbm Test Failing With Static Builds =item Perl Fails Because Of Unresolved Symbol sockatmark =item AUTHOR =back =head2 perluts - Perl under UTS =over 4 =item SYNOPSIS =item DESCRIPTION =item BUILDING PERL ON UTS =item Installing the built perl on UTS =item AUTHOR =back =head2 perlvmesa - building and installing Perl for VM/ESA. =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Unpacking Perl Distribution on VM/ESA =item Setup Perl and utilities on VM/ESA =item Configure Perl on VM/ESA =item Testing Anomalies of Perl on VM/ESA =item Usage Hints for Perl on VM/ESA =back =item AUTHORS =item SEE ALSO =over 4 =item Mailing list for Perl on VM/ESA =back =back =head2 perlvms - VMS-specific documentation for Perl =over 4 =item DESCRIPTION =item Installation =item Organization of Perl Images =over 4 =item Core Images =item Perl Extensions =item Installing static extensions =item Installing dynamic extensions =back =item File specifications =over 4 =item Syntax =item Filename Case =item Symbolic Links =item Wildcard expansion =item Pipes =back =item PERL5LIB and PERLLIB =item The Perl Forked Debugger =item PERL_VMS_EXCEPTION_DEBUG =item Command line =over 4 =item I/O redirection and backgrounding =item Command line switches -i, -S, -u =back =item Perl functions File tests, backticks, binmode FILEHANDLE, crypt PLAINTEXT, USER, die, dump, exec LIST, fork, getpwent, getpwnam, getpwuid, gmtime, kill, qx//, select (system call), stat EXPR, system LIST, time, times, unlink LIST, utime LIST, waitpid PID,FLAGS =item Perl variables %ENV, CRTL_ENV, CLISYM_[LOCAL], Any other string, $!, $^E, $?, $| =item Standard modules with VMS-specific differences =over 4 =item SDBM_File =back =item Revision date =item AUTHOR =back =head2 perlvos - Perl for Stratus VOS =over 4 =item SYNOPSIS =item BUILDING PERL FOR VOS =item INSTALLING PERL IN VOS =item USING PERL IN VOS =over 4 =item Restrictions of Perl on VOS =item Handling of underflow and overflow =back =item TEST STATUS =item SUPPORT STATUS =item AUTHOR =item LAST UPDATE =back =head2 perlwin32 - Perl under Windows =over 4 =item SYNOPSIS =item DESCRIPTION L<http://mingw.org>, L<http://mingw-w64.sf.net> =over 4 =item Setting Up Perl on Windows Make, Command Shell, Microsoft Visual C++, Microsoft Visual C++ 2008/2010 Express Edition, Microsoft Visual C++ 2005 Express Edition, Microsoft Visual C++ Toolkit 2003, Microsoft Platform SDK 64-bit Compiler, MinGW release 3 with gcc =item Building =item Testing Perl on Windows =item Installation of Perl on Windows =item Usage Hints for Perl on Windows Environment Variables, File Globbing, Using perl from the command line, Building Extensions, Command-line Wildcard Expansion, Notes on 64-bit Windows =item Running Perl Scripts =item Miscellaneous Things =back =item BUGS AND CAVEATS =item ACKNOWLEDGEMENTS =item AUTHORS Gary Ng E<lt>71564.1743@CompuServe.COME<gt>, Gurusamy Sarathy E<lt>gsar@activestate.comE<gt>, Nick Ing-Simmons E<lt>nick@ing-simmons.netE<gt>, Jan Dubois E<lt>jand@activestate.comE<gt>, Steve Hay E<lt>steve.m.hay@googlemail.comE<gt> =item SEE ALSO =item HISTORY =back =head2 perlboot - This document has been deleted =over 4 =item DESCRIPTION =back =head2 perlbot - This document has been deleted =over 4 =item DESCRIPTION =back =head2 perltodo - Perl TO-DO List =over 4 =item DESCRIPTION =back =head2 perltooc - This document has been deleted =over 4 =item DESCRIPTION =back =head2 perltoot - This document has been deleted =over 4 =item DESCRIPTION =back =head1 PRAGMA DOCUMENTATION =head2 arybase - Set indexing base via $[ =over 4 =item SYNOPSIS =item DESCRIPTION =item HISTORY =item BUGS =item SEE ALSO =back =head2 attributes - get/set subroutine or variable attributes =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item What C<import> does =item Built-in Attributes lvalue, method, locked =item Available Subroutines get, reftype =item Package-specific Attribute Handling FETCH_I<type>_ATTRIBUTES, MODIFY_I<type>_ATTRIBUTES =item Syntax of Attribute Lists =back =item EXPORTS =over 4 =item Default exports =item Available exports =item Export tags defined =back =item EXAMPLES =item MORE EXAMPLES =item SEE ALSO =back =head2 autodie - Replace functions with ones that succeed or die with lexical scope =over 4 =item SYNOPSIS =item DESCRIPTION =item EXCEPTIONS =item CATEGORIES =item FUNCTION SPECIFIC NOTES =over 4 =item flock =item system/exec =back =item GOTCHAS =item DIAGNOSTICS :void cannot be used with lexical scope, No user hints defined for %s =item BUGS =over 4 =item autodie and string eval =item REPORTING BUGS =back =item FEEDBACK =item AUTHOR =item LICENSE =item SEE ALSO =item ACKNOWLEDGEMENTS =back =head2 autodie::exception - Exceptions from autodying functions. =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Common Methods =back =back =over 4 =item Advanced methods =back =over 4 =item SEE ALSO =item LICENSE =item AUTHOR =back =head2 autodie::exception::system - Exceptions from autodying system(). =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item stringify =back =over 4 =item LICENSE =item AUTHOR =back =head2 autodie::hints - Provide hints about user subroutines to autodie =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Introduction =item What are hints? =item Example hints =back =item Manually setting hints from within your program =item Adding hints to your module =item Insisting on hints =back =over 4 =item Diagnostics Attempts to set_hints_for unidentifiable subroutine, fail hints cannot be provided with either scalar or list hints for %s, %s hint missing for %s =item ACKNOWLEDGEMENTS =item AUTHOR =item LICENSE =item SEE ALSO =back =head2 autouse - postpone load of modules until a function is used =over 4 =item SYNOPSIS =item DESCRIPTION =item WARNING =item AUTHOR =item SEE ALSO =back =head2 base - Establish an ISA relationship with base classes at compile time =over 4 =item SYNOPSIS =item DESCRIPTION =item DIAGNOSTICS Base class package "%s" is empty, Class 'Foo' tried to inherit from itself =item HISTORY =item CAVEATS =item SEE ALSO =back =head2 bigint - Transparent BigInteger support for Perl =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item use integer vs. use bigint =item Options a or accuracy, p or precision, t or trace, hex, oct, l, lib, try or only, v or version =item Math Library =item Internal Format =item Sign =item Methods inf(), NaN(), e, PI, bexp(), bpi(), upgrade(), in_effect() =item MATH LIBRARY =item Caveat =back =item CAVEATS in_effect(), hex()/oct() =item MODULES USED =item EXAMPLES =item LICENSE =item SEE ALSO =item AUTHORS =back =head2 bignum - Transparent BigNumber support for Perl =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Options a or accuracy, p or precision, t or trace, l or lib, hex, oct, v or version =item Methods =item Caveats inf(), NaN(), e, PI(), bexp(), bpi(), upgrade(), in_effect() =item Math Library =item INTERNAL FORMAT =item SIGN =back =item CAVEATS in_effect(), hex()/oct() =item MODULES USED =item EXAMPLES =item LICENSE =item SEE ALSO =item AUTHORS =back =head2 bigrat - Transparent BigNumber/BigRational support for Perl =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Modules Used =item Math Library =item Sign =item Methods inf(), NaN(), e, PI, bexp(), bpi(), upgrade(), in_effect() =item MATH LIBRARY =item Caveat =item Options a or accuracy, p or precision, t or trace, l or lib, hex, oct, v or version =back =item CAVEATS in_effect(), hex()/oct() =item EXAMPLES =item LICENSE =item SEE ALSO =item AUTHORS =back =head2 blib - Use MakeMaker's uninstalled version of a package =over 4 =item SYNOPSIS =item DESCRIPTION =item BUGS =item AUTHOR =back =head2 bytes - Perl pragma to force byte semantics rather than character semantics =over 4 =item NOTICE =item SYNOPSIS =item DESCRIPTION =item LIMITATIONS =item SEE ALSO =back =head2 charnames - access to Unicode character names and named character sequences; also define character names =over 4 =item SYNOPSIS =item DESCRIPTION =item LOOSE MATCHES =item ALIASES =item CUSTOM ALIASES =item charnames::string_vianame(I<name>) =item charnames::vianame(I<name>) =item charnames::viacode(I<code>) =item CUSTOM TRANSLATORS =item BUGS =back =head2 constant - Perl pragma to declare constants =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTES =over 4 =item List constants =item Defining multiple constants at once =item Magic constants =back =item TECHNICAL NOTES =item CAVEATS =item SEE ALSO =item BUGS =item AUTHORS =item COPYRIGHT & LICENSE =back =head2 deprecate - Perl pragma for deprecating the core version of a module =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item EXPORT =back =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 diagnostics, splain - produce verbose warning diagnostics =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item The C<diagnostics> Pragma =item The I<splain> Program =back =item EXAMPLES =item INTERNALS =item BUGS =item AUTHOR =back =head2 encoding - allows you to write your script in non-ascii or non-utf8 =over 4 =item SYNOPSIS =item ABSTRACT =over 4 =item Literal Conversions =item PerlIO layers for C<STD(IN|OUT)> =item Implicit upgrading for byte strings =item Side effects =back =item FEATURES THAT REQUIRE 5.8.1 "NON-EUC" doublebyte encodings, tr//, DATA pseudo-filehandle =item USAGE use encoding [I<ENCNAME>] ;, use encoding I<ENCNAME> [ STDIN =E<gt> I<ENCNAME_IN> ...] ;, use encoding I<ENCNAME> Filter=E<gt>1;, no encoding; =item The Filter Option =over 4 =item Filter-related changes at Encode version 1.87 =back =item CAVEATS =over 4 =item NOT SCOPED =item DO NOT MIX MULTIPLE ENCODINGS =item tr/// with ranges Legend of characters above =back =item EXAMPLE - Greekperl =item KNOWN PROBLEMS literals in regex that are longer than 127 bytes, EBCDIC, format, Thread safety =over 4 =item The Logic of :locale =back =item HISTORY =item SEE ALSO =back =head2 encoding::warnings - Warn on implicit encoding conversions =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =over 4 =item Overview of the problem =item Detecting the problem =item Solving the problem Upgrade both sides to unicode-strings, Downgrade both sides to byte-strings, Specify the encoding for implicit byte-string upgrading, PerlIO layers for B<STDIN> and B<STDOUT>, Literal conversions, Implicit upgrading for byte-strings =back =item CAVEATS =back =over 4 =item SEE ALSO =item AUTHORS =item COPYRIGHT =back =head2 feature - Perl pragma to enable new features =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Lexical effect =item C<no feature> =back =item AVAILABLE FEATURES =over 4 =item The 'say' feature =item The 'state' feature =item The 'switch' feature =item The 'unicode_strings' feature =item The 'unicode_eval' and 'evalbytes' features =item The 'current_sub' feature =item The 'array_base' feature =item The 'fc' feature =back =item FEATURE BUNDLES =item IMPLICIT LOADING =back =head2 fields - compile-time class fields =over 4 =item SYNOPSIS =item DESCRIPTION new, phash =item SEE ALSO =back =head2 filetest - Perl pragma to control the filetest permission operators =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Consider this carefully =item The "access" sub-pragma =item Limitation with regard to C<_> =back =back =head2 if - C<use> a Perl module if a condition holds =over 4 =item SYNOPSIS =item DESCRIPTION =item BUGS =item AUTHOR =back =head2 inc::latest - use modules bundled in inc/ if they are newer than installed ones =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Special notes on bundling =back =item USAGE =over 4 =item Author-mode loaded_modules(), write(), bundle_module() =item As bundled in inc/ =back =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 integer - Perl pragma to use integer arithmetic instead of floating point =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 less - perl pragma to request less of something =over 4 =item SYNOPSIS =item DESCRIPTION =item FOR MODULE AUTHORS =over 4 =item C<< BOOLEAN = less->of( FEATURE ) >> =item C<< FEATURES = less->of() >> =back =item CAVEATS This probably does nothing, This works only on 5.10+ =back =head2 lib - manipulate @INC at compile time =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Adding directories to @INC =item Deleting directories from @INC =item Restoring original @INC =back =item CAVEATS =item NOTES =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 locale - Perl pragma to use or avoid POSIX locales for built-in operations =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 mro - Method Resolution Order =over 4 =item SYNOPSIS =item DESCRIPTION =item OVERVIEW =item The C3 MRO =over 4 =item What is C3? =item How does C3 work =back =item Functions =over 4 =item mro::get_linear_isa($classname[, $type]) =item mro::set_mro ($classname, $type) =item mro::get_mro($classname) =item mro::get_isarev($classname) =item mro::is_universal($classname) =item mro::invalidate_all_method_caches() =item mro::method_changed_in($classname) =item mro::get_pkg_gen($classname) =item next::method =item next::can =item maybe::next::method =back =item SEE ALSO =over 4 =item The original Dylan paper L<http://www.webcom.com/haahr/dylan/linearization-oopsla96.html> =item Pugs =item Parrot L<http://use.perl.org/~autrijus/journal/25768> =item Python 2.3 MRO related links L<http://www.python.org/2.3/mro.html>, L<http://www.python.org/2.2.2/descrintro.html#mro> =item Class::C3 L<Class::C3> =back =item AUTHOR =back =head2 open - perl pragma to set default PerlIO layers for input and output =over 4 =item SYNOPSIS =item DESCRIPTION =item NONPERLIO FUNCTIONALITY =item IMPLEMENTATION DETAILS =item SEE ALSO =back =head2 ops - Perl pragma to restrict unsafe operations when compiling =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =back =head2 overload - Package for overloading Perl operations =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Fundamentals =item Overloadable Operations C<not>, C<neg>, C<++>, C<-->, I<Assignments>, I<Non-mutators with a mutator variant>, C<int>, I<String, numeric, boolean, and regexp conversions>, I<Iteration>, I<File tests>, I<Matching>, I<Dereferencing>, I<Special> =item Magic Autogeneration =item Special Keys for C<use overload> defined, but FALSE, C<undef>, TRUE =item How Perl Chooses an Operator Implementation =item Losing Overloading =item Inheritance and Overloading Method names in the C<use overload> directive, Overloading of an operation is inherited by derived classes =item Run-time Overloading =item Public Functions overload::StrVal(arg), overload::Overloaded(arg), overload::Method(obj,op) =item Overloading Constants integer, float, binary, q, qr =back =item IMPLEMENTATION =item COOKBOOK =over 4 =item Two-face Scalars =item Two-face References =item Symbolic Calculator =item I<Really> Symbolic Calculator =back =item AUTHOR =item SEE ALSO =item DIAGNOSTICS Odd number of arguments for overload::constant, '%s' is not an overloadable type, '%s' is not a code reference, overload arg '%s' is invalid =item BUGS AND PITFALLS =back =head2 overloading - perl pragma to lexically control overloading =over 4 =item SYNOPSIS =item DESCRIPTION C<no overloading>, C<no overloading @ops>, C<use overloading>, C<use overloading @ops> =back =head2 parent - Establish an ISA relationship with base classes at compile time =over 4 =item SYNOPSIS =item DESCRIPTION =item DIAGNOSTICS Class 'Foo' tried to inherit from itself =item HISTORY =item CAVEATS =item SEE ALSO =item AUTHORS AND CONTRIBUTORS =item MAINTAINER =item LICENSE =back =head2 re - Perl pragma to alter regular expression behaviour =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item 'taint' mode =item 'eval' mode =item '/flags' mode =item 'debug' mode =item 'Debug' mode Compile related options, COMPILE, PARSE, OPTIMISE, TRIEC, DUMP, Execute related options, EXECUTE, MATCH, TRIEE, INTUIT, Extra debugging options, EXTRA, BUFFERS, TRIEM, STATE, STACK, OPTIMISEM, OFFSETS, OFFSETSDBG, Other useful flags, ALL, All, MORE, More =item Exportable Functions is_regexp($ref), regexp_pattern($ref), regmust($ref), regname($name,$all), regnames($all), regnames_count() =back =item SEE ALSO =back =head2 sigtrap - Perl pragma to enable simple signal handling =over 4 =item SYNOPSIS =item DESCRIPTION =item OPTIONS =over 4 =item SIGNAL HANDLERS B<stack-trace>, B<die>, B<handler> I<your-handler> =item SIGNAL LISTS B<normal-signals>, B<error-signals>, B<old-interface-signals> =item OTHER B<untrapped>, B<any>, I<signal>, I<number> =back =item EXAMPLES =back =head2 sort - perl pragma to control sort() behaviour =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEATS =back =head2 strict - Perl pragma to restrict unsafe constructs =over 4 =item SYNOPSIS =item DESCRIPTION C<strict refs>, C<strict vars>, C<strict subs> =item HISTORY =back =head2 subs - Perl pragma to predeclare sub names =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 threads - Perl interpreter-based threads =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION $thr = threads->create(FUNCTION, ARGS), $thr->join(), $thr->detach(), threads->detach(), threads->self(), $thr->tid(), threads->tid(), "$thr", threads->object($tid), threads->yield(), threads->list(), threads->list(threads::all), threads->list(threads::running), threads->list(threads::joinable), $thr1->equal($thr2), async BLOCK;, $thr->error(), $thr->_handle(), threads->_handle() =item EXITING A THREAD threads->exit(), threads->exit(status), die(), exit(status), use threads 'exit' => 'threads_only', threads->create({'exit' => 'thread_only'}, ...), $thr->set_thread_exit_only(boolean), threads->set_thread_exit_only(boolean) =item THREAD STATE $thr->is_running(), $thr->is_joinable(), $thr->is_detached(), threads->is_detached() =item THREAD CONTEXT =over 4 =item Explicit context =item Implicit context =item $thr->wantarray() =item threads->wantarray() =back =item THREAD STACK SIZE threads->get_stack_size();, $size = $thr->get_stack_size();, $old_size = threads->set_stack_size($new_size);, use threads ('stack_size' => VALUE);, $ENV{'PERL5_ITHREADS_STACK_SIZE'}, threads->create({'stack_size' => VALUE}, FUNCTION, ARGS), $thr2 = $thr1->create(FUNCTION, ARGS) =item THREAD SIGNALLING $thr->kill('SIG...'); =item WARNINGS Perl exited with active threads:, Thread creation failed: pthread_create returned #, Thread # terminated abnormally: .., Using minimum thread stack size of #, Thread creation failed: pthread_attr_setstacksize(I<SIZE>) returned 22 =item ERRORS This Perl not built to support threads, Cannot change stack size of an existing thread, Cannot signal threads without safe signals, Unrecognized signal name: .. =item BUGS AND LIMITATIONS Thread-safe modules, Using non-thread-safe modules, Memory consumption, Current working directory, Environment variables, Catching signals, Parent-child threads, Creating threads inside special blocks, Unsafe signals, Perl has been built with C<PERL_OLD_SIGNALS> (see C<perl -V>), The environment variable C<PERL_SIGNALS> is set to C<unsafe> (see L<perlrun/"PERL_SIGNALS">), The module L<Perl::Unsafe::Signals> is used, Returning closures from threads, Returning objects from threads, END blocks in threads, Open directory handles, Perl Bugs and the CPAN Version of L<threads> =item REQUIREMENTS =item SEE ALSO =item AUTHOR =item LICENSE =item ACKNOWLEDGEMENTS =back =head2 threads::shared - Perl extension for sharing data structures between threads =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item EXPORT =item FUNCTIONS share VARIABLE, shared_clone REF, is_shared VARIABLE, lock VARIABLE, cond_wait VARIABLE, cond_wait CONDVAR, LOCKVAR, cond_timedwait VARIABLE, ABS_TIMEOUT, cond_timedwait CONDVAR, ABS_TIMEOUT, LOCKVAR, cond_signal VARIABLE, cond_broadcast VARIABLE =item OBJECTS =item NOTES =item BUGS AND LIMITATIONS =item SEE ALSO =item AUTHOR =item LICENSE =back =head2 utf8 - Perl pragma to enable/disable UTF-8 (or UTF-EBCDIC) in source code =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Utility functions $num_octets = utf8::upgrade($string), $success = utf8::downgrade($string[, FAIL_OK]), utf8::encode($string), $success = utf8::decode($string), $flag = utf8::is_utf8(STRING), $flag = utf8::valid(STRING) =back =item BUGS =item SEE ALSO =back =head2 vars - Perl pragma to predeclare global variable names (obsolete) =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 version - Perl extension for Version Objects =over 4 =item SYNOPSIS =item DESCRIPTION =item TYPES OF VERSION OBJECTS Decimal Versions, Dotted Decimal Versions =item DECLARING VERSIONS =over 4 =item How to convert a module from decimal to dotted-decimal =item How to C<declare()> a dotted-decimal version =back =item PARSING AND COMPARING VERSIONS =over 4 =item How to C<parse()> a version =item How to check for a legal version string C<is_lax()>, C<is_strict()> =item How to compare version objects =back =item OBJECT METHODS =over 4 =item is_alpha() =item is_qv() =item normal() =item numify() =item stringify() =back =item EXPORTED FUNCTIONS =over 4 =item qv() =item is_lax() =item is_strict() =back =item AUTHOR =item SEE ALSO =back =head2 version::Internals - Perl extension for Version Objects =over 4 =item DESCRIPTION =item WHAT IS A VERSION? Decimal Versions, Dotted-Decimal Versions =over 4 =item Decimal Versions =item Dotted-Decimal Versions =item Alpha Versions =item Regular Expressions for Version Parsing C<$version::LAX>, C<$version::STRICT>, v1.234.5 =back =item IMPLEMENTATION DETAILS =over 4 =item Equivalence between Decimal and Dotted-Decimal Versions =item Quoting Rules =item What about v-strings? =item Version Object Internals original, qv, alpha, version =item Replacement UNIVERSAL::VERSION =back =item USAGE DETAILS =over 4 =item Using modules that use version.pm Decimal versions always work, Dotted-Decimal version work sometimes =item Object Methods new(), qv(), Normal Form, Numification, Stringification, Comparison operators, Logical Operators =back =item AUTHOR =item SEE ALSO =back =head2 vmsish - Perl pragma to control VMS-specific language features =over 4 =item SYNOPSIS =item DESCRIPTION C<vmsish status>, C<vmsish exit>, C<vmsish time>, C<vmsish hushed> =back =head2 warnings - Perl pragma to control optional warnings =over 4 =item SYNOPSIS =item DESCRIPTION use warnings::register, warnings::enabled(), warnings::enabled($category), warnings::enabled($object), warnings::fatal_enabled(), warnings::fatal_enabled($category), warnings::fatal_enabled($object), warnings::warn($message), warnings::warn($category, $message), warnings::warn($object, $message), warnings::warnif($message), warnings::warnif($category, $message), warnings::warnif($object, $message), warnings::register_categories(@names) =back =head2 warnings::register - warnings import function =over 4 =item SYNOPSIS =item DESCRIPTION =back =head1 MODULE DOCUMENTATION =head2 AnyDBM_File - provide framework for multiple DBMs =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item DBM Comparisons [0], [1], [2], [3] =back =item SEE ALSO =back =head2 App::Cpan - easily interact with CPAN from the command line =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Options -a, -A module [ module ... ], -c module, -C module [ module ... ], -D module [ module ... ], -f, -F, -g module [ module ... ], -G module [ module ... ], -h, -i, -j Config.pm, -J, -l, -L author [ author ... ], -m, -O, -t, -r, -u, -v =item Examples =item Methods =back =back run() =over 4 =item EXIT VALUES =item TO DO =item BUGS =item SEE ALSO =item SOURCE AVAILABILITY =item CREDITS =item AUTHOR =item COPYRIGHT =back =head2 App::Prove - Implements the C<prove> command. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =back =over 4 =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Attributes C<archive>, C<argv>, C<backwards>, C<blib>, C<color>, C<directives>, C<dry>, C<exec>, C<extensions>, C<failures>, C<comments>, C<formatter>, C<harness>, C<ignore_exit>, C<includes>, C<jobs>, C<lib>, C<merge>, C<modules>, C<parse>, C<plugins>, C<quiet>, C<really_quiet>, C<recurse>, C<rules>, C<show_count>, C<show_help>, C<show_man>, C<show_version>, C<shuffle>, C<state>, C<state_class>, C<taint_fail>, C<taint_warn>, C<test_args>, C<timer>, C<verbose>, C<warnings_fail>, C<warnings_warn>, C<tapversion>, C<trap> =back =over 4 =item PLUGINS =over 4 =item Sample Plugin =back =item SEE ALSO =back =head2 App::Prove::State - State storage for the C<prove> command. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =back =over 4 =item METHODS =over 4 =item Class Methods C<store>, C<extensions> (optional), C<result_class> (optional) =back =back =over 4 =item C<result_class> =back =over 4 =item C<extensions> =back =over 4 =item C<results> =back =over 4 =item C<commit> =back =over 4 =item Instance Methods C<last>, C<failed>, C<passed>, C<all>, C<hot>, C<todo>, C<slow>, C<fast>, C<new>, C<old>, C<save> =back =head2 App::Prove::State::Result - Individual test suite results. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =back =over 4 =item METHODS =over 4 =item Class Methods =back =back =over 4 =item C<state_version> =back =over 4 =item C<test_class> =back =head2 App::Prove::State::Result::Test - Individual test results. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =back =over 4 =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Instance Methods =back =head2 Archive::Extract - A generic archive extracting mechanism =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item METHODS =over 4 =item $ae = Archive::Extract->new(archive => '/path/to/archive',[type => TYPE]) tar, tgz, gz, Z, zip, bz2, tbz, lzma, xz, txz =back =back =over 4 =item $ae->extract( [to => '/output/path'] ) $ae->extract_path, $ae->files =back =over 4 =item ACCESSORS =over 4 =item $ae->error([BOOL]) =item $ae->extract_path =item $ae->files =item $ae->archive =item $ae->type =item $ae->types =back =back =over 4 =item $ae->is_tgz =item $ae->is_tar =item $ae->is_gz =item $ae->is_Z =item $ae->is_zip =item $ae->is_lzma =item $ae->is_xz =back =over 4 =item $ae->bin_tar =item $ae->bin_gzip =item $ae->bin_unzip =item $ae->bin_unlzma =item $ae->bin_unxz =back =over 4 =item $bool = $ae->have_old_bunzip2 =back =over 4 =item debug( MESSAGE ) =back =over 4 =item HOW IT WORKS =item CAVEATS =over 4 =item File Extensions =item Supporting Very Large Files =item Bunzip2 support of arbitrary extensions. =back =item GLOBAL VARIABLES =over 4 =item $Archive::Extract::DEBUG =item $Archive::Extract::WARN =item $Archive::Extract::PREFER_BIN =back =item TODO / CAVEATS Mime magic support, Thread safety =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 Archive::Tar - module for manipulations of tar archives =over 4 =item SYNOPSIS =item DESCRIPTION =item Object Methods =over 4 =item Archive::Tar->new( [$file, $compressed] ) =back =back =over 4 =item $tar->read ( $filename|$handle, [$compressed, {opt => 'val'}] ) limit, filter, md5, extract =back =over 4 =item $tar->contains_file( $filename ) =back =over 4 =item $tar->extract( [@filenames] ) =back =over 4 =item $tar->extract_file( $file, [$extract_path] ) =back =over 4 =item $tar->list_files( [\@properties] ) =back =over 4 =item $tar->get_files( [@filenames] ) =back =over 4 =item $tar->get_content( $file ) =back =over 4 =item $tar->replace_content( $file, $content ) =back =over 4 =item $tar->rename( $file, $new_name ) =back =over 4 =item $tar->chmod( $file, $mode ) =back =over 4 =item $tar->chown( $file, $uname [, $gname] ) =back =over 4 =item $tar->remove (@filenamelist) =back =over 4 =item $tar->clear =back =over 4 =item $tar->write ( [$file, $compressed, $prefix] ) =back =over 4 =item $tar->add_files( @filenamelist ) =back =over 4 =item $tar->add_data ( $filename, $data, [$opthashref] ) FILE, HARDLINK, SYMLINK, CHARDEV, BLOCKDEV, DIR, FIFO, SOCKET =back =over 4 =item $tar->error( [$BOOL] ) =back =over 4 =item $tar->setcwd( $cwd ); =back =over 4 =item Class Methods =over 4 =item Archive::Tar->create_archive($file, $compressed, @filelist) =back =back =over 4 =item Archive::Tar->iter( $filename, [ $compressed, {opt => $val} ] ) =back =over 4 =item Archive::Tar->list_archive($file, $compressed, [\@properties]) =back =over 4 =item Archive::Tar->extract_archive($file, $compressed) =back =over 4 =item $bool = Archive::Tar->has_io_string =back =over 4 =item $bool = Archive::Tar->has_perlio =back =over 4 =item $bool = Archive::Tar->has_zlib_support =back =over 4 =item $bool = Archive::Tar->has_bzip2_support =back =over 4 =item Archive::Tar->can_handle_compressed_files =back =over 4 =item GLOBAL VARIABLES =over 4 =item $Archive::Tar::FOLLOW_SYMLINK =item $Archive::Tar::CHOWN =item $Archive::Tar::CHMOD =item $Archive::Tar::SAME_PERMISSIONS =item $Archive::Tar::DO_NOT_USE_PREFIX =item $Archive::Tar::DEBUG =item $Archive::Tar::WARN =item $Archive::Tar::error =item $Archive::Tar::INSECURE_EXTRACT_MODE =item $Archive::Tar::HAS_PERLIO =item $Archive::Tar::HAS_IO_STRING =item $Archive::Tar::ZERO_PAD_NUMBERS =back =item FAQ What's the minimum perl version required to run Archive::Tar?, Isn't Archive::Tar slow?, Isn't Archive::Tar heavier on memory than /bin/tar?, Can you lazy-load data instead?, How much memory will an X kb tar file need?, What do you do with unsupported filetypes in an archive?, I'm using WinZip, or some other non-POSIX client, and files are not being extracted properly!, How do I extract only files that have property X from an archive?, How do I access .tar.Z files?, How do I handle Unicode strings? =item CAVEATS =item TODO Check if passed in handles are open for read/write, Allow archives to be passed in as string, Facilitate processing an opened filehandle of a compressed archive =item SEE ALSO The GNU tar specification, The PAX format specification, A comparison of GNU and POSIX tar standards; C<http://www.delorie.com/gnu/docs/tar/tar_114.html>, GNU tar intends to switch to POSIX compatibility, A Comparison between various tar implementations =item AUTHOR =item ACKNOWLEDGEMENTS =item COPYRIGHT =back =head2 Archive::Tar::File - a subclass for in-memory extracted file from Archive::Tar =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Accessors name, mode, uid, gid, size, mtime, chksum, type, linkname, magic, version, uname, gname, devmajor, devminor, prefix, raw =back =item Methods =over 4 =item Archive::Tar::File->new( file => $path ) =item Archive::Tar::File->new( data => $path, $data, $opt ) =item Archive::Tar::File->new( chunk => $chunk ) =back =back =over 4 =item $bool = $file->extract( [ $alternative_name ] ) =back =over 4 =item $path = $file->full_path =back =over 4 =item $bool = $file->validate =back =over 4 =item $bool = $file->has_content =back =over 4 =item $content = $file->get_content =back =over 4 =item $cref = $file->get_content_by_ref =back =over 4 =item $bool = $file->replace_content( $content ) =back =over 4 =item $bool = $file->rename( $new_name ) =back =over 4 =item $bool = $file->chmod $mode) =back =over 4 =item $bool = $file->chown( $user [, $group]) =back =over 4 =item Convenience methods $file->is_file, $file->is_dir, $file->is_hardlink, $file->is_symlink, $file->is_chardev, $file->is_blockdev, $file->is_fifo, $file->is_socket, $file->is_longlink, $file->is_label, $file->is_unknown =back =head2 Attribute::Handlers - Simpler definition of attribute handlers =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION [0], [1], [2], [3], [4], [5], [6], [7] =over 4 =item Typed lexicals =item Type-specific attribute handlers =item Non-interpretive attribute handlers =item Phase-specific attribute handlers =item Attributes as C<tie> interfaces =back =item EXAMPLES =item UTILITY FUNCTIONS findsym =item DIAGNOSTICS C<Bad attribute type: ATTR(%s)>, C<Attribute handler %s doesn't handle %s attributes>, C<Declaration of %s attribute in package %s may clash with future reserved word>, C<Can't have two ATTR specifiers on one subroutine>, C<Can't autotie a %s>, C<Internal error: %s symbol went missing>, C<Won't be able to apply END handler> =item AUTHOR =item BUGS =item COPYRIGHT AND LICENSE =back =head2 AutoLoader - load subroutines only on demand =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Subroutine Stubs =item Using B<AutoLoader>'s AUTOLOAD Subroutine =item Overriding B<AutoLoader>'s AUTOLOAD Subroutine =item Package Lexicals =item Not Using AutoLoader =item B<AutoLoader> vs. B<SelfLoader> =back =item CAVEATS =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 AutoSplit - split a package for autoloading =over 4 =item SYNOPSIS =item DESCRIPTION $keep, $check, $modtime =over 4 =item Multiple packages =back =item DIAGNOSTICS =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 B - The Perl Compiler Backend =over 4 =item SYNOPSIS =item DESCRIPTION =item OVERVIEW =item Utility Functions =over 4 =item Functions Returning C<B::SV>, C<B::AV>, C<B::HV>, and C<B::CV> objects sv_undef, sv_yes, sv_no, svref_2object(SVREF), amagic_generation, init_av, check_av, unitcheck_av, begin_av, end_av, comppadlist, regex_padav, main_cv =item Functions for Examining the Symbol Table walksymtable(SYMREF, METHOD, RECURSE, PREFIX) =item Functions Returning C<B::OP> objects or for walking op trees main_root, main_start, walkoptree(OP, METHOD), walkoptree_debug(DEBUG) =item Miscellaneous Utility Functions ppname(OPNUM), hash(STR), cast_I32(I), minus_c, cstring(STR), perlstring(STR), class(OBJ), threadsv_names =item Exported utility variables @optype, @specialsv_name =back =item OVERVIEW OF CLASSES =over 4 =item SV-RELATED CLASSES =item B::SV Methods REFCNT, FLAGS, object_2svref =item B::IV Methods IV, IVX, UVX, int_value, needs64bits, packiv =item B::NV Methods NV, NVX =item B::RV Methods RV =item B::PV Methods PV, RV, PVX, CUR, LEN =item B::PVMG Methods MAGIC, SvSTASH =item B::MAGIC Methods MOREMAGIC, precomp, PRIVATE, TYPE, FLAGS, OBJ, PTR, REGEX =item B::PVLV Methods TARGOFF, TARGLEN, TYPE, TARG =item B::BM Methods USEFUL, PREVIOUS, RARE, TABLE =item B::GV Methods is_empty, NAME, SAFENAME, STASH, SV, IO, FORM, AV, HV, EGV, CV, CVGEN, LINE, FILE, FILEGV, GvREFCNT, FLAGS =item B::IO Methods LINES, PAGE, PAGE_LEN, LINES_LEFT, TOP_NAME, TOP_GV, FMT_NAME, FMT_GV, BOTTOM_NAME, BOTTOM_GV, SUBPROCESS, IoTYPE, IoFLAGS, IsSTD =item B::AV Methods FILL, MAX, ARRAY, ARRAYelt, OFF, AvFLAGS =item B::CV Methods STASH, START, ROOT, GV, FILE, DEPTH, PADLIST, OUTSIDE, OUTSIDE_SEQ, XSUB, XSUBANY, CvFLAGS, const_sv =item B::HV Methods FILL, MAX, KEYS, RITER, NAME, ARRAY, PMROOT =item OP-RELATED CLASSES =item B::OP Methods next, sibling, name, ppaddr, desc, targ, type, opt, flags, private, spare =item B::UNOP METHOD first =item B::BINOP METHOD last =item B::LOGOP METHOD other =item B::LISTOP METHOD children =item B::PMOP Methods pmreplroot, pmreplstart, pmnext, pmflags, extflags, precomp, pmoffset =item B::SVOP METHOD sv, gv =item B::PADOP METHOD padix =item B::PVOP METHOD pv =item B::LOOP Methods redoop, nextop, lastop =item B::COP Methods label, stash, stashpv, stashlen, file, cop_seq, arybase, line, warnings, io, hints, hints_hash =back =item AUTHOR =back =head2 B::Concise - Walk Perl syntax tree, printing concise info about ops =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLE =item OPTIONS =over 4 =item Options for Opcode Ordering B<-basic>, B<-exec>, B<-tree> =item Options for Line-Style B<-concise>, B<-terse>, B<-linenoise>, B<-debug>, B<-env> =item Options for tree-specific formatting B<-compact>, B<-loose>, B<-vt>, B<-ascii> =item Options controlling sequence numbering B<-base>I<n>, B<-bigendian>, B<-littleendian> =item Other options B<-src>, B<-stash="somepackage">, B<-main>, B<-nomain>, B<-nobanner>, B<-banner>, B<-banneris> => subref =item Option Stickiness =back =item ABBREVIATIONS =over 4 =item OP class abbreviations =item OP flags abbreviations =back =item FORMATTING SPECIFICATIONS =over 4 =item Special Patterns B<(x(>I<exec_text>B<;>I<basic_text>B<)x)>, B<(*(>I<text>B<)*)>, B<(*(>I<text1>B<;>I<text2>B<)*)>, B<(?(>I<text1>B<#>I<var>I<Text2>B<)?)>, B<~> =item # Variables B<#>I<var>, B<#>I<var>I<N>, B<#>I<Var>, B<#addr>, B<#arg>, B<#class>, B<#classsym>, B<#coplabel>, B<#exname>, B<#extarg>, B<#firstaddr>, B<#flags>, B<#flagval>, B<#hints>, B<#hintsval>, B<#hyphseq>, B<#label>, B<#lastaddr>, B<#name>, B<#NAME>, B<#next>, B<#nextaddr>, B<#noise>, B<#private>, B<#privval>, B<#seq>, B<#seqnum>, B<#opt>, B<#sibaddr>, B<#svaddr>, B<#svclass>, B<#svval>, B<#targ>, B<#targarg>, B<#targarglife>, B<#typenum> =back =item One-Liner Command tips perl -MO=Concise,bar foo.pl, perl -MDigest::MD5=md5 -MO=Concise,md5 -e1, perl -MPOSIX -MO=Concise,_POSIX_ARG_MAX -e1, perl -MPOSIX -MO=Concise,a -e 'print _POSIX_SAVED_IDS', perl -MPOSIX -MO=Concise,a -e 'sub a{_POSIX_SAVED_IDS}', perl -MB::Concise -e 'B::Concise::compile("-exec","-src", \%B::Concise::)->()' =item Using B::Concise outside of the O framework =over 4 =item Example: Altering Concise Renderings =item set_style() =item set_style_standard($name) =item add_style () =item add_callback () =item Running B::Concise::compile() =item B::Concise::reset_sequence() =item Errors =back =item AUTHOR =back =head2 B::Debug - Walk Perl syntax tree, printing debug info about ops =over 4 =item SYNOPSIS =item DESCRIPTION =item OPTIONS =item AUTHOR =item LICENSE =back =head2 B::Deparse - Perl compiler backend to produce perl code =over 4 =item SYNOPSIS =item DESCRIPTION =item OPTIONS B<-d>, B<-f>I<FILE>, B<-l>, B<-p>, B<-P>, B<-q>, B<-s>I<LETTERS>, B<C>, B<i>I<NUMBER>, B<T>, B<v>I<STRING>B<.>, B<-x>I<LEVEL> =item USING B::Deparse AS A MODULE =over 4 =item Synopsis =item Description =item new =item ambient_pragmas strict, $[, bytes, utf8, integer, re, warnings, hint_bits, warning_bits, %^H =item coderef2text =back =item BUGS =item AUTHOR =back =head2 B::Lint - Perl lint =over 4 =item SYNOPSIS =item DESCRIPTION =item OPTIONS AND LINT CHECKS B<magic-diamond>, B<context>, B<implicit-read> and B<implicit-write>, B<bare-subs>, B<dollar-underscore>, B<private-names>, B<undefined-subs>, B<regexp-variables>, B<all>, B<none> =item NON LINT-CHECK OPTIONS B<-u Package> =item EXTENDING LINT =item TODO while(<FH>) stomps $_, strict oo, unchecked system calls, more tests, validate against older perls =item BUGS =item AUTHOR =item ACKNOWLEDGEMENTS =back =head2 B::Lint::Debug - Adds debugging stringification to B:: =over 4 =item DESCRIPTION =back =head2 B::Showlex - Show lexical variables used in functions or files =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLES =over 4 =item OPTIONS =back =item SEE ALSO =item TODO =item AUTHOR =back =head2 B::Terse - Walk Perl syntax tree, printing terse info about ops =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR =back =head2 B::Xref - Generates cross reference reports for Perl programs =over 4 =item SYNOPSIS =item DESCRIPTION i, &, s, r =item OPTIONS C<-oFILENAME>, C<-r>, C<-d>, C<-D[tO]> =item BUGS =item AUTHOR =back =head2 Benchmark - benchmark running times of Perl code =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Methods new, debug, iters =item Standard Exports timeit(COUNT, CODE), timethis ( COUNT, CODE, [ TITLE, [ STYLE ]] ), timethese ( COUNT, CODEHASHREF, [ STYLE ] ), timediff ( T1, T2 ), timestr ( TIMEDIFF, [ STYLE, [ FORMAT ] ] ) =item Optional Exports clearcache ( COUNT ), clearallcache ( ), cmpthese ( COUNT, CODEHASHREF, [ STYLE ] ), cmpthese ( RESULTSHASHREF, [ STYLE ] ), countit(TIME, CODE), disablecache ( ), enablecache ( ), timesum ( T1, T2 ) =item :hireswallclock =back =item NOTES =item EXAMPLES =item INHERITANCE =item CAVEATS =item SEE ALSO =item AUTHORS =item MODIFICATION HISTORY =back =head2 CGI - Handle Common Gateway Interface requests and responses =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item PROGRAMMING STYLE =item CALLING CGI.PM ROUTINES =item CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE): =item CREATING A NEW QUERY OBJECT FROM AN INPUT FILE =item FETCHING A LIST OF KEYWORDS FROM THE QUERY: =item FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT: =item FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER: =item SETTING THE VALUE(S) OF A NAMED PARAMETER: =item APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER: =item IMPORTING ALL PARAMETERS INTO A NAMESPACE: =item DELETING A PARAMETER COMPLETELY: =item DELETING ALL PARAMETERS: =item HANDLING NON-URLENCODED ARGUMENTS =item DIRECT ACCESS TO THE PARAMETER LIST: =item FETCHING THE PARAMETER LIST AS A HASH: =item SAVING THE STATE OF THE SCRIPT TO A FILE: =item RETRIEVING CGI ERRORS =item USING THE FUNCTION-ORIENTED INTERFACE B<:cgi>, B<:form>, B<:html2>, B<:html3>, B<:html4>, B<:netscape>, B<:html>, B<:standard>, B<:all> =item PRAGMAS -any, -compile, -nosticky, -tabindex, -no_undef_params, -no_xhtml, -utf8, -nph, -newstyle_urls, -oldstyle_urls, -autoload, -no_debug, -debug, -private_tempfiles =item SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS 1. start_table() (generates a <table> tag), 2. end_table() (generates a </table> tag), 3. start_ul() (generates a <ul> tag), 4. end_ul() (generates a </ul> tag) =back =item GENERATING DYNAMIC DOCUMENTS =over 4 =item CREATING A STANDARD HTTP HEADER: =item GENERATING A REDIRECTION HEADER =item CREATING THE HTML DOCUMENT HEADER B<Parameters:>, 4, 5, 6.. =item ENDING THE HTML DOCUMENT: =item CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION: =item OBTAINING THE SCRIPT'S URL B<-absolute>, B<-relative>, B<-full>, B<-path> (B<-path_info>), B<-query> (B<-query_string>), B<-base>, B<-rewrite> =item MIXING POST AND URL PARAMETERS =back =item CREATING STANDARD HTML ELEMENTS: =over 4 =item PROVIDING ARGUMENTS TO HTML SHORTCUTS =item THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS =item HTML SHORTCUTS AND LIST INTERPOLATION =item NON-STANDARD HTML SHORTCUTS =item AUTOESCAPING HTML $escaped_string = escapeHTML("unescaped string");, $charset = charset([$charset]);, $flag = autoEscape([$flag]); =item PRETTY-PRINTING HTML =back =item CREATING FILL-OUT FORMS: =over 4 =item CREATING AN ISINDEX TAG =item STARTING AND ENDING A FORM B<application/x-www-form-urlencoded>, B<multipart/form-data> =item FORM ELEMENTS B<-name>, B<-value>, B<-values>, B<-tabindex>, B<-id>, B<-override>, B<-onChange>, B<-onFocus>, B<-onBlur>, B<-onMouseOver>, B<-onMouseOut>, B<-onSelect> =item CREATING A TEXT FIELD B<Parameters> =item CREATING A BIG TEXT FIELD =item CREATING A PASSWORD FIELD =item CREATING A FILE UPLOAD FIELD B<Parameters> =item PROCESSING A FILE UPLOAD FIELD =item CREATING A POPUP MENU =item CREATING AN OPTION GROUP =item CREATING A SCROLLING LIST B<Parameters:> =item CREATING A GROUP OF RELATED CHECKBOXES B<Parameters:> =item CREATING A STANDALONE CHECKBOX B<Parameters:> =item CREATING A RADIO BUTTON GROUP B<Parameters:> =item CREATING A SUBMIT BUTTON B<Parameters:> =item CREATING A RESET BUTTON =item CREATING A DEFAULT BUTTON =item CREATING A HIDDEN FIELD B<Parameters:> =item CREATING A CLICKABLE IMAGE BUTTON B<Parameters:>, 3. The third option (-align, optional) is an alignment type, and may be TOP, BOTTOM or MIDDLE =item CREATING A JAVASCRIPT ACTION BUTTON =back =item HTTP COOKIES 1. an expiration time, 2. a domain, 3. a path, 4. a "secure" flag, B<-name>, B<-value>, B<-path>, B<-domain>, B<-expires>, B<-secure> =item WORKING WITH FRAMES 1. Create a <Frameset> document, 2. Specify the destination for the document in the HTTP header, 3. Specify the destination for the document in the <form> tag =item SUPPORT FOR JAVASCRIPT B<onLoad>, B<onUnload>, B<onSubmit>, B<onClick>, B<onChange>, B<onFocus>, B<onBlur>, B<onSelect>, B<onMouseOver>, B<onMouseOut> =item LIMITED SUPPORT FOR CASCADING STYLE SHEETS =item DEBUGGING =over 4 =item DUMPING OUT ALL THE NAME/VALUE PAIRS =back =item FETCHING ENVIRONMENT VARIABLES B<Accept()>, B<raw_cookie()>, B<user_agent()>, B<path_info()>, B<path_translated()>, B<remote_host()>, B<remote_addr()>, B<script_name()> Return the script name as a partial URL, for self-referring scripts, B<referer()>, B<auth_type ()>, B<server_name ()>, B<virtual_host ()>, B<server_port ()>, B<virtual_port ()>, B<server_software ()>, B<remote_user ()>, B<user_name ()>, B<request_method()>, B<content_type()>, B<http()>, B<https()> =item USING NPH SCRIPTS In the B<use> statement, By calling the B<nph()> method:, By using B<-nph> parameters =item Server Push multipart_init(), multipart_start(), multipart_end(), multipart_final() =item Avoiding Denial of Service Attacks B<$CGI::POST_MAX>, B<$CGI::DISABLE_UPLOADS>, B<1. On a script-by-script basis>, B<2. Globally for all scripts> =item COMPATIBILITY WITH CGI-LIB.PL =over 4 =item Cgi-lib functions that are available in CGI.pm =item Cgi-lib functions that are not available in CGI.pm =back =item AUTHOR INFORMATION =item CREDITS Matt Heffron (heffron@falstaff.css.beckman.com), James Taylor (james.taylor@srs.gov), Scott Anguish <sanguish@digifix.com>, Mike Jewell (mlj3u@virginia.edu), Timothy Shimmin (tes@kbs.citri.edu.au), Joergen Haegg (jh@axis.se), Laurent Delfosse (delfosse@delfosse.com), Richard Resnick (applepi1@aol.com), Craig Bishop (csb@barwonwater.vic.gov.au), Tony Curtis (tc@vcpc.univie.ac.at), Tim Bunce (Tim.Bunce@ig.co.uk), Tom Christiansen (tchrist@convex.com), Andreas Koenig (k@franz.ww.TU-Berlin.DE), Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au), Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu), Stephen Dahmen (joyfire@inxpress.net), Ed Jordan (ed@fidalgo.net), David Alan Pisoni (david@cnation.com), Doug MacEachern (dougm@opengroup.org), Robin Houston (robin@oneworld.org), ...and many many more.. =item A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT =item BUGS =item SEE ALSO =back =head2 CGI::Apache - Backward compatibility module for CGI.pm =over 4 =item SYNOPSIS =item ABSTRACT =item DESCRIPTION =item AUTHOR INFORMATION =item BUGS =item SEE ALSO =back =head2 CGI::Carp, B<CGI::Carp> - CGI routines for writing to the HTTPD (or other) error log =over 4 =item SYNOPSIS =item DESCRIPTION =item REDIRECTING ERROR MESSAGES =item MAKING PERL ERRORS APPEAR IN THE BROWSER WINDOW =over 4 =item Changing the default message =back =item DOING MORE THAN PRINTING A MESSAGE IN THE EVENT OF PERL ERRORS =over 4 =item SUPPRESSING PERL ERRORS APPEARING IN THE BROWSER WINDOW =back =item MAKING WARNINGS APPEAR AS HTML COMMENTS =item OVERRIDING THE NAME OF THE PROGRAM =item AUTHORS =item SEE ALSO =back =head2 CGI::Cookie - Interface to HTTP Cookies =over 4 =item SYNOPSIS =item DESCRIPTION =item USING CGI::Cookie B<1. expiration date>, B<2. domain>, B<3. path>, B<4. secure flag>, B<5. httponly flag> =over 4 =item Creating New Cookies =item Sending the Cookie to the Browser =item Recovering Previous Cookies =item Manipulating Cookies B<name()>, B<value()>, B<domain()>, B<path()>, B<expires()> =back =item AUTHOR INFORMATION =item BUGS =item SEE ALSO =back =head2 CGI::Fast - CGI Interface for Fast CGI =over 4 =item SYNOPSIS =item DESCRIPTION =item OTHER PIECES OF THE PUZZLE =item WRITING FASTCGI PERL SCRIPTS =item INSTALLING FASTCGI SCRIPTS =item USING FASTCGI SCRIPTS AS CGI SCRIPTS =item EXTERNAL FASTCGI SERVER INVOCATION FCGI_SOCKET_PATH, FCGI_LISTEN_QUEUE =item CAVEATS =item AUTHOR INFORMATION =item BUGS =item SEE ALSO =back =head2 CGI::Pretty - module to produce nicely formatted HTML code =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Recommendation for when to use CGI::Pretty =item Tags that won't be formatted =item Customizing the Indenting =back =item AUTHOR =item SEE ALSO =back =head2 CGI::Push - Simple Interface to Server Push =over 4 =item SYNOPSIS =item DESCRIPTION =item USING CGI::Push -next_page, -last_page, -type, -delay, -cookie, -target, -expires, -nph =over 4 =item Heterogeneous Pages =item Changing the Page Delay on the Fly =back =item INSTALLING CGI::Push SCRIPTS =item AUTHOR INFORMATION =item BUGS =item SEE ALSO =back =head2 CGI::Switch - Backward compatibility module for defunct CGI::Switch =over 4 =item SYNOPSIS =item ABSTRACT =item DESCRIPTION =item AUTHOR INFORMATION =item BUGS =item SEE ALSO =back =head2 CGI::Util - Internal utilities used by CGI module =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR INFORMATION =item SEE ALSO =back =head2 CORE - Namespace for Perl's core routines =over 4 =item SYNOPSIS =item DESCRIPTION =item OVERRIDING CORE FUNCTIONS =item AUTHOR =item SEE ALSO =back =head2 CPAN - query, download and build perl modules from CPAN sites =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item CPAN::shell([$prompt, $command]) Starting Interactive Mode Searching for authors, bundles, distribution files and modules, C<get>, C<make>, C<test>, C<install>, C<clean> modules or distributions, C<readme>, C<perldoc>, C<look> module or distribution, C<ls> author, C<ls> globbing_expression, C<failed>, Persistence between sessions, The C<force> and the C<fforce> pragma, Lockfile, Signals =item CPAN::Shell =item autobundle =item hosts =item mkmyconfig =item r [Module|/Regexp/]... =item recent ***EXPERIMENTAL COMMAND*** =item recompile =item report Bundle|Distribution|Module =item smoke ***EXPERIMENTAL COMMAND*** =item upgrade [Module|/Regexp/]... =item The four C<CPAN::*> Classes: Author, Bundle, Module, Distribution =item Integrating local directories =item Redirection =back =item CONFIGURATION completion support, displaying some help: o conf help, displaying current values: o conf [KEY], changing of scalar values: o conf KEY VALUE, changing of list values: o conf KEY SHIFT|UNSHIFT|PUSH|POP|SPLICE|LIST, reverting to saved: o conf defaults, saving the config: o conf commit =over 4 =item Config Variables C<o conf E<lt>scalar optionE<gt>>, C<o conf E<lt>scalar optionE<gt> E<lt>valueE<gt>>, C<o conf E<lt>list optionE<gt>>, C<o conf E<lt>list optionE<gt> [shift|pop]>, C<o conf E<lt>list optionE<gt> [unshift|push|splice] E<lt>listE<gt>>, interactive editing: o conf init [MATCH|LIST] =item CPAN::anycwd($path): Note on config variable getcwd cwd, getcwd, fastcwd, backtickcwd =item Note on the format of the urllist parameter =item The urllist parameter has CD-ROM support =item Maintaining the urllist parameter =item The C<requires> and C<build_requires> dependency declarations =item Configuration for individual distributions (I<Distroprefs>) =item Filenames =item Fallback Data::Dumper and Storable =item Blueprint =item Language Specs comment [scalar], cpanconfig [hash], depends [hash] *** EXPERIMENTAL FEATURE ***, disabled [boolean], features [array] *** EXPERIMENTAL FEATURE ***, goto [string], install [hash], make [hash], match [hash], patches [array], pl [hash], test [hash] =item Processing Instructions args [array], commandline, eexpect [hash], env [hash], expect [array] =item Schema verification with C<Kwalify> =item Example Distroprefs Files =back =item PROGRAMMER'S INTERFACE expand($type,@things), expandany(@things), Programming Examples =over 4 =item Methods in the other Classes CPAN::Author::as_glimpse(), CPAN::Author::as_string(), CPAN::Author::email(), CPAN::Author::fullname(), CPAN::Author::name(), CPAN::Bundle::as_glimpse(), CPAN::Bundle::as_string(), CPAN::Bundle::clean(), CPAN::Bundle::contains(), CPAN::Bundle::force($method,@args), CPAN::Bundle::get(), CPAN::Bundle::inst_file(), CPAN::Bundle::inst_version(), CPAN::Bundle::uptodate(), CPAN::Bundle::install(), CPAN::Bundle::make(), CPAN::Bundle::readme(), CPAN::Bundle::test(), CPAN::Distribution::as_glimpse(), CPAN::Distribution::as_string(), CPAN::Distribution::author, CPAN::Distribution::pretty_id(), CPAN::Distribution::base_id(), CPAN::Distribution::clean(), CPAN::Distribution::containsmods(), CPAN::Distribution::cvs_import(), CPAN::Distribution::dir(), CPAN::Distribution::force($method,@args), CPAN::Distribution::get(), CPAN::Distribution::install(), CPAN::Distribution::install_tested(), CPAN::Distribution::isa_perl(), CPAN::Distribution::look(), CPAN::Distribution::make(), CPAN::Distribution::perldoc(), CPAN::Distribution::prefs(), CPAN::Distribution::prereq_pm(), CPAN::Distribution::readme(), CPAN::Distribution::reports(), CPAN::Distribution::read_yaml(), CPAN::Distribution::test(), CPAN::Distribution::uptodate(), CPAN::Index::force_reload(), CPAN::Index::reload(), CPAN::InfoObj::dump(), CPAN::Module::as_glimpse(), CPAN::Module::as_string(), CPAN::Module::clean(), CPAN::Module::cpan_file(), CPAN::Module::cpan_version(), CPAN::Module::cvs_import(), CPAN::Module::description(), CPAN::Module::distribution(), CPAN::Module::dslip_status(), CPAN::Module::force($method,@args), CPAN::Module::get(), CPAN::Module::inst_file(), CPAN::Module::available_file(), CPAN::Module::inst_version(), CPAN::Module::available_version(), CPAN::Module::install(), CPAN::Module::look(), CPAN::Module::make(), CPAN::Module::manpage_headline(), CPAN::Module::perldoc(), CPAN::Module::readme(), CPAN::Module::reports(), CPAN::Module::test(), CPAN::Module::uptodate(), CPAN::Module::userid() =item Cache Manager =item Bundles =back =item PREREQUISITES =item UTILITIES =over 4 =item Finding packages and VERSION =item Debugging o debug package.., o debug -package.., o debug all, o debug number =item Floppy, Zip, Offline Mode =item Basic Utilities for Programmers has_inst($module), has_usable($module), instance($module) =back =item SECURITY =over 4 =item Cryptographically signed modules =back =item EXPORT =item ENVIRONMENT =item POPULATE AN INSTALLATION WITH LOTS OF MODULES =item WORKING WITH CPAN.pm BEHIND FIREWALLS =over 4 =item Three basic types of firewalls http firewall, ftp firewall, One-way visibility, SOCKS, IP Masquerade =item Configuring lynx or ncftp for going through a firewall =back =item FAQ 1), 2), 3), 4), 5), 6), 7), 8), 9), 10), 11), 12), 13), 14), 15), 16), 17), 18) =item COMPATIBILITY =over 4 =item OLD PERL VERSIONS =item CPANPLUS =item CPANMINUS =back =item SECURITY ADVICE =item BUGS =item AUTHOR =item LICENSE =item TRANSLATIONS =item SEE ALSO =back =head2 CPAN::API::HOWTO - a recipe book for programming with CPAN.pm =over 4 =item RECIPES =over 4 =item What distribution contains a particular module? =item What modules does a particular distribution contain? =back =item SEE ALSO =item LICENSE =item AUTHOR =back =head2 CPAN::Debug - internal debugging for CPAN.pm =over 4 =item LICENSE =back =head2 CPAN::Distroprefs -- read and match distroprefs =over 4 =item SYNOPSIS =item DESCRIPTION =item INTERFACE a CPAN::Distroprefs::Result object, C<undef>, indicating that no prefs files remain to be found =item RESULTS =over 4 =item Common =item Errors =item Successes =back =item PREFS =item LICENSE =back =head2 CPAN::FirstTime - Utility for CPAN::Config file Initialization =over 4 =item SYNOPSIS =item DESCRIPTION =back auto_commit, build_cache, build_dir, build_dir_reuse, build_requires_install_policy, cache_metadata, check_sigs, colorize_output, colorize_print, colorize_warn, colorize_debug, commandnumber_in_prompt, connect_to_internet_ok, ftp_passive, ftpstats_period, ftpstats_size, getcwd, halt_on_failure, histfile, histsize, inactivity_timeout, index_expire, inhibit_startup_message, keep_source_where, load_module_verbosity, makepl_arg, make_arg, make_install_arg, make_install_make_command, mbuildpl_arg, mbuild_arg, mbuild_install_arg, mbuild_install_build_command, pager, prefer_installer, prefs_dir, prerequisites_policy, randomize_urllist, scan_cache, shell, show_unparsable_versions, show_upload_date, show_zero_versions, tar_verbosity, term_is_latin, term_ornaments, test_report, perl5lib_verbosity, prefer_external_tar, trust_test_report_history, use_sqlite, version_timeout, yaml_load_code, yaml_module =over 4 =item LICENSE =back =head2 CPAN::HandleConfig - internal configuration handling for CPAN.pm =over 4 =item C<< CLASS->safe_quote ITEM >> =back =over 4 =item LICENSE =back =head2 CPAN::Kwalify - Interface between CPAN.pm and Kwalify.pm =over 4 =item SYNOPSIS =item DESCRIPTION _validate($schema_name, $data, $file, $doc), yaml($schema_name) =item AUTHOR =item LICENSE =back =head2 CPAN::Meta - the distribution metadata for a CPAN dist =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new =item create =item load_file =item load_yaml_string =item load_json_string =item save =item meta_spec_version =item effective_prereqs =item should_index_file =item should_index_package =item features =item feature =item as_struct =item as_string =back =item STRING DATA =item LIST DATA =item MAP DATA =item CUSTOM DATA =item BUGS =item SEE ALSO =item SUPPORT =over 4 =item Bugs / Feature Requests =item Source Code =back =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 CPAN::Meta::Converter - Convert CPAN distribution metadata structures =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new =item convert =back =item BUGS =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 CPAN::Meta::Feature - an optional feature provided by a CPAN distribution =over 4 =item VERSION =item DESCRIPTION =item METHODS =over 4 =item new =item identifier =item description =item prereqs =back =item BUGS =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 CPAN::Meta::History - history of CPAN Meta Spec changes =over 4 =item VERSION =item DESCRIPTION =item HISTORY =over 4 =item Version 2 =item Version 1.4 =item Version 1.3 =item Version 1.2 =item Version 1.1 =item Version 1.0 =back =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 CPAN::Meta::Prereqs - a set of distribution prerequisites by phase and type =over 4 =item VERSION =item DESCRIPTION =item METHODS =over 4 =item new =item requirements_for =item with_merged_prereqs =item as_string_hash =item is_finalized =item finalize =item clone =back =item BUGS =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 CPAN::Meta::Requirements - a set of version requirements for a CPAN dist =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new =item add_minimum =item add_maximum =item add_exclusion =item exact_version =item add_requirements =item accepts_module =item clear_requirement =item required_modules =item clone =item is_simple =item is_finalized =item finalize =item as_string_hash =item add_string_requirement >= 1.3, <= 1.3, ! 1.3, > 1.3, < 1.3, >= 1.3, ! 1.5, <= 2.0 =item from_string_hash =back =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 CPAN::Meta::Spec - specification for CPAN distribution metadata =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item TERMINOLOGY distribution, module, package, consumer, producer, must, should, may, etc =item DATA TYPES =over 4 =item Boolean =item String =item List =item Map =item License String =item URL =item Version =item Version Range =back =item STRUCTURE =over 4 =item REQUIRED FIELDS version, url, stable, testing, unstable =item OPTIONAL FIELDS file, directory, package, namespace, description, prereqs, file, version, homepage, license, bugtracker, repository =item DEPRECATED FIELDS =back =item VERSION NUMBERS =over 4 =item Version Formats Decimal versions, Dotted-integer versions =item Version Ranges =back =item PREREQUISITES =over 4 =item Prereq Spec configure, build, test, runtime, develop, requires, recommends, suggests, conflicts =item Merging and Resolving Prerequisites =back =item SERIALIZATION =item NOTES FOR IMPLEMENTORS =over 4 =item Extracting Version Numbers from Perl Modules =item Comparing Version Numbers =back =item SEE ALSO =item CONTRIBUTORS =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 CPAN::Meta::Validator - validate CPAN distribution metadata structures =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new =item is_valid =item errors =item Check Methods =item Validator Methods =back =item BUGS =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 CPAN::Meta::YAML - Read and write a subset of YAML for CPAN Meta files =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item SUPPORT =item SEE ALSO =item SUPPORT =over 4 =item Bugs / Feature Requests =item Source Code =back =item AUTHORS =item COPYRIGHT AND LICENSE =back =over 4 =item SYNOPSIS =item DESCRIPTION =back new( LOCAL_FILE_NAME ) continents() countries( [CONTINENTS] ) mirrors( [COUNTRIES] ) get_mirrors_by_countries( [COUNTRIES] ) get_mirrors_by_continents( [CONTINENTS] ) get_countries_by_continents( [CONTINENTS] ) best_mirrors get_n_random_mirrors_by_continents( N, [CONTINENTS] get_mirrors_timings( MIRROR_LIST, SEEN, CALLBACK ); find_best_continents( HASH_REF ); =over 4 =item AUTHOR =item LICENSE =back =head2 CPAN::Nox - Wrapper around CPAN.pm without using any XS module =over 4 =item SYNOPSIS =item DESCRIPTION =item LICENSE =item SEE ALSO =back =head2 CPAN::Queue - internal queue support for CPAN.pm =over 4 =item LICENSE =back =head2 CPAN::Tarzip - internal handling of tar archives for CPAN.pm =over 4 =item LICENSE =back =head2 CPAN::Version - utility functions to compare CPAN versions =over 4 =item SYNOPSIS =item DESCRIPTION =item LICENSE =back =head2 CPANPLUS - API & CLI access to the CPAN mirrors =over 4 =item SYNOPSIS =item DESCRIPTION =item GUIDE TO DOCUMENTATION =over 4 =item GENERAL USAGE =item API REFERENCE =back =back =over 4 =item COMMANDLINE TOOLS =over 4 =item STARTING AN INTERACTIVE SHELL =item CHOOSE A SHELL =item BUILDING PACKAGES =back =item FUNCTIONS =over 4 =item $bool = install( Module::Name | /A/AU/AUTHOR/Module-Name-1.tgz ) =item $where = fetch( Module::Name | /A/AU/AUTHOR/Module-Name-1.tgz ) =item $where = get( Module::Name | /A/AU/AUTHOR/Module-Name-1.tgz ) =item shell() =back =item FAQ =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =item CONTACT INFORMATION Bug reporting: I<bug-cpanplus@rt.cpan.org>, Questions & suggestions: I<bug-cpanplus@rt.cpan.org> =back =head2 CPANPLUS::Backend - programmer's interface to CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =item ENVIRONMENT =item METHODS =over 4 =item $cb = CPANPLUS::Backend->new( [CONFIGURE_OBJ] ) Provide a valid C<CPANPLUS::Configure> object, No arguments =back =back =over 4 =item $href = $cb->module_tree( [@modules_names_list] ) =back =over 4 =item $href = $cb->author_tree( [@author_names_list] ) =back =over 4 =item $conf = $cb->configure_object; =back =over 4 =item $su = $cb->selfupdate_object; =back =over 4 =item @mods = $cb->search( type => TYPE, allow => AREF, [data => AREF, verbose => BOOL] ) =back =over 4 =item $backend_rv = $cb->fetch( modules => \@mods ) =item $backend_rv = $cb->extract( modules => \@mods ) =item $backend_rv = $cb->install( modules => \@mods ) =item $backend_rv = $cb->readme( modules => \@mods ) =item $backend_rv = $cb->files( modules => \@mods ) =item $backend_rv = $cb->distributions( modules => \@mods ) =back =over 4 =item $mod_obj = $cb->parse_module( module => $modname|$distname|$modobj|URI|PATH ) Text::Bastardize, Text-Bastardize, Text/Bastardize.pm, Text-Bastardize-1.06, AYRNIEU/Text-Bastardize, AYRNIEU/Text-Bastardize-1.06, AYRNIEU/Text-Bastardize-1.06.tar.gz, http://example.com/Text-Bastardize-1.06.tar.gz, file:///tmp/Text-Bastardize-1.06.tar.gz, /tmp/Text-Bastardize-1.06, ./Text-Bastardize-1.06 =back =over 4 =item $bool = $cb->reload_indices( [update_source => BOOL, verbose => BOOL] ); =back =over 4 =item $bool = $cb->flush(CACHE_NAME) C<methods>, C<hosts>, C<modules>, C<lib>, C<load>, C<all> =back =over 4 =item @mods = $cb->installed() =back =over 4 =item $bool = $cb->local_mirror([path => '/dir/to/save/to', index_files => BOOL, force => BOOL, verbose => BOOL] ) path, index_files, force, verbose =back =over 4 =item $file = $cb->autobundle([path => OUTPUT_PATH, force => BOOL, verbose => BOOL]) =back =over 4 =item $bool = $cb->save_state =back =over 4 =item CUSTOM MODULE SOURCES =over 4 =item %files = $cb->list_custom_sources =back =back =over 4 =item $local_index = $cb->add_custom_source( uri => URI, [verbose => BOOL] ); =back =over 4 =item $local_index = $cb->remove_custom_source( uri => URI, [verbose => BOOL] ); =back =over 4 =item $bool = $cb->update_custom_source( [remote => URI] ); =back =over 4 =item $file = $cb->write_custom_source_index( path => /path/to/package/root, [to => /path/to/index/file, verbose => BOOL] ); =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 CPANPLUS::Backend::RV - return value objects =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new( ok => BOOL, args => DATA, rv => DATA, [function => $method_name] ) ok, args, rv, function =back =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 CPANPLUS::Config - configuration defaults and heuristics for CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =item CONFIGURATION =back =over 4 =item Section 'conf' hosts =back allow_build_interactivity allow_unknown_prereqs base buildflags cpantest cpantest_mx debug dist_type email enable_custom_sources extractdir fetchdir flush force lib makeflags makemakerflags md5 no_update passive prefer_bin prefer_makefile prereqs shell show_startup_tip signature skiptest storable timeout verbose write_install_log source_engine cpantest_reporter_args =over 4 =item Section 'program' =back editor make pager shell sudo perlwrapper =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 CPANPLUS::Configure - configuration for CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item $Configure = CPANPLUS::Configure->new( load_configs => BOOL ) load_configs =back =back =over 4 =item $bool = $Configure->init( [rescan => BOOL]) =back =over 4 =item can_save( [$config_location] ) =back =over 4 =item $file = $conf->save( [$package_name] ) =back =over 4 =item options( type => TYPE ) =back =over 4 =item ACCESSORS =over 4 =item get_SOMETHING( ITEM, [ITEM, ITEM, ... ] ); =item set_SOMETHING( ITEM => VAL, [ITEM => VAL, ITEM => VAL, ... ] ); =item add_SOMETHING( ITEM => VAL, [ITEM => VAL, ITEM => VAL, ... ] ); set|get_conf, set|get_program, _set|_get_build, _set|_get_source, _set|_get_mirror, _set|_get_fetch =back =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 CPANPLUS::Dist - base class for plugins =over 4 =item SYNOPSIS =item DESCRIPTION =item ACCESSORS parent(), status() =item STATUS ACCESSORS created(), installed(), uninstalled(), dist() =back =over 4 =item $dist = CPANPLUS::Dist::YOUR_DIST_TYPE_HERE->new( module => MODOBJ ); =back =over 4 =item @dists = CPANPLUS::Dist->dist_types; =back =over 4 =item $bool = CPANPLUS::Dist->rescan_dist_types; =back =over 4 =item $bool = CPANPLUS::Dist->has_dist_type( $type ) =back =over 4 =item $bool = $dist->prereq_satisfied( modobj => $modobj, version => $version_spec ) =back =over 4 =item $configure_requires = $dist->find_configure_requires( [file => /path/to/META.yml] ) =back =over 4 =item $bool = $dist->_resolve_prereqs( ... ) =back =head2 CPANPLUS::Dist::Autobundle - distribution class for installation snapshots =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 CPANPLUS::Dist::Base - Base class for custom distribution classes =over 4 =item SYNOPSIS =item DESCRIPTION =item FLOW =item METHODS =back =over 4 =item @subs = $Class->methods =back =over 4 =item $bool = $Class->format_available =back =over 4 =item $bool = $dist->init =back =over 4 =item $bool = $dist->prepare =back =over 4 =item $bool = $dist->create =back =over 4 =item $bool = $dist->install =back =over 4 =item $bool = $dist->uninstall =back =head2 CPANPLUS::Dist::Build - CPANPLUS plugin to install packages that use Build.PL =over 4 =item SYNOPSIS =item DESCRIPTION =item ACCESSORS C<parent()>, C<status()> =item STATUS ACCESSORS C<build_pl ()>, C<build ()>, C<test ()>, C<prepared ()>, C<distdir ()>, C<created ()>, C<installed ()>, uninstalled (), C<_create_args ()>, C<_install_args ()> =back =over 4 =item METHODS =over 4 =item $bool = CPANPLUS::Dist::Build->format_available(); =back =back =over 4 =item $bool = $dist->init(); =back =over 4 =item $bool = $dist->prepare([perl => '/path/to/perl', buildflags => 'EXTRA=FLAGS', force => BOOL, verbose => BOOL]) =back =over 4 =item $dist->create([perl => '/path/to/perl', buildflags => 'EXTRA=FLAGS', prereq_target => TARGET, force => BOOL, verbose => BOOL, skiptest => BOOL]) =back =over 4 =item $dist->install([verbose => BOOL, perl => /path/to/perl]) =back =over 4 =item AUTHOR =item LICENSE =back =head2 CPANPLUS::Dist::Build::Constants - Constants for CPANPLUS::Dist::Build =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR =item LICENSE =back =head2 CPANPLUS::Dist::MM - distribution class for MakeMaker related modules =over 4 =item SYNOPSIS =item DESCRIPTION =item ACCESSORS parent(), status() =item STATUS ACCESSORS makefile (), make (), test (), prepared (), distdir (), created (), installed (), uninstalled (), _create_args (), _install_args () =back =over 4 =item METHODS =over 4 =item $bool = $dist->format_available(); =back =back =over 4 =item $bool = $dist->init(); =back =over 4 =item $bool = $dist->prepare([perl => '/path/to/perl', makemakerflags => 'EXTRA=FLAGS', force => BOOL, verbose => BOOL]) =back =over 4 =item $href = $dist->_find_prereqs( file => '/path/to/Makefile', [verbose => BOOL]) =back =over 4 =item $bool = $dist->create([perl => '/path/to/perl', make => '/path/to/make', makeflags => 'EXTRA=FLAGS', prereq_target => TARGET, skiptest => BOOL, force => BOOL, verbose => BOOL]) =back =over 4 =item $bool = $dist->install([make => '/path/to/make', makemakerflags => 'EXTRA=FLAGS', force => BOOL, verbose => BOOL]) =back =over 4 =item $bool = $dist->write_makefile_pl([force => BOOL, verbose => BOOL]) =back =head2 CPANPLUS::Dist::Sample -- Sample code to create your own Dist::* plugin =over 4 =item Description. =back =head2 CPANPLUS::Error - error handling for CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS =over 4 =item cp_msg("message string" [,VERBOSE]) =item msg() =item cp_error("error string" [,VERBOSE]) =item error() =back =item CLASS METHODS =over 4 =item CPANPLUS::Error->stack() =item CPANPLUS::Error->stack_as_string([TRACE]) =item CPANPLUS::Error->flush() =back =back =over 4 =item GLOBAL VARIABLES $ERROR_FH, $MSG_FH =back =head2 CPANPLUS::FAQ - CPANPLUS Frequently Asked Questions =head2 CPANPLUS::FAQ =over 4 =item DESCRIPTION =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 CPANPLUS::Hacking - developing CPANPLUS =over 4 =item DESCRIPTION =item OBTAINING CPANPLUS =item INSTALLING CPANPLUS =item CONFIGURING CPANPLUS =item RUNNING CPANPLUS FROM DEVELOPMENT ENVIRONMENT =item RUNNING CPANPLUS TESTS =item FINDING BUGS Problem description, Program demonstrating the bug, [OPTIONAL] A patch to the test suite to test for the bug, [OPTIONAL] A patch to the code + tests + documentation =item SUPPLYING PATCHES In C<diff -u> or C<diff -c> format, From the root of the snapshot, Including patches for code + tests + docs, Sent per mail to bug-cpanplus@rt.cpan.org, With subject containing C<[PATCH]> + description of the patch =back =head2 CPANPLUS::Internals - CPANPLUS internals =over 4 =item SYNOPSIS =item DESCRIPTION =item ACCESSORS _conf, _id =back =over 4 =item METHODS =over 4 =item $internals = CPANPLUS::Internals->_init( _conf => CONFIG_OBJ ) =back =back =over 4 =item $bool = $internals->_flush( list => \@caches ) =back =over 4 =item $bool = $internals->_register_callback( name => CALLBACK_NAME, code => CODEREF ); install_prerequisite, send_test_report, munge_test_report, edit_test_report, proceed_on_test_failure, munge_dist_metafile =back =over 4 =item $bool = $internals->_add_to_includepath( directories => \@dirs ) =back =over 4 =item $id = CPANPLUS::Internals->_last_id =item $id = CPANPLUS::Internals->_store_id( $internals ) =item $obj = CPANPLUS::Internals->_retrieve_id( $ID ) =item CPANPLUS::Internals->_remove_id( $ID ) =item @objs = CPANPLUS::Internals->_return_all_objects =back =head2 CPANPLUS::Internals::Extract - internals for archive extraction =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item $dir = _extract( module => $modobj, [perl => '/path/to/perl', extractdir => '/path/to/extract/to', prefer_bin => BOOL, verbose => BOOL, force => BOOL] ) module, extractdir, prefer_bin, perl, verbose, force =back =back =head2 CPANPLUS::Internals::Fetch - internals for fetching files =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =back =over 4 =item $path = _fetch( module => $modobj, [fetchdir => '/path/to/save/to', fetch_from => 'scheme://path/to/fetch/from', verbose => BOOL, force => BOOL, prefer_bin => BOOL, ttl => $seconds] ) =back =over 4 =item _add_fail_host( host => $host_hashref ) =item _host_ok( host => $host_hashref ) =back =head2 CPANPLUS::Internals::Report - internals for sending test reports =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item $bool = $cb->_have_query_report_modules =item $bool = $cb->_have_send_report_modules =back =back =over 4 =item @list = $cb->_query_report( module => $modobj, [all_versions => BOOL, verbose => BOOL] ) =back =over 4 =item $bool = $cb->_send_report( module => $modobj, buffer => $make_output, failed => BOOL, [save => BOOL, address => $email_to, verbose => BOOL, force => BOOL]); module, buffer, failed, save, address, verbose, force =back =head2 CPANPLUS::Internals::Search - internals for searching for modules =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item _search_module_tree( type => TYPE, allow => \@regexes, [data => \@previous_results ] ) type, allow, data =back =back =over 4 =item _search_author_tree( type => TYPE, allow => \@regexex, [data => \@previous_results ] ) type, allow, data =back =over 4 =item _all_installed() =back =head2 CPANPLUS::Internals::Source - internals for updating source files =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =back =over 4 =item $cb->_build_trees( uptodate => BOOL, [use_stored => BOOL, path => $path, verbose => BOOL] ) uptodate, path, verbose, use_stored =back =over 4 =item $cb->_check_trees( [update_source => BOOL, path => PATH, verbose => BOOL] ) update_source, path, verbose =back =over 4 =item $cb->__check_uptodate( file => $file, name => $name, [update_source => BOOL, verbose => BOOL] ) file, name, update_source, verbose =back =over 4 =item $cb->_update_source( name => $name, [path => $path, verbose => BOOL] ) name, path, verbose =back =over 4 =item $cb->__create_author_tree([path => $path, uptodate => BOOL, verbose => BOOL]) uptodate, path, verbose =back =over 4 =item $cb->_create_mod_tree([path => $path, uptodate => BOOL, verbose => BOOL]) uptodate, path, verbose =back =over 4 =item $cb->__create_dslip_tree([path => $path, uptodate => BOOL, verbose => BOOL]) uptodate, path, verbose =back =over 4 =item $cb->_dslip_defs () =back =over 4 =item $file = $cb->_add_custom_module_source( uri => URI, [verbose => BOOL] ); =back =over 4 =item $index = $cb->__custom_module_source_index_file( uri => $uri ); =back =over 4 =item $file = $cb->_remove_custom_module_source( uri => URI, [verbose => BOOL] ); =back =over 4 =item %files = $cb->__list_custom_module_sources =back =over 4 =item $bool = $cb->__update_custom_module_sources( [verbose => BOOL] ); =back =over 4 =item $ok = $cb->__update_custom_module_source =back =over 4 =item $bool = $cb->__write_custom_module_index( path => /path/to/packages, [to => /path/to/index/file, verbose => BOOL] ) =back =over 4 =item $bool = $cb->__create_custom_module_entries( [verbose => BOOL] ) =back =head2 CPANPLUS::Internals::Source::Memory - In memory implementation =over 4 =item $cb->__memory_retrieve_source(name => $name, [path => $path, uptodate => BOOL, verbose => BOOL]) name, uptodate, path, verbose =back =over 4 =item $cb->__memory_save_source([verbose => BOOL, path => $path]) path, verbose =back =head2 CPANPLUS::Internals::Source::SQLite - SQLite implementation =head2 CPANPLUS::Internals::Utils - convenience functions for CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item $cb->_mkdir( dir => '/some/dir' ) =back =back =over 4 =item $cb->_chdir( dir => '/some/dir' ) =back =over 4 =item $cb->_rmdir( dir => '/some/dir' ); =back =over 4 =item $cb->_perl_version ( perl => 'some/perl/binary' ); =back =over 4 =item $cb->_version_to_number( version => $version ); =back =over 4 =item $cb->_whoami =back =over 4 =item _get_file_contents( file => $file ); =back =over 4 =item $cb->_move( from => $file|$dir, to => $target ); =back =over 4 =item $cb->_copy( from => $file|$dir, to => $target ); =back =over 4 =item $cb->_mode_plus_w( file => '/path/to/file' ); =back =over 4 =item $uri = $cb->_host_to_uri( scheme => SCHEME, host => HOST, path => PATH ); =back =over 4 =item $cb->_vcmp( VERSION, VERSION ); =back =over 4 =item $cb->_home_dir =back =over 4 =item $path = $cb->_safe_path( path => $path ); =back =over 4 =item ($pkg, $version, $ext) = $cb->_split_package_string( package => PACKAGE_STRING ); =back =head2 CPANPLUS::Module - CPAN module objects for CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item CLASS METHODS =over 4 =item accessors () =back =back =over 4 =item ACCESSORS name, module, version, path, comment, package, description, dslip =back status, author, parent =over 4 =item STATUS ACCESSORS installer_type, dist_cpan, dist, prereqs | requires, configure_requires, signature, extract, fetch, readme, uninstall, created, installed, checksums, checksum_ok, checksum_value =item METHODS =over 4 =item $self = CPANPLUS::Module->new( OPTIONS ) =back =back =over 4 =item $mod->package_name( [$package_string] ) =item $mod->package_version( [$package_string] ) =item $mod->package_extension( [$package_string] ) =item $mod->package_is_perl_core =item $mod->module_is_supplied_with_perl_core( [version => $]] ) =item $mod->is_bundle =item $mod->is_autobundle; =item $mod->is_third_party =item $mod->third_party_information =back =over 4 =item $clone = $self->clone =back =over 4 =item $where = $self->fetch =back =over 4 =item $path = $self->extract =back =over 4 =item $type = $self->get_installer_type([prefer_makefile => BOOL]) =back =over 4 =item $dist = $self->dist([target => 'prepare|create', format => DISTRIBUTION_TYPE, args => {key => val}]); =back =over 4 =item $bool = $mod->prepare( ) =back =over 4 =item $bool = $mod->create( ) =back =over 4 =item $bool = $mod->test( ) =back =over 4 =item $bool = $self->install([ target => 'init|prepare|create|install', format => FORMAT_TYPE, extractdir => DIRECTORY, fetchdir => DIRECTORY, prefer_bin => BOOL, force => BOOL, verbose => BOOL, ..... ]); =back =over 4 =item $text = $self->readme =back =over 4 =item $version = $self->installed_version() =item $where = $self->installed_file() =item $dir = $self->installed_dir() =item $bool = $self->is_uptodate([version => VERSION_NUMBER]) =back =over 4 =item $href = $self->details() =back =over 4 =item @list = $self->contains() =back =over 4 =item @list_of_hrefs = $self->fetch_report() =back =over 4 =item $bool = $self->uninstall([type => [all|man|prog]) =back =over 4 =item @modobj = $self->distributions() =back =over 4 =item @list = $self->files () =item @list = $self->directory_tree () =item @list = $self->packlist () =item @list = $self->validate () =back =over 4 =item $bool = $self->add_to_includepath; =back =over 4 =item $path = $self->best_path_to_module_build(); =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 CPANPLUS::Module::Author - CPAN author object for CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =item ACCESSORS author, cpanid, email, parent =back =over 4 =item METHODS =over 4 =item $auth = CPANPLUS::Module::Author->new( author => AUTHOR_NAME, cpanid => CPAN_ID, _id => INTERNALS_ID [, email => AUTHOR_EMAIL] ) =back =back =over 4 =item @mod_objs = $auth->modules() =back =over 4 =item @dists = $auth->distributions() =back =over 4 =item CLASS METHODS =over 4 =item accessors () =back =back =head2 CPANPLUS::Module::Author::Fake - dummy author object for CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new( _id => DIGIT ) =back =back =head2 CPANPLUS::Module::Checksums - checking the checksum of a distribution =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item $mod->checksums =back =back =head2 CPANPLUS::Module::Fake - fake module object for internal use =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new( module => $mod, path => $path, package => $pkg, [_id => DIGIT] ) =back =back =head2 CPANPLUS::Selfupdate - self-updating for CPANPLUS =over 4 =item SYNOPSIS =back =over 4 =item METHODS =over 4 =item $self = CPANPLUS::Selfupdate->new( $backend_object ); =back =back =over 4 =item @cat = $self->list_categories =back =over 4 =item %list = $self->list_modules_to_update( update => "core|dependencies|enabled_features|features|all", [latest => BOOL] ) =back =over 4 =item $bool = $self->selfupdate( update => "core|dependencies|enabled_features|features|all", [latest => BOOL, force => BOOL] ) =back =over 4 =item @features = $self->list_features =back =over 4 =item @features = $self->list_enabled_features =back =over 4 =item @mods = $self->modules_for_feature( FEATURE [,AS_HASH] ) =back =over 4 =item @mods = $self->list_core_dependencies( [AS_HASH] ) =back =over 4 =item @mods = $self->list_core_modules( [AS_HASH] ) =back =over 4 =item CPANPLUS::Selfupdate::Module =back =over 4 =item $version = $mod->version_required =back =over 4 =item $bool = $mod->is_installed_version_sufficient =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 CPANPLUS::Shell - base class for CPANPLUS shells =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 CPANPLUS::Shell::Classic - CPAN.pm emulation for CPANPLUS =over 4 =item DESCRIPTION =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =over 4 =item SEE ALSO =back =head2 CPANPLUS::Shell::Default - the default CPANPLUS shell =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 CPANPLUS::Shell::Default::Plugins::CustomSource - add custom sources to CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 CPANPLUS::Shell::Default::Plugins::HOWTO -- documentation on how to write your own plugins =over 4 =item SYNOPSIS =item DESCRIPTION =item HOWTO =over 4 =item Registering Plugin Modules =item Registering Plugin Commands =item Registering Plugin Help =item Arguments to Plugin Commands Classname -- The name of your plugin class, Shell -- The CPANPLUS::Shell::Default object, Backend -- The CPANPLUS::Backend object, Command -- The command issued by the user, Input -- The input string from the user, Options -- A hashref of options provided by the user =back =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 CPANPLUS::Shell::Default::Plugins::Remote - connect to a remote CPANPLUS =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 CPANPLUS::Shell::Default::Plugins::Source - read in CPANPLUS commands =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 Carp - alternative warn and die for modules =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Forcing a Stack Trace =back =item GLOBAL VARIABLES =over 4 =item $Carp::MaxEvalLen =item $Carp::MaxArgLen =item $Carp::MaxArgNums =item $Carp::Verbose =item @CARP_NOT =item %Carp::Internal =item %Carp::CarpInternal =item $Carp::CarpLevel =back =item BUGS =item SEE ALSO =item AUTHOR =item COPYRIGHT =item LICENSE =back =head2 Class::Struct - declare struct-like datatypes as Perl classes =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item The C<struct()> function =item Class Creation at Compile Time =item Element Types and Accessor Methods Scalar (C<'$'> or C<'*$'>), Array (C<'@'> or C<'*@'>), Hash (C<'%'> or C<'*%'>), Class (C<'Class_Name'> or C<'*Class_Name'>) =item Initializing with C<new> =back =item EXAMPLES Example 1, Example 2, Example 3 =item Author and Modification History =back =head2 Compress::Raw::Bzip2 - Low-Level Interface to bzip2 compression library =over 4 =item SYNOPSIS =item DESCRIPTION =item Compression =over 4 =item ($z, $status) = new Compress::Raw::Bzip2 $appendOutput, $blockSize100k, $workfactor; B<$appendOutput>, B<$blockSize100k>, B<$workfactor> =item $status = $bz->bzdeflate($input, $output); =item $status = $bz->bzflush($output); =item $status = $bz->bzclose($output); =item Example =back =item Uncompression =over 4 =item ($z, $status) = new Compress::Raw::Bunzip2 $appendOutput, $consumeInput, $small, $verbosity, $limitOutput; B<$appendOutput>, B<$consumeInput>, B<$small>, B<$limitOutput>, B<$verbosity> =item $status = $z->bzinflate($input, $output); =back =item Misc =over 4 =item my $version = Compress::Raw::Bzip2::bzlibversion(); =back =item Constants =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 Compress::Raw::Zlib - Low-Level Interface to zlib compression library =over 4 =item SYNOPSIS =item DESCRIPTION =item Compress::Raw::Zlib::Deflate =over 4 =item B<($d, $status) = new Compress::Raw::Zlib::Deflate( [OPT] ) > B<-Level>, B<-Method>, B<-WindowBits>, B<-MemLevel>, B<-Strategy>, B<-Dictionary>, B<-Bufsize>, B<-AppendOutput>, B<-CRC32>, B<-ADLER32> =item B<$status = $d-E<gt>deflate($input, $output)> =item B<$status = $d-E<gt>flush($output [, $flush_type]) > =item B<$status = $d-E<gt>deflateReset() > =item B<$status = $d-E<gt>deflateParams([OPT])> B<-Level>, B<-Strategy>, B<-BufSize> =item B<$status = $d-E<gt>deflateTune($good_length, $max_lazy, $nice_length, $max_chain)> =item B<$d-E<gt>dict_adler()> =item B<$d-E<gt>crc32()> =item B<$d-E<gt>adler32()> =item B<$d-E<gt>msg()> =item B<$d-E<gt>total_in()> =item B<$d-E<gt>total_out()> =item B<$d-E<gt>get_Strategy()> =item B<$d-E<gt>get_Level()> =item B<$d-E<gt>get_BufSize()> =item Example =back =item Compress::Raw::Zlib::Inflate =over 4 =item B< ($i, $status) = new Compress::Raw::Zlib::Inflate( [OPT] ) > B<-WindowBits>, B<-Bufsize>, B<-Dictionary>, B<-AppendOutput>, B<-CRC32>, B<-ADLER32>, B<-ConsumeInput>, B<-LimitOutput> =item B< $status = $i-E<gt>inflate($input, $output [,$eof]) > =item B<$status = $i-E<gt>inflateSync($input)> =item B<$status = $i-E<gt>inflateReset() > =item B<$i-E<gt>dict_adler()> =item B<$i-E<gt>crc32()> =item B<$i-E<gt>adler32()> =item B<$i-E<gt>msg()> =item B<$i-E<gt>total_in()> =item B<$i-E<gt>total_out()> =item B<$d-E<gt>get_BufSize()> =item Examples =back =item CHECKSUM FUNCTIONS =item Misc =over 4 =item my $version = Compress::Raw::Zlib::zlib_version(); =item my $flags = Compress::Raw::Zlib::zlibCompileFlags(); =back =item The LimitOutput option. =item ACCESSING ZIP FILES =item FAQ =over 4 =item Compatibility with Unix compress/uncompress. =item Accessing .tar.Z files =item Zlib Library Version Support =back =item CONSTANTS =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 Compress::Zlib - Interface to zlib compression library =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Notes for users of Compress::Zlib version 1 =back =item GZIP INTERFACE B<$gz = gzopen($filename, $mode)>, B<$gz = gzopen($filehandle, $mode)>, B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>, B<$bytesread = $gz-E<gt>gzreadline($line) ;>, B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>, B<$status = $gz-E<gt>gzflush($flush_type) ;>, B<$offset = $gz-E<gt>gztell() ;>, B<$status = $gz-E<gt>gzseek($offset, $whence) ;>, B<$gz-E<gt>gzclose>, B<$gz-E<gt>gzsetparams($level, $strategy>, B<$level>, B<$strategy>, B<$gz-E<gt>gzerror>, B<$gzerrno> =over 4 =item Examples =item Compress::Zlib::memGzip =item Compress::Zlib::memGunzip =back =item COMPRESS/UNCOMPRESS B<$dest = compress($source [, $level] ) ;>, B<$dest = uncompress($source) ;> =item Deflate Interface =over 4 =item B<($d, $status) = deflateInit( [OPT] )> B<-Level>, B<-Method>, B<-WindowBits>, B<-MemLevel>, B<-Strategy>, B<-Dictionary>, B<-Bufsize> =item B<($out, $status) = $d-E<gt>deflate($buffer)> =item B<($out, $status) = $d-E<gt>flush()> =head2 B<($out, $status) = $d-E<gt>flush($flush_type)> =item B<$status = $d-E<gt>deflateParams([OPT])> B<-Level>, B<-Strategy> =item B<$d-E<gt>dict_adler()> =item B<$d-E<gt>msg()> =item B<$d-E<gt>total_in()> =item B<$d-E<gt>total_out()> =item Example =back =item Inflate Interface =over 4 =item B<($i, $status) = inflateInit()> B<-WindowBits>, B<-Bufsize>, B<-Dictionary> =item B<($out, $status) = $i-E<gt>inflate($buffer)> =item B<$status = $i-E<gt>inflateSync($buffer)> =item B<$i-E<gt>dict_adler()> =item B<$i-E<gt>msg()> =item B<$i-E<gt>total_in()> =item B<$i-E<gt>total_out()> =item Example =back =item CHECKSUM FUNCTIONS =item Misc =over 4 =item my $version = Compress::Zlib::zlib_version(); =back =item CONSTANTS =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 Config - access Perl configuration information =over 4 =item SYNOPSIS =item DESCRIPTION myconfig(), config_sh(), config_re($regex), config_vars(@names), bincompat_options(), non_bincompat_options(), compile_date(), local_patches(), header_files() =item EXAMPLE =item WARNING =item GLOSSARY =back =over 4 =item _ =back C<_a>, C<_exe>, C<_o> =over 4 =item a =back C<afs>, C<afsroot>, C<alignbytes>, C<ansi2knr>, C<aphostname>, C<api_revision>, C<api_subversion>, C<api_version>, C<api_versionstring>, C<ar>, C<archlib>, C<archlibexp>, C<archname>, C<archname64>, C<archobjs>, C<asctime_r_proto>, C<awk> =over 4 =item b =back C<baserev>, C<bash>, C<bin>, C<bin_ELF>, C<binexp>, C<bison>, C<byacc>, C<byteorder> =over 4 =item c =back C<c>, C<castflags>, C<cat>, C<cc>, C<cccdlflags>, C<ccdlflags>, C<ccflags>, C<ccflags_uselargefiles>, C<ccname>, C<ccsymbols>, C<ccversion>, C<cf_by>, C<cf_email>, C<cf_time>, C<charbits>, C<charsize>, C<chgrp>, C<chmod>, C<chown>, C<clocktype>, C<comm>, C<compress>, C<config_arg0>, C<config_argc>, C<config_args>, C<contains>, C<cp>, C<cpio>, C<cpp>, C<cpp_stuff>, C<cppccsymbols>, C<cppflags>, C<cpplast>, C<cppminus>, C<cpprun>, C<cppstdin>, C<cppsymbols>, C<crypt_r_proto>, C<cryptlib>, C<csh>, C<ctermid_r_proto>, C<ctime_r_proto> =over 4 =item d =back C<d__fwalk>, C<d_access>, C<d_accessx>, C<d_aintl>, C<d_alarm>, C<d_archlib>, C<d_asctime64>, C<d_asctime_r>, C<d_atolf>, C<d_atoll>, C<d_attribute_deprecated>, C<d_attribute_format>, C<d_attribute_malloc>, C<d_attribute_nonnull>, C<d_attribute_noreturn>, C<d_attribute_pure>, C<d_attribute_unused>, C<d_attribute_warn_unused_result>, C<d_bcmp>, C<d_bcopy>, C<d_bsd>, C<d_bsdgetpgrp>, C<d_bsdsetpgrp>, C<d_builtin_choose_expr>, C<d_builtin_expect>, C<d_bzero>, C<d_c99_variadic_macros>, C<d_casti32>, C<d_castneg>, C<d_charvspr>, C<d_chown>, C<d_chroot>, C<d_chsize>, C<d_class>, C<d_clearenv>, C<d_closedir>, C<d_cmsghdr_s>, C<d_const>, C<d_copysignl>, C<d_cplusplus>, C<d_crypt>, C<d_crypt_r>, C<d_csh>, C<d_ctermid>, C<d_ctermid_r>, C<d_ctime64>, C<d_ctime_r>, C<d_cuserid>, C<d_dbl_dig>, C<d_dbminitproto>, C<d_difftime>, C<d_difftime64>, C<d_dir_dd_fd>, C<d_dirfd>, C<d_dirnamlen>, C<d_dlerror>, C<d_dlopen>, C<d_dlsymun>, C<d_dosuid>, C<d_drand48_r>, C<d_drand48proto>, C<d_dup2>, C<d_eaccess>, C<d_endgrent>, C<d_endgrent_r>, C<d_endhent>, C<d_endhostent_r>, C<d_endnent>, C<d_endnetent_r>, C<d_endpent>, C<d_endprotoent_r>, C<d_endpwent>, C<d_endpwent_r>, C<d_endsent>, C<d_endservent_r>, C<d_eofnblk>, C<d_eunice>, C<d_faststdio>, C<d_fchdir>, C<d_fchmod>, C<d_fchown>, C<d_fcntl>, C<d_fcntl_can_lock>, C<d_fd_macros>, C<d_fd_set>, C<d_fds_bits>, C<d_fgetpos>, C<d_finite>, C<d_finitel>, C<d_flexfnam>, C<d_flock>, C<d_flockproto>, C<d_fork>, C<d_fp_class>, C<d_fpathconf>, C<d_fpclass>, C<d_fpclassify>, C<d_fpclassl>, C<d_fpos64_t>, C<d_frexpl>, C<d_fs_data_s>, C<d_fseeko>, C<d_fsetpos>, C<d_fstatfs>, C<d_fstatvfs>, C<d_fsync>, C<d_ftello>, C<d_ftime>, C<d_futimes>, C<d_Gconvert>, C<d_gdbm_ndbm_h_uses_prototypes>, C<d_gdbmndbm_h_uses_prototypes>, C<d_getaddrinfo>, C<d_getcwd>, C<d_getespwnam>, C<d_getfsstat>, C<d_getgrent>, C<d_getgrent_r>, C<d_getgrgid_r>, C<d_getgrnam_r>, C<d_getgrps>, C<d_gethbyaddr>, C<d_gethbyname>, C<d_gethent>, C<d_gethname>, C<d_gethostbyaddr_r>, C<d_gethostbyname_r>, C<d_gethostent_r>, C<d_gethostprotos>, C<d_getitimer>, C<d_getlogin>, C<d_getlogin_r>, C<d_getmnt>, C<d_getmntent>, C<d_getnameinfo>, C<d_getnbyaddr>, C<d_getnbyname>, C<d_getnent>, C<d_getnetbyaddr_r>, C<d_getnetbyname_r>, C<d_getnetent_r>, C<d_getnetprotos>, C<d_getpagsz>, C<d_getpbyname>, C<d_getpbynumber>, C<d_getpent>, C<d_getpgid>, C<d_getpgrp>, C<d_getpgrp2>, C<d_getppid>, C<d_getprior>, C<d_getprotobyname_r>, C<d_getprotobynumber_r>, C<d_getprotoent_r>, C<d_getprotoprotos>, C<d_getprpwnam>, C<d_getpwent>, C<d_getpwent_r>, C<d_getpwnam_r>, C<d_getpwuid_r>, C<d_getsbyname>, C<d_getsbyport>, C<d_getsent>, C<d_getservbyname_r>, C<d_getservbyport_r>, C<d_getservent_r>, C<d_getservprotos>, C<d_getspnam>, C<d_getspnam_r>, C<d_gettimeod>, C<d_gmtime64>, C<d_gmtime_r>, C<d_gnulibc>, C<d_grpasswd>, C<d_hasmntopt>, C<d_htonl>, C<d_ilogbl>, C<d_inc_version_list>, C<d_index>, C<d_inetaton>, C<d_inetntop>, C<d_inetpton>, C<d_int64_t>, C<d_ipv6_mreq>, C<d_isascii>, C<d_isblank>, C<d_isfinite>, C<d_isinf>, C<d_isnan>, C<d_isnanl>, C<d_killpg>, C<d_lchown>, C<d_ldbl_dig>, C<d_libm_lib_version>, C<d_link>, C<d_localtime64>, C<d_localtime_r>, C<d_localtime_r_needs_tzset>, C<d_locconv>, C<d_lockf>, C<d_longdbl>, C<d_longlong>, C<d_lseekproto>, C<d_lstat>, C<d_madvise>, C<d_malloc_good_size>, C<d_malloc_size>, C<d_mblen>, C<d_mbstowcs>, C<d_mbtowc>, C<d_memchr>, C<d_memcmp>, C<d_memcpy>, C<d_memmove>, C<d_memset>, C<d_mkdir>, C<d_mkdtemp>, C<d_mkfifo>, C<d_mkstemp>, C<d_mkstemps>, C<d_mktime>, C<d_mktime64>, C<d_mmap>, C<d_modfl>, C<d_modfl_pow32_bug>, C<d_modflproto>, C<d_mprotect>, C<d_msg>, C<d_msg_ctrunc>, C<d_msg_dontroute>, C<d_msg_oob>, C<d_msg_peek>, C<d_msg_proxy>, C<d_msgctl>, C<d_msgget>, C<d_msghdr_s>, C<d_msgrcv>, C<d_msgsnd>, C<d_msync>, C<d_munmap>, C<d_mymalloc>, C<d_ndbm>, C<d_ndbm_h_uses_prototypes>, C<d_nice>, C<d_nl_langinfo>, C<d_nv_preserves_uv>, C<d_nv_zero_is_allbits_zero>, C<d_off64_t>, C<d_old_pthread_create_joinable>, C<d_oldpthreads>, C<d_oldsock>, C<d_open3>, C<d_pathconf>, C<d_pause>, C<d_perl_otherlibdirs>, C<d_phostname>, C<d_pipe>, C<d_poll>, C<d_portable>, C<d_prctl>, C<d_prctl_set_name>, C<d_PRId64>, C<d_PRIeldbl>, C<d_PRIEUldbl>, C<d_PRIfldbl>, C<d_PRIFUldbl>, C<d_PRIgldbl>, C<d_PRIGUldbl>, C<d_PRIi64>, C<d_printf_format_null>, C<d_PRIo64>, C<d_PRIu64>, C<d_PRIx64>, C<d_PRIXU64>, C<d_procselfexe>, C<d_pseudofork>, C<d_pthread_atfork>, C<d_pthread_attr_setscope>, C<d_pthread_yield>, C<d_pwage>, C<d_pwchange>, C<d_pwclass>, C<d_pwcomment>, C<d_pwexpire>, C<d_pwgecos>, C<d_pwpasswd>, C<d_pwquota>, C<d_qgcvt>, C<d_quad>, C<d_random_r>, C<d_readdir>, C<d_readdir64_r>, C<d_readdir_r>, C<d_readlink>, C<d_readv>, C<d_recvmsg>, C<d_rename>, C<d_rewinddir>, C<d_rmdir>, C<d_safebcpy>, C<d_safemcpy>, C<d_sanemcmp>, C<d_sbrkproto>, C<d_scalbnl>, C<d_sched_yield>, C<d_scm_rights>, C<d_SCNfldbl>, C<d_seekdir>, C<d_select>, C<d_sem>, C<d_semctl>, C<d_semctl_semid_ds>, C<d_semctl_semun>, C<d_semget>, C<d_semop>, C<d_sendmsg>, C<d_setegid>, C<d_seteuid>, C<d_setgrent>, C<d_setgrent_r>, C<d_setgrps>, C<d_sethent>, C<d_sethostent_r>, C<d_setitimer>, C<d_setlinebuf>, C<d_setlocale>, C<d_setlocale_r>, C<d_setnent>, C<d_setnetent_r>, C<d_setpent>, C<d_setpgid>, C<d_setpgrp>, C<d_setpgrp2>, C<d_setprior>, C<d_setproctitle>, C<d_setprotoent_r>, C<d_setpwent>, C<d_setpwent_r>, C<d_setregid>, C<d_setresgid>, C<d_setresuid>, C<d_setreuid>, C<d_setrgid>, C<d_setruid>, C<d_setsent>, C<d_setservent_r>, C<d_setsid>, C<d_setvbuf>, C<d_sfio>, C<d_shm>, C<d_shmat>, C<d_shmatprototype>, C<d_shmctl>, C<d_shmdt>, C<d_shmget>, C<d_sigaction>, C<d_signbit>, C<d_sigprocmask>, C<d_sigsetjmp>, C<d_sin6_scope_id>, C<d_sitearch>, C<d_snprintf>, C<d_sockaddr_in6>, C<d_sockaddr_sa_len>, C<d_sockatmark>, C<d_sockatmarkproto>, C<d_socket>, C<d_socklen_t>, C<d_sockpair>, C<d_socks5_init>, C<d_sprintf_returns_strlen>, C<d_sqrtl>, C<d_srand48_r>, C<d_srandom_r>, C<d_sresgproto>, C<d_sresuproto>, C<d_statblks>, C<d_statfs_f_flags>, C<d_statfs_s>, C<d_static_inline>, C<d_statvfs>, C<d_stdio_cnt_lval>, C<d_stdio_ptr_lval>, C<d_stdio_ptr_lval_nochange_cnt>, C<d_stdio_ptr_lval_sets_cnt>, C<d_stdio_stream_array>, C<d_stdiobase>, C<d_stdstdio>, C<d_strchr>, C<d_strcoll>, C<d_strctcpy>, C<d_strerrm>, C<d_strerror>, C<d_strerror_r>, C<d_strftime>, C<d_strlcat>, C<d_strlcpy>, C<d_strtod>, C<d_strtol>, C<d_strtold>, C<d_strtoll>, C<d_strtoq>, C<d_strtoul>, C<d_strtoull>, C<d_strtouq>, C<d_strxfrm>, C<d_suidsafe>, C<d_symlink>, C<d_syscall>, C<d_syscallproto>, C<d_sysconf>, C<d_sysernlst>, C<d_syserrlst>, C<d_system>, C<d_tcgetpgrp>, C<d_tcsetpgrp>, C<d_telldir>, C<d_telldirproto>, C<d_time>, C<d_timegm>, C<d_times>, C<d_tm_tm_gmtoff>, C<d_tm_tm_zone>, C<d_tmpnam_r>, C<d_truncate>, C<d_ttyname_r>, C<d_tzname>, C<d_u32align>, C<d_ualarm>, C<d_umask>, C<d_uname>, C<d_union_semun>, C<d_unordered>, C<d_unsetenv>, C<d_usleep>, C<d_usleepproto>, C<d_ustat>, C<d_vendorarch>, C<d_vendorbin>, C<d_vendorlib>, C<d_vendorscript>, C<d_vfork>, C<d_void_closedir>, C<d_voidsig>, C<d_voidtty>, C<d_volatile>, C<d_vprintf>, C<d_vsnprintf>, C<d_wait4>, C<d_waitpid>, C<d_wcstombs>, C<d_wctomb>, C<d_writev>, C<d_xenix>, C<date>, C<db_hashtype>, C<db_prefixtype>, C<db_version_major>, C<db_version_minor>, C<db_version_patch>, C<defvoidused>, C<direntrytype>, C<dlext>, C<dlsrc>, C<doublesize>, C<drand01>, C<drand48_r_proto>, C<dtrace>, C<dynamic_ext> =over 4 =item e =back C<eagain>, C<ebcdic>, C<echo>, C<egrep>, C<emacs>, C<endgrent_r_proto>, C<endhostent_r_proto>, C<endnetent_r_proto>, C<endprotoent_r_proto>, C<endpwent_r_proto>, C<endservent_r_proto>, C<eunicefix>, C<exe_ext>, C<expr>, C<extensions>, C<extern_C>, C<extras> =over 4 =item f =back C<fflushall>, C<fflushNULL>, C<find>, C<firstmakefile>, C<flex>, C<fpossize>, C<fpostype>, C<freetype>, C<from>, C<full_ar>, C<full_csh>, C<full_sed> =over 4 =item g =back C<gccansipedantic>, C<gccosandvers>, C<gccversion>, C<getgrent_r_proto>, C<getgrgid_r_proto>, C<getgrnam_r_proto>, C<gethostbyaddr_r_proto>, C<gethostbyname_r_proto>, C<gethostent_r_proto>, C<getlogin_r_proto>, C<getnetbyaddr_r_proto>, C<getnetbyname_r_proto>, C<getnetent_r_proto>, C<getprotobyname_r_proto>, C<getprotobynumber_r_proto>, C<getprotoent_r_proto>, C<getpwent_r_proto>, C<getpwnam_r_proto>, C<getpwuid_r_proto>, C<getservbyname_r_proto>, C<getservbyport_r_proto>, C<getservent_r_proto>, C<getspnam_r_proto>, C<gidformat>, C<gidsign>, C<gidsize>, C<gidtype>, C<glibpth>, C<gmake>, C<gmtime_r_proto>, C<gnulibc_version>, C<grep>, C<groupcat>, C<groupstype>, C<gzip> =over 4 =item h =back C<h_fcntl>, C<h_sysfile>, C<hint>, C<hostcat>, C<html1dir>, C<html1direxp>, C<html3dir>, C<html3direxp> =over 4 =item i =back C<i16size>, C<i16type>, C<i32size>, C<i32type>, C<i64size>, C<i64type>, C<i8size>, C<i8type>, C<i_arpainet>, C<i_assert>, C<i_bsdioctl>, C<i_crypt>, C<i_db>, C<i_dbm>, C<i_dirent>, C<i_dld>, C<i_dlfcn>, C<i_fcntl>, C<i_float>, C<i_fp>, C<i_fp_class>, C<i_gdbm>, C<i_gdbm_ndbm>, C<i_gdbmndbm>, C<i_grp>, C<i_ieeefp>, C<i_inttypes>, C<i_langinfo>, C<i_libutil>, C<i_limits>, C<i_locale>, C<i_machcthr>, C<i_malloc>, C<i_mallocmalloc>, C<i_math>, C<i_memory>, C<i_mntent>, C<i_ndbm>, C<i_netdb>, C<i_neterrno>, C<i_netinettcp>, C<i_niin>, C<i_poll>, C<i_prot>, C<i_pthread>, C<i_pwd>, C<i_rpcsvcdbm>, C<i_sfio>, C<i_sgtty>, C<i_shadow>, C<i_socks>, C<i_stdarg>, C<i_stdbool>, C<i_stddef>, C<i_stdlib>, C<i_string>, C<i_sunmath>, C<i_sysaccess>, C<i_sysdir>, C<i_sysfile>, C<i_sysfilio>, C<i_sysin>, C<i_sysioctl>, C<i_syslog>, C<i_sysmman>, C<i_sysmode>, C<i_sysmount>, C<i_sysndir>, C<i_sysparam>, C<i_syspoll>, C<i_sysresrc>, C<i_syssecrt>, C<i_sysselct>, C<i_syssockio>, C<i_sysstat>, C<i_sysstatfs>, C<i_sysstatvfs>, C<i_systime>, C<i_systimek>, C<i_systimes>, C<i_systypes>, C<i_sysuio>, C<i_sysun>, C<i_sysutsname>, C<i_sysvfs>, C<i_syswait>, C<i_termio>, C<i_termios>, C<i_time>, C<i_unistd>, C<i_ustat>, C<i_utime>, C<i_values>, C<i_varargs>, C<i_varhdr>, C<i_vfork>, C<ignore_versioned_solibs>, C<inc_version_list>, C<inc_version_list_init>, C<incpath>, C<inews>, C<initialinstalllocation>, C<installarchlib>, C<installbin>, C<installhtml1dir>, C<installhtml3dir>, C<installman1dir>, C<installman3dir>, C<installprefix>, C<installprefixexp>, C<installprivlib>, C<installscript>, C<installsitearch>, C<installsitebin>, C<installsitehtml1dir>, C<installsitehtml3dir>, C<installsitelib>, C<installsiteman1dir>, C<installsiteman3dir>, C<installsitescript>, C<installstyle>, C<installusrbinperl>, C<installvendorarch>, C<installvendorbin>, C<installvendorhtml1dir>, C<installvendorhtml3dir>, C<installvendorlib>, C<installvendorman1dir>, C<installvendorman3dir>, C<installvendorscript>, C<intsize>, C<issymlink>, C<ivdformat>, C<ivsize>, C<ivtype> =over 4 =item k =back C<known_extensions>, C<ksh> =over 4 =item l =back C<ld>, C<ld_can_script>, C<lddlflags>, C<ldflags>, C<ldflags_uselargefiles>, C<ldlibpthname>, C<less>, C<lib_ext>, C<libc>, C<libperl>, C<libpth>, C<libs>, C<libsdirs>, C<libsfiles>, C<libsfound>, C<libspath>, C<libswanted>, C<libswanted_uselargefiles>, C<line>, C<lint>, C<lkflags>, C<ln>, C<lns>, C<localtime_r_proto>, C<locincpth>, C<loclibpth>, C<longdblsize>, C<longlongsize>, C<longsize>, C<lp>, C<lpr>, C<ls>, C<lseeksize>, C<lseektype> =over 4 =item m =back C<mad>, C<madlyh>, C<madlyobj>, C<madlysrc>, C<mail>, C<mailx>, C<make>, C<make_set_make>, C<mallocobj>, C<mallocsrc>, C<malloctype>, C<man1dir>, C<man1direxp>, C<man1ext>, C<man3dir>, C<man3direxp>, C<man3ext>, C<mips_type>, C<mistrustnm>, C<mkdir>, C<mmaptype>, C<modetype>, C<more>, C<multiarch>, C<mv>, C<myarchname>, C<mydomain>, C<myhostname>, C<myuname> =over 4 =item n =back C<n>, C<need_va_copy>, C<netdb_hlen_type>, C<netdb_host_type>, C<netdb_name_type>, C<netdb_net_type>, C<nm>, C<nm_opt>, C<nm_so_opt>, C<nonxs_ext>, C<nroff>, C<nv_overflows_integers_at>, C<nv_preserves_uv_bits>, C<nveformat>, C<nvEUformat>, C<nvfformat>, C<nvFUformat>, C<nvgformat>, C<nvGUformat>, C<nvsize>, C<nvtype> =over 4 =item o =back C<o_nonblock>, C<obj_ext>, C<old_pthread_create_joinable>, C<optimize>, C<orderlib>, C<osname>, C<osvers>, C<otherlibdirs> =over 4 =item p =back C<package>, C<pager>, C<passcat>, C<patchlevel>, C<path_sep>, C<perl>, C<perl5> =over 4 =item P =back C<PERL_API_REVISION>, C<PERL_API_SUBVERSION>, C<PERL_API_VERSION>, C<PERL_CONFIG_SH>, C<PERL_PATCHLEVEL>, C<perl_patchlevel>, C<PERL_REVISION>, C<perl_static_inline>, C<PERL_SUBVERSION>, C<PERL_VERSION>, C<perladmin>, C<perllibs>, C<perlpath>, C<pg>, C<phostname>, C<pidtype>, C<plibpth>, C<pmake>, C<pr>, C<prefix>, C<prefixexp>, C<privlib>, C<privlibexp>, C<procselfexe>, C<prototype>, C<ptrsize> =over 4 =item q =back C<quadkind>, C<quadtype> =over 4 =item r =back C<randbits>, C<randfunc>, C<random_r_proto>, C<randseedtype>, C<ranlib>, C<rd_nodata>, C<readdir64_r_proto>, C<readdir_r_proto>, C<revision>, C<rm>, C<rm_try>, C<rmail>, C<run>, C<runnm> =over 4 =item s =back C<sched_yield>, C<scriptdir>, C<scriptdirexp>, C<sed>, C<seedfunc>, C<selectminbits>, C<selecttype>, C<sendmail>, C<setgrent_r_proto>, C<sethostent_r_proto>, C<setlocale_r_proto>, C<setnetent_r_proto>, C<setprotoent_r_proto>, C<setpwent_r_proto>, C<setservent_r_proto>, C<sGMTIME_max>, C<sGMTIME_min>, C<sh>, C<shar>, C<sharpbang>, C<shmattype>, C<shortsize>, C<shrpenv>, C<shsharp>, C<sig_count>, C<sig_name>, C<sig_name_init>, C<sig_num>, C<sig_num_init>, C<sig_size>, C<signal_t>, C<sitearch>, C<sitearchexp>, C<sitebin>, C<sitebinexp>, C<sitehtml1dir>, C<sitehtml1direxp>, C<sitehtml3dir>, C<sitehtml3direxp>, C<sitelib>, C<sitelib_stem>, C<sitelibexp>, C<siteman1dir>, C<siteman1direxp>, C<siteman3dir>, C<siteman3direxp>, C<siteprefix>, C<siteprefixexp>, C<sitescript>, C<sitescriptexp>, C<sizesize>, C<sizetype>, C<sleep>, C<sLOCALTIME_max>, C<sLOCALTIME_min>, C<smail>, C<so>, C<sockethdr>, C<socketlib>, C<socksizetype>, C<sort>, C<spackage>, C<spitshell>, C<sPRId64>, C<sPRIeldbl>, C<sPRIEUldbl>, C<sPRIfldbl>, C<sPRIFUldbl>, C<sPRIgldbl>, C<sPRIGUldbl>, C<sPRIi64>, C<sPRIo64>, C<sPRIu64>, C<sPRIx64>, C<sPRIXU64>, C<srand48_r_proto>, C<srandom_r_proto>, C<src>, C<sSCNfldbl>, C<ssizetype>, C<st_ino_sign>, C<st_ino_size>, C<startperl>, C<startsh>, C<static_ext>, C<stdchar>, C<stdio_base>, C<stdio_bufsiz>, C<stdio_cnt>, C<stdio_filbuf>, C<stdio_ptr>, C<stdio_stream_array>, C<strerror_r_proto>, C<strings>, C<submit>, C<subversion>, C<sysman> =over 4 =item t =back C<tail>, C<tar>, C<targetarch>, C<tbl>, C<tee>, C<test>, C<timeincl>, C<timetype>, C<tmpnam_r_proto>, C<to>, C<touch>, C<tr>, C<trnl>, C<troff>, C<ttyname_r_proto> =over 4 =item u =back C<u16size>, C<u16type>, C<u32size>, C<u32type>, C<u64size>, C<u64type>, C<u8size>, C<u8type>, C<uidformat>, C<uidsign>, C<uidsize>, C<uidtype>, C<uname>, C<uniq>, C<uquadtype>, C<use5005threads>, C<use64bitall>, C<use64bitint>, C<usecrosscompile>, C<usedevel>, C<usedl>, C<usedtrace>, C<usefaststdio>, C<useithreads>, C<usekernprocpathname>, C<uselargefiles>, C<uselongdouble>, C<usemallocwrap>, C<usemorebits>, C<usemultiplicity>, C<usemymalloc>, C<usenm>, C<usensgetexecutablepath>, C<useopcode>, C<useperlio>, C<useposix>, C<usereentrant>, C<userelocatableinc>, C<usesfio>, C<useshrplib>, C<usesitecustomize>, C<usesocks>, C<usethreads>, C<usevendorprefix>, C<usevfork>, C<usrinc>, C<uuname>, C<uvoformat>, C<uvsize>, C<uvtype>, C<uvuformat>, C<uvxformat>, C<uvXUformat> =over 4 =item v =back C<vaproto>, C<vendorarch>, C<vendorarchexp>, C<vendorbin>, C<vendorbinexp>, C<vendorhtml1dir>, C<vendorhtml1direxp>, C<vendorhtml3dir>, C<vendorhtml3direxp>, C<vendorlib>, C<vendorlib_stem>, C<vendorlibexp>, C<vendorman1dir>, C<vendorman1direxp>, C<vendorman3dir>, C<vendorman3direxp>, C<vendorprefix>, C<vendorprefixexp>, C<vendorscript>, C<vendorscriptexp>, C<version>, C<version_patchlevel_string>, C<versiononly>, C<vi>, C<voidflags> =over 4 =item x =back C<xlibpth> =over 4 =item y =back C<yacc>, C<yaccflags> =over 4 =item z =back C<zcat>, C<zip> =over 4 =item GIT DATA =item NOTE =back =over 4 =item SYNOPSIS =item DESCRIPTION dynamic, nonxs, static =item AUTHOR =back =head2 Cwd - get pathname of current working directory =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item getcwd and friends getcwd, cwd, fastcwd, fastgetcwd, getdcwd =item abs_path and friends abs_path, realpath, fast_abs_path =item $ENV{PWD} =back =item NOTES =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 DB - programmatic interface to the Perl debugging API =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Global Variables $DB::sub, %DB::sub, $DB::single, $DB::signal, $DB::trace, @DB::args, @DB::dbline, %DB::dbline, $DB::package, $DB::filename, $DB::subname, $DB::lineno =item API Methods CLIENT->register(), CLIENT->evalcode(STRING), CLIENT->skippkg('D::hide'), CLIENT->run(), CLIENT->step(), CLIENT->next(), CLIENT->done() =item Client Callback Methods CLIENT->init(), CLIENT->prestop([STRING]), CLIENT->stop(), CLIENT->idle(), CLIENT->poststop([STRING]), CLIENT->evalcode(STRING), CLIENT->cleanup(), CLIENT->output(LIST) =back =item BUGS =item AUTHOR =back =head2 DBM_Filter -- Filter DBM keys/values =over 4 =item SYNOPSIS =item DESCRIPTION =item What is a DBM Filter? =over 4 =item So what's new? =back =item METHODS =over 4 =item $db->Filter_Push() / $db->Filter_Key_Push() / $db->Filter_Value_Push() Filter_Push, Filter_Key_Push, Filter_Value_Push =item $db->Filter_Pop() =item $db->Filtered() =back =item Writing a Filter =over 4 =item Immediate Filters =item Canned Filters "name", params =back =item Filters Included utf8, encode, compress, int32, null =item NOTES =over 4 =item Maintain Round Trip Integrity =item Don't mix filtered & non-filtered data in the same database file. =back =item EXAMPLE =item SEE ALSO =item AUTHOR =back =head2 DBM_Filter::compress - filter for DBM_Filter =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =back =head2 DBM_Filter::encode - filter for DBM_Filter =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =back =head2 DBM_Filter::int32 - filter for DBM_Filter =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =back =head2 DBM_Filter::null - filter for DBM_Filter =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =back =head2 DBM_Filter::utf8 - filter for DBM_Filter =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =back =head2 DB_File - Perl5 access to Berkeley DB version 1.x =over 4 =item SYNOPSIS =item DESCRIPTION B<DB_HASH>, B<DB_BTREE>, B<DB_RECNO> =over 4 =item Using DB_File with Berkeley DB version 2 or greater =item Interface to Berkeley DB =item Opening a Berkeley DB Database File =item Default Parameters =item In Memory Databases =back =item DB_HASH =over 4 =item A Simple Example =back =item DB_BTREE =over 4 =item Changing the BTREE sort order =item Handling Duplicate Keys =item The get_dup() Method =item The find_dup() Method =item The del_dup() Method =item Matching Partial Keys =back =item DB_RECNO =over 4 =item The 'bval' Option =item A Simple Example =item Extra RECNO Methods B<$X-E<gt>push(list) ;>, B<$value = $X-E<gt>pop ;>, B<$X-E<gt>shift>, B<$X-E<gt>unshift(list) ;>, B<$X-E<gt>length>, B<$X-E<gt>splice(offset, length, elements);> =item Another Example =back =item THE API INTERFACE B<$status = $X-E<gt>get($key, $value [, $flags]) ;>, B<$status = $X-E<gt>put($key, $value [, $flags]) ;>, B<$status = $X-E<gt>del($key [, $flags]) ;>, B<$status = $X-E<gt>fd ;>, B<$status = $X-E<gt>seq($key, $value, $flags) ;>, B<$status = $X-E<gt>sync([$flags]) ;> =item DBM FILTERS B<filter_store_key>, B<filter_store_value>, B<filter_fetch_key>, B<filter_fetch_value> =over 4 =item The Filter =item An Example -- the NULL termination problem. =item Another Example -- Key is a C int. =back =item HINTS AND TIPS =over 4 =item Locking: The Trouble with fd =item Safe ways to lock a database B<Tie::DB_Lock>, B<Tie::DB_LockFile>, B<DB_File::Lock> =item Sharing Databases With C Applications =item The untie() Gotcha =back =item COMMON QUESTIONS =over 4 =item Why is there Perl source in my database? =item How do I store complex data structures with DB_File? =item What does "Invalid Argument" mean? =item What does "Bareword 'DB_File' not allowed" mean? =back =item REFERENCES =item HISTORY =item BUGS =item AVAILABILITY =item COPYRIGHT =item SEE ALSO =item AUTHOR =back =head2 Data::Dumper - stringified perl data structures, suitable for both printing and C<eval> =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Methods I<PACKAGE>->new(I<ARRAYREF [>, I<ARRAYREF]>), I<$OBJ>->Dump I<or> I<PACKAGE>->Dump(I<ARRAYREF [>, I<ARRAYREF]>), I<$OBJ>->Seen(I<[HASHREF]>), I<$OBJ>->Values(I<[ARRAYREF]>), I<$OBJ>->Names(I<[ARRAYREF]>), I<$OBJ>->Reset =item Functions Dumper(I<LIST>) =item Configuration Variables or Methods =item Exports Dumper =back =item EXAMPLES =item BUGS =over 4 =item NOTE =back =item AUTHOR =item VERSION =item SEE ALSO =back =head2 Devel::InnerPackage - find all the inner packages of a package =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item list_packages <package name> =back =back =over 4 =item AUTHOR =item COPYING =item BUGS =back =head2 Devel::PPPort - Perl/Pollution/Portability =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Why use ppport.h? =item How to use ppport.h =item Running ppport.h =back =item FUNCTIONS =over 4 =item WriteFile =back =item COMPATIBILITY =over 4 =item Provided Perl compatibility API =item Perl API not supported by ppport.h perl 5.14.0, perl 5.13.10, perl 5.13.8, perl 5.13.7, perl 5.13.6, perl 5.13.5, perl 5.13.4, perl 5.13.3, perl 5.13.2, perl 5.13.1, perl 5.11.5, perl 5.11.4, perl 5.11.2, perl 5.11.1, perl 5.11.0, perl 5.10.1, perl 5.10.0, perl 5.9.5, perl 5.9.4, perl 5.9.3, perl 5.9.2, perl 5.9.1, perl 5.9.0, perl 5.8.3, perl 5.8.1, perl 5.8.0, perl 5.7.3, perl 5.7.2, perl 5.7.1, perl 5.6.1, perl 5.6.0, perl 5.005_03, perl 5.005, perl 5.004_05, perl 5.004 =back =item BUGS =item AUTHORS =item COPYRIGHT =item SEE ALSO =back =head2 Devel::Peek - A data debugging tool for the XS programmer =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Runtime debugging =item Memory footprint debugging =back =item EXAMPLES =over 4 =item A simple scalar string =item A simple scalar number =item A simple scalar with an extra reference =item A reference to a simple scalar =item A reference to an array =item A reference to a hash =item Dumping a large array or hash =item A reference to an SV which holds a C pointer =item A reference to a subroutine =back =item EXPORTS =item BUGS =item AUTHOR =item SEE ALSO =back =head2 Devel::SelfStubber - generate stubs for a SelfLoading module =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 Digest - Modules that calculate message digests =over 4 =item SYNOPSIS =item DESCRIPTION I<binary>, I<hex>, I<base64> =item OO INTERFACE $ctx = Digest->XXX($arg,...), $ctx = Digest->new(XXX => $arg,...), $ctx = Digest::XXX->new($arg,...), $other_ctx = $ctx->clone, $ctx->reset, $ctx->add( $data ), $ctx->add( $chunk1, $chunk2, ... ), $ctx->addfile( $io_handle ), $ctx->add_bits( $data, $nbits ), $ctx->add_bits( $bitstring ), $ctx->digest, $ctx->hexdigest, $ctx->b64digest =item Digest speed =item SEE ALSO =item AUTHOR =back =head2 Digest::MD5 - Perl interface to the MD5 Algorithm =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS md5($data,...), md5_hex($data,...), md5_base64($data,...) =item METHODS $md5 = Digest::MD5->new, $md5->reset, $md5->clone, $md5->add($data,...), $md5->addfile($io_handle), $md5->add_bits($data, $nbits), $md5->add_bits($bitstring), $md5->digest, $md5->hexdigest, $md5->b64digest =item EXAMPLES =item SEE ALSO =item COPYRIGHT =item AUTHORS =back =head2 Digest::SHA - Perl extension for SHA-1/224/256/384/512 =over 4 =item SYNOPSIS =item SYNOPSIS (HMAC-SHA) =item ABSTRACT =item DESCRIPTION =item NIST STATEMENT ON SHA-1 =item PADDING OF BASE64 DIGESTS =item EXPORT =item EXPORTABLE FUNCTIONS B<sha1($data, ...)>, B<sha224($data, ...)>, B<sha256($data, ...)>, B<sha384($data, ...)>, B<sha512($data, ...)>, B<sha512224($data, ...)>, B<sha512256($data, ...)>, B<sha1_hex($data, ...)>, B<sha224_hex($data, ...)>, B<sha256_hex($data, ...)>, B<sha384_hex($data, ...)>, B<sha512_hex($data, ...)>, B<sha512224_hex($data, ...)>, B<sha512256_hex($data, ...)>, B<sha1_base64($data, ...)>, B<sha224_base64($data, ...)>, B<sha256_base64($data, ...)>, B<sha384_base64($data, ...)>, B<sha512_base64($data, ...)>, B<sha512224_base64($data, ...)>, B<sha512256_base64($data, ...)>, B<new($alg)>, B<reset($alg)>, B<hashsize>, B<algorithm>, B<clone>, B<add($data, ...)>, B<add_bits($data, $nbits)>, B<add_bits($bits)>, B<addfile(*FILE)>, B<addfile($filename [, $mode])>, B<dump($filename)>, B<load($filename)>, B<digest>, B<hexdigest>, B<b64digest>, B<hmac_sha1($data, $key)>, B<hmac_sha224($data, $key)>, B<hmac_sha256($data, $key)>, B<hmac_sha384($data, $key)>, B<hmac_sha512($data, $key)>, B<hmac_sha512224($data, $key)>, B<hmac_sha512256($data, $key)>, B<hmac_sha1_hex($data, $key)>, B<hmac_sha224_hex($data, $key)>, B<hmac_sha256_hex($data, $key)>, B<hmac_sha384_hex($data, $key)>, B<hmac_sha512_hex($data, $key)>, B<hmac_sha512224_hex($data, $key)>, B<hmac_sha512256_hex($data, $key)>, B<hmac_sha1_base64($data, $key)>, B<hmac_sha224_base64($data, $key)>, B<hmac_sha256_base64($data, $key)>, B<hmac_sha384_base64($data, $key)>, B<hmac_sha512_base64($data, $key)>, B<hmac_sha512224_base64($data, $key)>, B<hmac_sha512256_base64($data, $key)> =item SEE ALSO =item AUTHOR =item ACKNOWLEDGMENTS =item COPYRIGHT AND LICENSE =back =head2 Digest::base - Digest base class =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =back =head2 Digest::file - Calculate digests of files =over 4 =item SYNOPSIS =item DESCRIPTION digest_file( $file, $algorithm, [$arg,...] ), digest_file_hex( $file, $algorithm, [$arg,...] ), digest_file_base64( $file, $algorithm, [$arg,...] ) =item SEE ALSO =back =head2 DirHandle - supply object methods for directory handles =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 Dumpvalue - provides screen dump of Perl data. =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Creation C<arrayDepth>, C<hashDepth>, C<compactDump>, C<veryCompact>, C<globPrint>, C<dumpDBFiles>, C<dumpPackages>, C<dumpReused>, C<tick>, C<quoteHighBit>, C<printUndef>, C<usageOnly>, unctrl, subdump, bareStringify, quoteHighBit, stopDbSignal =item Methods dumpValue, dumpValues, stringify, dumpvars, set_quote, set_unctrl, compactDump, veryCompact, set, get =back =back =head2 DynaLoader - Dynamically load C libraries into Perl code =over 4 =item SYNOPSIS =item DESCRIPTION @dl_library_path, @dl_resolve_using, @dl_require_symbols, @dl_librefs, @dl_modules, @dl_shared_objects, dl_error(), $dl_debug, dl_findfile(), dl_expandspec(), dl_load_file(), dl_unload_file(), dl_load_flags(), dl_find_symbol(), dl_find_symbol_anywhere(), dl_undef_symbols(), dl_install_xsub(), bootstrap() =item AUTHOR =back =head2 Encode - character encodings in Perl =over 4 =item SYNOPSIS =over 4 =item Table of Contents =back =item DESCRIPTION =over 4 =item TERMINOLOGY =back =item THE PERL ENCODING API $octets = encode(ENCODING, STRING[, CHECK]), $string = decode(ENCODING, OCTETS[, CHECK]), [$obj =] find_encoding(ENCODING), [$length =] from_to($octets, FROM_ENC, TO_ENC [, CHECK]), $octets = encode_utf8($string);, $string = decode_utf8($octets [, CHECK]); =over 4 =item Listing available encodings =item Defining Aliases =item Finding IANA Character Set Registry names =back =item Encoding via PerlIO =item Handling Malformed Data B<NOTE:> Not all encoding support this feature, I<CHECK> = Encode::FB_DEFAULT ( == 0), I<CHECK> = Encode::FB_CROAK ( == 1), I<CHECK> = Encode::FB_QUIET, I<CHECK> = Encode::FB_WARN, perlqq mode (I<CHECK> = Encode::FB_PERLQQ), HTML charref mode (I<CHECK> = Encode::FB_HTMLCREF), XML charref mode (I<CHECK> = Encode::FB_XMLCREF), The bitmask, Encode::LEAVE_SRC =over 4 =item coderef for CHECK =back =item Defining Encodings =item The UTF8 flag Goal #1:, Goal #2:, Goal #3:, Goal #4: =over 4 =item Messing with Perl's Internals is_utf8(STRING [, CHECK]), _utf8_on(STRING), _utf8_off(STRING) =back =item UTF-8 vs. utf8 vs. UTF8 =item SEE ALSO =item MAINTAINER =item COPYRIGHT =back =head2 Encode::Alias - alias definitions to encodings =over 4 =item SYNOPSIS =item DESCRIPTION As a simple string, As a qr// compiled regular expression, e.g.:, As a code reference, e.g.: =over 4 =item Alias overloading =back =item SEE ALSO =back =head2 Encode::Byte - Single Byte Encodings =over 4 =item SYNOPSIS =item ABSTRACT =item DESCRIPTION =item SEE ALSO =back =head2 Encode::CJKConstants -- Internally used by Encode::??::ISO_2022_* =head2 Encode::CN - China-based Chinese Encodings =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTES =item BUGS =item SEE ALSO =back =head2 Encode::CN::HZ -- internally used by Encode::CN =head2 Encode::Config -- internally used by Encode =head2 Encode::EBCDIC - EBCDIC Encodings =over 4 =item SYNOPSIS =item ABSTRACT =item DESCRIPTION =item SEE ALSO =back =head2 Encode::Encoder -- Object Oriented Encoder =over 4 =item SYNOPSIS =item ABSTRACT =item Description =over 4 =item Predefined Methods $e = Encode::Encoder-E<gt>new([$data, $encoding]);, encoder(), $e-E<gt>data([$data]), $e-E<gt>encoding([$encoding]), $e-E<gt>bytes([$encoding]) =item Example: base64 transcoder =item Operator Overloading =back =item SEE ALSO =back =head2 Encode::Encoding - Encode Implementation Base Class =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Methods you should implement -E<gt>encode($string [,$check]), -E<gt>decode($octets [,$check]), -E<gt>cat_decode($destination, $octets, $offset, $terminator [,$check]) =item Other methods defined in Encode::Encodings -E<gt>name, -E<gt>mime_name, -E<gt>renew, -E<gt>renewed, -E<gt>perlio_ok(), -E<gt>needs_lines() =item Example: Encode::ROT13 =back =item Why the heck Encode API is different? =over 4 =item Compiled Encodings =back =item SEE ALSO Scheme 1, Scheme 2, Other Schemes =back =head2 Encode::GSM0338 -- ESTI GSM 03.38 Encoding =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTES =item BUGS =item SEE ALSO =back =head2 Encode::Guess -- Guesses encoding from data =over 4 =item SYNOPSIS =item ABSTRACT =item DESCRIPTION Encode::Guess->set_suspects, Encode::Guess->add_suspects, Encode::decode("Guess" ...), Encode::Guess->guess($data), guess_encoding($data, [, I<list of suspects>]) =item CAVEATS =item TO DO =item SEE ALSO =back =head2 Encode::JP - Japanese Encodings =over 4 =item SYNOPSIS =item ABSTRACT =item DESCRIPTION =item Note on ISO-2022-JP(-1)? =item BUGS =item SEE ALSO =back =head2 Encode::JP::H2Z -- internally used by Encode::JP::2022_JP* =head2 Encode::JP::JIS7 -- internally used by Encode::JP =head2 Encode::KR - Korean Encodings =over 4 =item SYNOPSIS =item DESCRIPTION =item BUGS =item SEE ALSO =back =head2 Encode::KR::2022_KR -- internally used by Encode::KR =head2 Encode::MIME::Header -- MIME 'B' and 'Q' header encoding =over 4 =item SYNOPSIS =item ABSTRACT =item DESCRIPTION =item BUGS =item SEE ALSO =back =head2 Encode::MIME::Name, Encode::MIME::NAME -- internally used by Encode =over 4 =item SEE ALSO =back =head2 Encode::PerlIO -- a detailed document on Encode and PerlIO =over 4 =item Overview =item How does it work? =item Line Buffering =over 4 =item How can I tell whether my encoding fully supports PerlIO ? =back =item SEE ALSO =back =head2 Encode::Supported -- Encodings supported by Encode =over 4 =item DESCRIPTION =over 4 =item Encoding Names =back =item Supported Encodings =over 4 =item Built-in Encodings =item Encode::Unicode -- other Unicode encodings =item Encode::Byte -- Extended ASCII ISO-8859 and corresponding vendor mappings, KOI8 - De Facto Standard for the Cyrillic world =item gsm0338 - Hentai Latin 1 gsm0338 support before 2.19 =item CJK: Chinese, Japanese, Korean (Multibyte) Encode::CN -- Continental China, Encode::JP -- Japan, Encode::KR -- Korea, Encode::TW -- Taiwan, Encode::HanExtra -- More Chinese via CPAN, Encode::JIS2K -- JIS X 0213 encodings via CPAN =item Miscellaneous encodings Encode::EBCDIC, Encode::Symbols, Encode::MIME::Header, Encode::Guess =back =item Unsupported encodings ISO-2022-JP-2 [RFC1554], ISO-2022-CN [RFC1922], Various HP-UX encodings, Cyrillic encoding ISO-IR-111, ISO-8859-8-1 [Hebrew], ISIRI 3342, Iran System, ISIRI 2900 [Farsi], Thai encoding TCVN, Vietnamese encodings VPS, Various Mac encodings, (Mac) Indic encodings =item Encoding vs. Charset -- terminology =item Encoding Classification (by Anton Tagunov and Dan Kogai) =over 4 =item Microsoft-related naming mess KS_C_5601-1987, GB2312, Big5, Shift_JIS =back =item Glossary character repertoire, coded character set (CCS), character encoding scheme (CES), charset (in MIME context), EUC, ISO-2022, UCS, UCS-2, Unicode, UTF, UTF-16 =item See Also =item References ECMA, ECMA-035 (eq C<ISO-2022>), IANA, Assigned Charset Names by IANA, ISO, RFC, UC, Unicode Glossary =over 4 =item Other Notable Sites czyborra.com, CJK.inf, Jungshik Shin's Hangul FAQ, debian.org: "Introduction to i18n" =item Offline sources C<CJKV Information Processing> by Ken Lunde =back =back =head2 Encode::Symbol - Symbol Encodings =over 4 =item SYNOPSIS =item ABSTRACT =item DESCRIPTION =item SEE ALSO =back =head2 Encode::TW - Taiwan-based Chinese Encodings =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTES =item BUGS =item SEE ALSO =back =head2 Encode::Unicode -- Various Unicode Transformation Formats =over 4 =item SYNOPSIS =item ABSTRACT L<http://www.unicode.org/glossary/> says:, Quick Reference =item Size, Endianness, and BOM =over 4 =item by size =item by endianness BOM as integer when fetched in network byte order =back =item Surrogate Pairs =item Error Checking =item SEE ALSO =back =head2 Encode::Unicode::UTF7 -- UTF-7 encoding =over 4 =item SYNOPSIS =item ABSTRACT =item In Practice =item SEE ALSO =back =head2 English - use nice English (or awk) names for ugly punctuation variables =over 4 =item SYNOPSIS =item DESCRIPTION =item PERFORMANCE =back =head2 Env - perl module that imports environment variables as scalars or arrays =over 4 =item SYNOPSIS =item DESCRIPTION =item LIMITATIONS =item AUTHOR =back =head2 Errno - System errno constants =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEATS =item AUTHOR =item COPYRIGHT =back =head2 Exporter - Implements default import method for modules =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item How to Export =item Selecting What To Export =item How to Import C<use YourModule;>, C<use YourModule ();>, C<use YourModule qw(...);> =back =item Advanced features =over 4 =item Specialised Import Lists =item Exporting without using Exporter's import method =item Exporting without inheriting from Exporter =item Module Version Checking =item Managing Unknown Symbols =item Tag Handling Utility Functions =item Generating combined tags =item C<AUTOLOAD>ed Constants =back =item Good Practices =over 4 =item Declaring C<@EXPORT_OK> and Friends =item Playing Safe =item What not to Export =back =item SEE ALSO =item LICENSE =back =head2 Exporter::Heavy - Exporter guts =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 ExtUtils::CBuilder - Compile and link C code for Perl modules =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS new, have_compiler, have_cplusplus, compile, C<object_file>, C<include_dirs>, C<extra_compiler_flags>, C<C++>, link, lib_file, module_name, extra_linker_flags, link_executable, exe_file, object_file, lib_file, exe_file, prelink, need_prelink, extra_link_args_after_prelink =item TO DO =item HISTORY =item SUPPORT =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 ExtUtils::CBuilder::Platform::Windows - Builder class for Windows platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 ExtUtils::Command - utilities to replace common UNIX commands in Makefiles etc. =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item FUNCTIONS =back =back cat eqtime rm_rf rm_f touch mv cp chmod mkpath test_f test_d dos2unix =over 4 =item SEE ALSO =item AUTHOR =back =head2 ExtUtils::Command::MM - Commands for the MM's to use in Makefiles =over 4 =item SYNOPSIS =item DESCRIPTION B<test_harness> =back B<pod2man> B<warn_if_old_packlist> B<perllocal_install> B<uninstall> =head2 ExtUtils::Constant - generate XS code to import C header constants =over 4 =item SYNOPSIS =item DESCRIPTION =item USAGE IV, UV, NV, PV, PVN, SV, YES, NO, UNDEF =item FUNCTIONS =back constant_types XS_constant PACKAGE, TYPES, XS_SUBNAME, C_SUBNAME autoload PACKAGE, VERSION, AUTOLOADER WriteMakefileSnippet WriteConstants ATTRIBUTE =E<gt> VALUE [, ...], NAME, DEFAULT_TYPE, BREAKOUT_AT, NAMES, PROXYSUBS, C_FH, C_FILE, XS_FH, XS_FILE, XS_SUBNAME, C_SUBNAME =over 4 =item AUTHOR =back =head2 ExtUtils::Constant::Base - base class for ExtUtils::Constant objects =over 4 =item SYNOPSIS =item DESCRIPTION =item USAGE =back header memEQ_clause args_hashref dump_names arg_hashref, ITEM.. assign arg_hashref, VALUE.. return_clause arg_hashref, ITEM switch_clause arg_hashref, NAMELEN, ITEMHASH, ITEM.. params WHAT dogfood arg_hashref, ITEM.. normalise_items args, default_type, seen_types, seen_items, ITEM.. C_constant arg_hashref, ITEM.., name, type, value, macro, default, pre, post, def_pre, def_post, utf8, weight =over 4 =item BUGS =item AUTHOR =back =head2 ExtUtils::Constant::Utils - helper functions for ExtUtils::Constant =over 4 =item SYNOPSIS =item DESCRIPTION =item USAGE C_stringify NAME =back perl_stringify NAME =over 4 =item AUTHOR =back =head2 ExtUtils::Constant::XS - generate C code for XS modules' constants. =over 4 =item SYNOPSIS =item DESCRIPTION =item BUGS =item AUTHOR =back =head2 ExtUtils::Embed - Utilities for embedding Perl in C/C++ applications =over 4 =item SYNOPSIS =item DESCRIPTION =item @EXPORT =item FUNCTIONS xsinit(), Examples, ldopts(), Examples, perl_inc(), ccflags(), ccdlflags(), ccopts(), xsi_header(), xsi_protos(@modules), xsi_body(@modules) =item EXAMPLES =item SEE ALSO =item AUTHOR =back =head2 ExtUtils::Install - install files from here to there =over 4 =item SYNOPSIS =item VERSION =back =over 4 =item DESCRIPTION _chmod($$;$), _warnonce(@), _choke(@) =back _move_file_at_boot( $file, $target, $moan ) _unlink_or_rename( $file, $tryhard, $installing ) =over 4 =item Functions _get_install_skip =back _have_write_access _can_write_dir(C<$dir>) _mkpath($dir,$show,$mode,$verbose,$dry_run) _copy($from,$to,$verbose,$dry_run) _chdir($from) B<install> _do_cleanup install_rooted_file( $file ), install_rooted_dir( $dir ) forceunlink( $file, $tryhard ) directory_not_empty( $dir ) B<install_default> I<DISCOURAGED> B<uninstall> inc_uninstall($filepath,$libdir,$verbose,$dry_run,$ignore,$results) run_filter($cmd,$src,$dest) B<pm_to_blib> _autosplit _invokant =over 4 =item ENVIRONMENT B<PERL_INSTALL_ROOT>, B<EU_INSTALL_IGNORE_SKIP>, B<EU_INSTALL_SITE_SKIPFILE>, B<EU_INSTALL_ALWAYS_COPY> =item AUTHOR =item LICENSE =back =head2 ExtUtils::Installed - Inventory management of installed modules =over 4 =item SYNOPSIS =item DESCRIPTION =item USAGE =item METHODS new(), modules(), files(), directories(), directory_tree(), validate(), packlist(), version() =item EXAMPLE =item AUTHOR =back =head2 ExtUtils::Liblist - determine libraries to use and how to use them =over 4 =item SYNOPSIS =item DESCRIPTION For static extensions, For dynamic extensions at build/link time, For dynamic extensions at load time =over 4 =item EXTRALIBS =item LDLOADLIBS and LD_RUN_PATH =item BSLOADLIBS =back =item PORTABILITY =over 4 =item VMS implementation =item Win32 implementation =back =item SEE ALSO =back =head2 ExtUtils::MM - OS adjusted ExtUtils::MakeMaker subclass =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 ExtUtils::MM_AIX - AIX specific subclass of ExtUtils::MM_Unix =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Overridden methods =back =back =over 4 =item AUTHOR =item SEE ALSO =back =head2 ExtUtils::MM_Any - Platform-agnostic MM methods =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Cross-platform helper methods =back =back =over 4 =item Targets =back =over 4 =item Init methods =back =over 4 =item Tools =back =over 4 =item File::Spec wrappers =back =over 4 =item Misc =back =over 4 =item AUTHOR =back =head2 ExtUtils::MM_BeOS - methods to override UN*X behaviour in ExtUtils::MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION =back os_flavor init_linker =head2 ExtUtils::MM_Cygwin - methods to override UN*X behaviour in ExtUtils::MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION os_flavor =back cflags replace_manpage_separator init_linker maybe_command dynamic_lib all_target =head2 ExtUtils::MM_DOS - DOS specific subclass of ExtUtils::MM_Unix =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Overridden methods os_flavor =back =back B<replace_manpage_separator> =over 4 =item AUTHOR =item SEE ALSO =back =head2 ExtUtils::MM_Darwin - special behaviors for OS X =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Overriden Methods =back =back =head2 ExtUtils::MM_MacOS - once produced Makefiles for MacOS Classic =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 ExtUtils::MM_NW5 - methods to override UN*X behaviour in ExtUtils::MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION =back os_flavor init_platform, platform_constants const_cccmd static_lib dynamic_lib =head2 ExtUtils::MM_OS2 - methods to override UN*X behaviour in ExtUtils::MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS init_dist =back init_linker os_flavor =head2 ExtUtils::MM_QNX - QNX specific subclass of ExtUtils::MM_Unix =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Overridden methods =back =back =over 4 =item AUTHOR =item SEE ALSO =back =head2 ExtUtils::MM_UWIN - U/WIN specific subclass of ExtUtils::MM_Unix =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Overridden methods os_flavor =back =back B<replace_manpage_separator> =over 4 =item AUTHOR =item SEE ALSO =back =head2 ExtUtils::MM_Unix - methods used by ExtUtils::MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =back =over 4 =item Methods os_flavor =back c_o (o) cflags (o) const_cccmd (o) const_config (o) const_loadlibs (o) constants (o) depend (o) init_DEST init_dist dist (o) dist_basics (o) dist_ci (o) dist_core (o) B<dist_target> B<tardist_target> B<zipdist_target> B<tarfile_target> zipfile_target uutardist_target shdist_target dlsyms (o) dynamic_bs (o) dynamic_lib (o) exescan extliblist find_perl fixin force (o) guess_name has_link_code init_dirscan init_MANPODS init_MAN1PODS init_MAN3PODS init_PM init_DIRFILESEP init_main init_tools init_linker init_lib2arch init_PERL init_platform, platform_constants init_PERM init_xs install (o) installbin (o) linkext (o) lsdir macro (o) makeaperl (o) makefile (o) maybe_command needs_linking (o) parse_abstract parse_version pasthru (o) perl_script perldepend (o) pm_to_blib post_constants (o) post_initialize (o) postamble (o) ppd prefixify processPL (o) quote_paren replace_manpage_separator cd oneliner quote_literal escape_newlines max_exec_len static (o) static_lib (o) staticmake (o) subdir_x (o) subdirs (o) test (o) test_via_harness (override) test_via_script (override) tool_xsubpp (o) all_target top_targets (o) writedoc xs_c (o) xs_cpp (o) xs_o (o) =over 4 =item SEE ALSO =back =head2 ExtUtils::MM_VMS - methods to override UN*X behaviour in ExtUtils::MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Methods always loaded wraplist =back =back =over 4 =item Methods guess_name (override) =back find_perl (override) _fixin_replace_shebang (override) maybe_command (override) pasthru (override) pm_to_blib (override) perl_script (override) replace_manpage_separator init_DEST init_DIRFILESEP init_main (override) init_tools (override) init_others (override) init_platform (override) platform_constants init_VERSION (override) constants (override) special_targets cflags (override) const_cccmd (override) tools_other (override) init_dist (override) c_o (override) xs_c (override) xs_o (override) dlsyms (override) dynamic_lib (override) static_lib (override) extra_clean_files zipfile_target, tarfile_target, shdist_target install (override) perldepend (override) makeaperl (override) maketext_filter (override) prefixify (override) cd oneliner B<echo> quote_literal escape_dollarsigns escape_all_dollarsigns escape_newlines max_exec_len init_linker catdir (override), catfile (override) eliminate_macros fixpath os_flavor =over 4 =item AUTHOR =back =head2 ExtUtils::MM_VOS - VOS specific subclass of ExtUtils::MM_Unix =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Overridden methods =back =back =over 4 =item AUTHOR =item SEE ALSO =back =head2 ExtUtils::MM_Win32 - methods to override UN*X behaviour in ExtUtils::MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item Overridden methods B<dlsyms> =back replace_manpage_separator B<maybe_command> B<init_DIRFILESEP> init_tools init_others init_platform, platform_constants constants special_targets static_lib dynamic_lib extra_clean_files init_linker perl_script xs_o pasthru arch_check (override) oneliner cd max_exec_len os_flavor cflags =head2 ExtUtils::MM_Win95 - method to customize MakeMaker for Win9X =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Overridden methods xs_c =back =back xs_cpp xs_o max_exec_len os_flavor =over 4 =item AUTHOR =back =head2 ExtUtils::MY - ExtUtils::MakeMaker subclass for customization =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 ExtUtils::MakeMaker - Create a module Makefile =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item How To Write A Makefile.PL =item Default Makefile Behaviour =item make test =item make testdb =item make install =item INSTALL_BASE =item PREFIX and LIB attribute =item AFS users =item Static Linking of a new Perl Binary =item Determination of Perl Library and Installation Locations =item Which architecture dependent directory? =item Using Attributes and Parameters ABSTRACT, ABSTRACT_FROM, AUTHOR, BINARY_LOCATION, BUILD_REQUIRES, C, CCFLAGS, CONFIG, CONFIGURE, CONFIGURE_REQUIRES, DEFINE, DESTDIR, DIR, DISTNAME, DISTVNAME, DL_FUNCS, DL_VARS, EXCLUDE_EXT, EXE_FILES, FIRST_MAKEFILE, FULLPERL, FULLPERLRUN, FULLPERLRUNINST, FUNCLIST, H, IMPORTS, INC, INCLUDE_EXT, INSTALLARCHLIB, INSTALLBIN, INSTALLDIRS, INSTALLMAN1DIR, INSTALLMAN3DIR, INSTALLPRIVLIB, INSTALLSCRIPT, INSTALLSITEARCH, INSTALLSITEBIN, INSTALLSITELIB, INSTALLSITEMAN1DIR, INSTALLSITEMAN3DIR, INSTALLSITESCRIPT, INSTALLVENDORARCH, INSTALLVENDORBIN, INSTALLVENDORLIB, INSTALLVENDORMAN1DIR, INSTALLVENDORMAN3DIR, INSTALLVENDORSCRIPT, INST_ARCHLIB, INST_BIN, INST_LIB, INST_MAN1DIR, INST_MAN3DIR, INST_SCRIPT, LD, LDDLFLAGS, LDFROM, LIB, LIBPERL_A, LIBS, LICENSE, LINKTYPE, MAKE, MAKEAPERL, MAKEFILE_OLD, MAN1PODS, MAN3PODS, MAP_TARGET, META_ADD, META_MERGE, MIN_PERL_VERSION, MYEXTLIB, NAME, NEEDS_LINKING, NOECHO, NORECURS, NO_META, NO_MYMETA, NO_VC, OBJECT, OPTIMIZE, PERL, PERL_CORE, PERLMAINCC, PERL_ARCHLIB, PERL_LIB, PERL_MALLOC_OK, PERLPREFIX, PERLRUN, PERLRUNINST, PERL_SRC, PERM_DIR, PERM_RW, PERM_RWX, PL_FILES, PM, PMLIBDIRS, PM_FILTER, POLLUTE, PPM_INSTALL_EXEC, PPM_INSTALL_SCRIPT, PREFIX, PREREQ_FATAL, PREREQ_PM, PREREQ_PRINT, PRINT_PREREQ, SITEPREFIX, SIGN, SKIP, TYPEMAPS, USE_MM_LD_RUN_PATH, VENDORPREFIX, VERBINST, VERSION, VERSION_FROM, VERSION_SYM, XS, XSOPT, XSPROTOARG, XS_VERSION =item Additional lowercase attributes clean, depend, dist, dynamic_lib, linkext, macro, postamble, realclean, test, tool_autosplit =item Overriding MakeMaker Methods =item The End Of Cargo Cult Programming C<< MAN3PODS => ' ' >> =item Hintsfile support =item Distribution Support make distcheck, make skipcheck, make distclean, make manifest, make distdir, make disttest, make tardist, make dist, make uutardist, make shdist, make zipdist, make ci =item Module Meta-Data (META and MYMETA) =item Disabling an extension =item Other Handy Functions prompt =back =item ENVIRONMENT PERL_MM_OPT, PERL_MM_USE_DEFAULT, PERL_CORE =item SEE ALSO =item AUTHORS =item LICENSE =back =head2 ExtUtils::MakeMaker::Config - Wrapper around Config.pm =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 ExtUtils::MakeMaker::FAQ - Frequently Asked Questions About MakeMaker =over 4 =item DESCRIPTION =over 4 =item Module Installation How do I install a module into my home directory?, How do I get MakeMaker and Module::Build to install to the same place?, How do I keep from installing man pages?, How do I use a module without installing it?, PREFIX vs INSTALL_BASE from Module::Build::Cookbook =item Philosophy and History Why not just use <insert other build config tool here>?, What is Module::Build and how does it relate to MakeMaker?, pure perl. no make, no shell commands, easier to customize, cleaner internals, less cruft =item Module Writing How do I keep my $VERSION up to date without resetting it manually?, What's this F<META.yml> thing and how did it get in my F<MANIFEST>?!, How do I delete everything not in my F<MANIFEST>?, Which tar should I use on Windows?, Which zip should I use on Windows for '[nd]make zipdist'? =item XS How to I prevent "object version X.XX does not match bootstrap parameter Y.YY" errors?, How do I make two or more XS files coexist in the same directory? =back =item PATCHING =item AUTHOR =item SEE ALSO =back =head2 ExtUtils::MakeMaker::Tutorial - Writing a module with MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item The Mantra =item The Layout Makefile.PL, MANIFEST, lib/, t/, Changes, README, INSTALL, MANIFEST.SKIP, bin/ =back =item SEE ALSO =back =head2 ExtUtils::Manifest - utilities to write and check a MANIFEST file =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Functions mkmanifest =back =back manifind manicheck filecheck fullcheck skipcheck maniread maniskip manicopy maniadd =over 4 =item MANIFEST =item MANIFEST.SKIP #!include_default, #!include /Path/to/another/manifest.skip =item EXPORT_OK =item GLOBAL VARIABLES =back =over 4 =item DIAGNOSTICS C<Not in MANIFEST:> I<file>, C<Skipping> I<file>, C<No such file:> I<file>, C<MANIFEST:> I<$!>, C<Added to MANIFEST:> I<file> =item ENVIRONMENT B<PERL_MM_MANIFEST_DEBUG> =item SEE ALSO =item AUTHOR =back =head2 ExtUtils::Miniperl, writemain - write the C code for perlmain.c =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =back =head2 ExtUtils::Mkbootstrap - make a bootstrap file for use by DynaLoader =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 ExtUtils::Mksymlists - write linker options files for dynamic extension =over 4 =item SYNOPSIS =item DESCRIPTION DLBASE, DL_FUNCS, DL_VARS, FILE, FUNCLIST, IMPORTS, NAME =item AUTHOR =item REVISION mkfh() =back __find_relocations =head2 ExtUtils::Packlist - manage .packlist files =over 4 =item SYNOPSIS =item DESCRIPTION =item USAGE =item FUNCTIONS new(), read(), write(), validate(), packlist_file() =item EXAMPLE =item AUTHOR =back =head2 ExtUtils::ParseXS - converts Perl XS code into C code =over 4 =item SYNOPSIS =item DESCRIPTION =item EXPORT =item FUNCTIONS process_file(), B<C++>, B<hiertype>, B<except>, B<typemap>, B<prototypes>, B<versioncheck>, B<linenumbers>, B<optimize>, B<inout>, B<argtypes>, B<s>, errors() =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 ExtUtils::ParseXS::Constants - Initialization values for some globals =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 ExtUtils::ParseXS::Utilities - Subroutines used with ExtUtils::ParseXS =over 4 =item SYNOPSIS =item SUBROUTINES =over 4 =item C<standard_typemap_locations()> Purpose, Arguments, Return Value =back =back =over 4 =item C<trim_whitespace()> Purpose, Argument, Return Value =back =over 4 =item C<tidy_type()> Purpose, Arguments, Return Value =back =over 4 =item C<C_string()> Purpose, Arguments, Return Value =back =over 4 =item C<valid_proto_string()> Purpose, Arguments, Return Value =back =over 4 =item C<process_typemaps()> Purpose, Arguments, Return Value =back =over 4 =item C<make_targetable()> Purpose, Arguments, Return Value =back =over 4 =item C<map_type()> Purpose, Arguments, Return Value =back =over 4 =item C<standard_XS_defs()> Purpose, Arguments, Return Value =back =over 4 =item C<assign_func_args()> Purpose, Arguments, Return Value =back =over 4 =item C<analyze_preprocessor_statements()> Purpose, Arguments, Return Value =back =over 4 =item C<set_cond()> Purpose, Arguments, Return Value =back =over 4 =item C<current_line_number()> Purpose, Arguments, Return Value =back =over 4 =item C<Warn()> Purpose, Arguments, Return Value =back =over 4 =item C<blurt()> Purpose, Arguments, Return Value =back =over 4 =item C<death()> Purpose, Arguments, Return Value =back =over 4 =item C<check_conditional_preprocessor_statements()> Purpose, Arguments, Return Value =back =over 4 =item C<escape_file_for_line_directive()> Purpose, Arguments, Return Value =back =over 4 =item C<report_typemap_failure> Purpose, Arguments, Return Value =back =head2 ExtUtils::Typemaps - Read/Write/Modify Perl/XS typemap files =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =back =over 4 =item new =back =over 4 =item file =back =over 4 =item add_typemap =back =over 4 =item add_inputmap =back =over 4 =item add_outputmap =back =over 4 =item add_string =back =over 4 =item remove_typemap =back =over 4 =item remove_inputmap =back =over 4 =item remove_inputmap =back =over 4 =item get_typemap =back =over 4 =item get_inputmap =back =over 4 =item get_outputmap =back =over 4 =item write =back =over 4 =item as_string =back =over 4 =item as_embedded_typemap =back =over 4 =item merge =back =over 4 =item is_empty =back =over 4 =item list_mapped_ctypes =back =over 4 =item _get_typemap_hash =back =over 4 =item _get_inputmap_hash =back =over 4 =item _get_outputmap_hash =back =over 4 =item _get_prototype_hash =back =over 4 =item CAVEATS =item SEE ALSO =item AUTHOR =item COPYRIGHT & LICENSE =back =head2 ExtUtils::Typemaps::Cmd - Quick commands for handling typemaps =over 4 =item SYNOPSIS =item DESCRIPTION =item EXPORTED FUNCTIONS =over 4 =item embeddable_typemap =back =item SEE ALSO =item AUTHOR =item COPYRIGHT & LICENSE =back =head2 ExtUtils::Typemaps::InputMap - Entry in the INPUT section of a typemap =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =back =over 4 =item new =back =over 4 =item code =back =over 4 =item xstype =back =over 4 =item cleaned_code =back =over 4 =item SEE ALSO =item AUTHOR =item COPYRIGHT & LICENSE =back =head2 ExtUtils::Typemaps::OutputMap - Entry in the OUTPUT section of a typemap =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =back =over 4 =item new =back =over 4 =item code =back =over 4 =item xstype =back =over 4 =item cleaned_code =back =over 4 =item targetable =back =over 4 =item SEE ALSO =item AUTHOR =item COPYRIGHT & LICENSE =back =head2 ExtUtils::Typemaps::Type - Entry in the TYPEMAP section of a typemap =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =back =over 4 =item new =back =over 4 =item proto =back =over 4 =item xstype =back =over 4 =item ctype =back =over 4 =item tidy_ctype =back =over 4 =item SEE ALSO =item AUTHOR =item COPYRIGHT & LICENSE =back =head2 ExtUtils::XSSymSet - keep sets of symbol names palatable to the VMS linker =over 4 =item SYNOPSIS =item DESCRIPTION new([$maxlen[,$silent]]), addsym($name[,$maxlen[,$silent]]), trimsym($name[,$maxlen[,$silent]]), delsym($name), get_orig($trimmed), get_trimmed($name), all_orig(), all_trimmed() =item AUTHOR =item REVISION =back =head2 ExtUtils::testlib - add blib/* directories to @INC =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 Fatal - Replace functions with equivalents which succeed or die =over 4 =item SYNOPSIS =item BEST PRACTICE =item DESCRIPTION =item DIAGNOSTICS Bad subroutine name for Fatal: %s, %s is not a Perl subroutine, %s is neither a builtin, nor a Perl subroutine, Cannot make the non-overridable %s fatal, Internal error: %s =item BUGS =item AUTHOR =item LICENSE =item SEE ALSO =back =head2 Fcntl - load the C Fcntl.h defines =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTE =item EXPORTED SYMBOLS =back =head2 File::Basename - Parse file paths into directory, filename and suffix. =over 4 =item SYNOPSIS =item DESCRIPTION =back C<fileparse> X<fileparse> C<basename> X<basename> X<filename> C<dirname> X<dirname> C<fileparse_set_fstype> X<filesystem> =over 4 =item SEE ALSO =back =head2 File::CheckTree - run many filetest checks on a tree =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR =item HISTORY =back =head2 File::Compare - Compare files or filehandles =over 4 =item SYNOPSIS =item DESCRIPTION =item RETURN =item AUTHOR =back =head2 File::Copy - Copy files or filehandles =over 4 =item SYNOPSIS =item DESCRIPTION copy X<copy> X<cp>, move X<move> X<mv> X<rename>, syscopy X<syscopy>, rmscopy($from,$to[,$date_flag]) X<rmscopy> =item RETURN =item AUTHOR =back =head2 File::DosGlob - DOS like globbing and then some =over 4 =item SYNOPSIS =item DESCRIPTION =item EXPORTS (by request only) =item BUGS =item AUTHOR =item HISTORY =item SEE ALSO =back =head2 File::Fetch - A generic file fetching mechanism =over 4 =item SYNOPSIS =item DESCRIPTION =item ACCESSORS $ff->uri, $ff->scheme, $ff->host, $ff->vol, $ff->share, $ff->path, $ff->file =back $ff->output_file =over 4 =item METHODS =over 4 =item $ff = File::Fetch->new( uri => 'http://some.where.com/dir/file.txt' ); =back =back =over 4 =item $where = $ff->fetch( [to => /my/output/dir/ | \$scalar] ) =back =over 4 =item $ff->error([BOOL]) =back =over 4 =item HOW IT WORKS =item GLOBAL VARIABLES =over 4 =item $File::Fetch::FROM_EMAIL =item $File::Fetch::USER_AGENT =item $File::Fetch::FTP_PASSIVE =item $File::Fetch::TIMEOUT =item $File::Fetch::WARN =item $File::Fetch::DEBUG =item $File::Fetch::BLACKLIST =item $File::Fetch::METHOD_FAIL =back =item MAPPING =item FREQUENTLY ASKED QUESTIONS =over 4 =item So how do I use a proxy with File::Fetch? =item I used 'lynx' to fetch a file, but its contents is all wrong! =item Files I'm trying to fetch have reserved characters or non-ASCII characters in them. What do I do? =back =item TODO Implement $PREFER_BIN =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 File::Find - Traverse a directory tree. =over 4 =item SYNOPSIS =item DESCRIPTION B<find>, B<finddepth> =over 4 =item %options C<wanted>, C<bydepth>, C<preprocess>, C<postprocess>, C<follow>, C<follow_fast>, C<follow_skip>, C<dangling_symlinks>, C<no_chdir>, C<untaint>, C<untaint_pattern>, C<untaint_skip> =item The wanted function C<$File::Find::dir> is the current directory name,, C<$_> is the current filename within that directory, C<$File::Find::name> is the complete pathname to the file =back =item WARNINGS =item CAVEAT $dont_use_nlink, symlinks =item BUGS AND CAVEATS =item HISTORY =item SEE ALSO =back =head2 File::Glob - Perl extension for BSD glob routine =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item META CHARACTERS =item EXPORTS =item POSIX FLAGS C<GLOB_ERR>, C<GLOB_LIMIT>, C<GLOB_MARK>, C<GLOB_NOCASE>, C<GLOB_NOCHECK>, C<GLOB_NOSORT>, C<GLOB_BRACE>, C<GLOB_NOMAGIC>, C<GLOB_QUOTE>, C<GLOB_TILDE>, C<GLOB_CSH>, C<GLOB_ALPHASORT> =back =item DIAGNOSTICS C<GLOB_NOSPACE>, C<GLOB_ABEND> =item NOTES =item SEE ALSO =item AUTHOR =back =head2 File::GlobMapper - Extend File Glob to Allow Input and Output Files =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Behind The Scenes =item Limitations =item Input File Glob B<~>, B<~user>, B<.>, B<*>, B<?>, B<\>, B<[]>, B<{,}>, B<()> =item Output File Glob "*", #1 =item Returned Data =back =item EXAMPLES =over 4 =item A Rename script =item A few example globmaps =back =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 File::Path - Create or remove directory trees =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION make_path( $dir1, $dir2, .... ), make_path( $dir1, $dir2, ...., \%opts ), mode => $num, verbose => $bool, error => \$err, owner => $owner, user => $owner, uid => $owner, group => $group, mkpath( $dir ), mkpath( $dir, $verbose, $mode ), mkpath( [$dir1, $dir2,...], $verbose, $mode ), mkpath( $dir1, $dir2,..., \%opt ), remove_tree( $dir1, $dir2, .... ), remove_tree( $dir1, $dir2, ...., \%opts ), verbose => $bool, safe => $bool, keep_root => $bool, result => \$res, error => \$err, rmtree( $dir ), rmtree( $dir, $verbose, $safe ), rmtree( [$dir1, $dir2,...], $verbose, $safe ), rmtree( $dir1, $dir2,..., \%opt ) =over 4 =item ERROR HANDLING B<NOTE:> =item NOTES =back =item DIAGNOSTICS mkdir [path]: [errmsg] (SEVERE), No root path(s) specified, No such file or directory, cannot fetch initial working directory: [errmsg], cannot stat initial working directory: [errmsg], cannot chdir to [dir]: [errmsg], directory [dir] changed before chdir, expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL), cannot make directory [dir] read+writeable: [errmsg], cannot read [dir]: [errmsg], cannot reset chmod [dir]: [errmsg], cannot remove [dir] when cwd is [dir], cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL), cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL), previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL), cannot make directory [dir] writeable: [errmsg], cannot remove directory [dir]: [errmsg], cannot restore permissions of [dir] to [0nnn]: [errmsg], cannot make file [file] writeable: [errmsg], cannot unlink file [file]: [errmsg], cannot restore permissions of [file] to [0nnn]: [errmsg], unable to map [owner] to a uid, ownership not changed");, unable to map [group] to a gid, group ownership not changed =item SEE ALSO =item BUGS =item ACKNOWLEDGEMENTS =item AUTHORS =item COPYRIGHT =item LICENSE =back =head2 File::Spec - portably perform operations on file names =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS canonpath X<canonpath>, catdir X<catdir>, catfile X<catfile>, curdir X<curdir>, devnull X<devnull>, rootdir X<rootdir>, tmpdir X<tmpdir>, updir X<updir>, no_upwards, case_tolerant, file_name_is_absolute, path X<path>, join X<join, path>, splitpath X<splitpath> X<split, path>, splitdir X<splitdir> X<split, dir>, catpath(), abs2rel X<abs2rel> X<absolute, path> X<relative, path>, rel2abs() X<rel2abs> X<absolute, path> X<relative, path> =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 File::Spec::Cygwin - methods for Cygwin file specs =over 4 =item SYNOPSIS =item DESCRIPTION =back canonpath file_name_is_absolute tmpdir (override) case_tolerant =over 4 =item COPYRIGHT =back =head2 File::Spec::Epoc - methods for Epoc file specs =over 4 =item SYNOPSIS =item DESCRIPTION =back canonpath() =over 4 =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 File::Spec::Functions - portably perform operations on file names =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Exports =back =item COPYRIGHT =item SEE ALSO =back =head2 File::Spec::Mac - File::Spec for Mac OS (Classic) =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS canonpath =back catdir() catfile curdir devnull rootdir tmpdir updir file_name_is_absolute path splitpath splitdir catpath abs2rel rel2abs =over 4 =item AUTHORS =item COPYRIGHT =item SEE ALSO =back =head2 File::Spec::OS2 - methods for OS/2 file specs =over 4 =item SYNOPSIS =item DESCRIPTION tmpdir, splitpath =item COPYRIGHT =back =head2 File::Spec::Unix - File::Spec for Unix, base for other File::Spec modules =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS canonpath() =back catdir() catfile curdir devnull rootdir tmpdir updir no_upwards case_tolerant file_name_is_absolute path join splitpath splitdir catpath() abs2rel rel2abs() =over 4 =item COPYRIGHT =item SEE ALSO =back =head2 File::Spec::VMS - methods for VMS file specs =over 4 =item SYNOPSIS =item DESCRIPTION =back canonpath (override) catdir (override) catfile (override) curdir (override) devnull (override) rootdir (override) tmpdir (override) updir (override) case_tolerant (override) path (override) file_name_is_absolute (override) splitpath (override) splitdir (override) catpath (override) abs2rel (override) rel2abs (override) =over 4 =item COPYRIGHT =item SEE ALSO =back =head2 File::Spec::Win32 - methods for Win32 file specs =over 4 =item SYNOPSIS =item DESCRIPTION devnull =back tmpdir case_tolerant file_name_is_absolute catfile canonpath splitpath splitdir catpath =over 4 =item Note For File::Spec::Win32 Maintainers =back =over 4 =item COPYRIGHT =item SEE ALSO =back =head2 File::Temp - return name and handle of a temporary file safely =over 4 =item PORTABILITY =item SYNOPSIS =item DESCRIPTION =back =over 4 =item OBJECT-ORIENTED INTERFACE B<new> =back B<newdir> B<filename> B<dirname>, B<unlink_on_destroy> B<DESTROY> =over 4 =item FUNCTIONS B<tempfile> =back B<tempdir> =over 4 =item MKTEMP FUNCTIONS B<mkstemp> =back B<mkstemps> B<mkdtemp> B<mktemp> =over 4 =item POSIX FUNCTIONS B<tmpnam> =back B<tmpfile> =over 4 =item ADDITIONAL FUNCTIONS B<tempnam> =back =over 4 =item UTILITY FUNCTIONS B<unlink0> =back B<cmpstat> B<unlink1> B<cleanup> =over 4 =item PACKAGE VARIABLES B<safe_level>, STANDARD, MEDIUM, HIGH =back TopSystemUID B<$KEEP_ALL>, B<$DEBUG> =over 4 =item WARNING =over 4 =item Temporary files and NFS =item Forking =item Directory removal =item BINMODE =back =item HISTORY =item SEE ALSO =item AUTHOR =back =head2 File::stat - by-name interface to Perl's built-in stat() functions =over 4 =item SYNOPSIS =item DESCRIPTION =item BUGS =item ERRORS -%s is not implemented on a File::stat object =item WARNINGS File::stat ignores use filetest 'access', File::stat ignores VMS ACLs =item NOTE =item AUTHOR =back =head2 FileCache - keep more files open than the system permits =over 4 =item SYNOPSIS =item DESCRIPTION cacheout EXPR, cacheout MODE, EXPR =item CAVEATS =item BUGS =back =head2 FileHandle - supply object methods for filehandles =over 4 =item SYNOPSIS =item DESCRIPTION $fh->print, $fh->printf, $fh->getline, $fh->getlines =item SEE ALSO =back =head2 Filter::Simple - Simplified source filtering =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item The Problem =item A Solution =item Disabling or changing <no> behaviour =item All-in-one interface =item Filtering only specific components of source code C<"code">, C<"code_no_comments">, C<"executable">, C<"executable_no_comments">, C<"quotelike">, C<"string">, C<"regex">, C<"all"> =item Filtering only the code parts of source code =item Using Filter::Simple with an explicit C<import> subroutine =item Using Filter::Simple and Exporter together =item How it works =back =item AUTHOR =item CONTACT =item COPYRIGHT AND LICENSE =back =head2 Filter::Util::Call - Perl Source Filter Utility Module =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item B<use Filter::Util::Call> =item B<import()> =item B<filter() and anonymous sub> B<$_>, B<$status>, B<filter_read> and B<filter_read_exact>, B<filter_del> =back =item EXAMPLES =over 4 =item Example 1: A simple filter. =item Example 2: Using the context =item Example 3: Using the context within the filter =item Example 4: Using filter_del =back =item Filter::Simple =item AUTHOR =item DATE =back =head2 FindBin - Locate directory of original perl script =over 4 =item SYNOPSIS =item DESCRIPTION =item EXPORTABLE VARIABLES =item KNOWN ISSUES =item AUTHORS =item COPYRIGHT =back =head2 GDBM_File - Perl5 access to the gdbm library. =over 4 =item SYNOPSIS =item DESCRIPTION =item AVAILABILITY =item BUGS =item SEE ALSO =back =head2 Getopt::Long - Extended processing of command line options =over 4 =item SYNOPSIS =item DESCRIPTION =item Command Line Options, an Introduction =item Getting Started with Getopt::Long =over 4 =item Simple options =item A little bit less simple options =item Mixing command line option with other arguments =item Options with values =item Options with multiple values =item Options with hash values =item User-defined subroutines to handle options =item Options with multiple names =item Case and abbreviations =item Summary of Option Specifications !, +, s, i, o, f, : I<type> [ I<desttype> ], : I<number> [ I<desttype> ], : + [ I<desttype> ] =back =item Advanced Possibilities =over 4 =item Object oriented interface =item Thread Safety =item Documentation and help texts =item Parsing options from an arbitrary array =item Parsing options from an arbitrary string =item Storing options values in a hash =item Bundling =item The lonesome dash =item Argument callback =back =item Configuring Getopt::Long default, posix_default, auto_abbrev, getopt_compat, gnu_compat, gnu_getopt, require_order, permute, bundling (default: disabled), bundling_override (default: disabled), ignore_case (default: enabled), ignore_case_always (default: disabled), auto_version (default:disabled), auto_help (default:disabled), pass_through (default: disabled), prefix, prefix_pattern, long_prefix_pattern, debug (default: disabled) =item Exportable Methods VersionMessage, C<-message>, C<-msg>, C<-exitval>, C<-output>, HelpMessage =item Return values and Errors =item Legacy =over 4 =item Default destinations =item Alternative option starters =item Configuration variables =back =item Tips and Techniques =over 4 =item Pushing multiple values in a hash option =back =item Troubleshooting =over 4 =item GetOptions does not return a false result when an option is not supplied =item GetOptions does not split the command line correctly =item Undefined subroutine &main::GetOptions called =item How do I put a "-?" option into a Getopt::Long? =back =item AUTHOR =item COPYRIGHT AND DISCLAIMER =back =head2 Getopt::Std, getopt, getopts - Process single-character switches with switch clustering =over 4 =item SYNOPSIS =item DESCRIPTION =item C<--help> and C<--version> =back =head2 HTTP::Tiny - A small, simple, correct HTTP/1.1 client =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new =item get|head|put|post|delete =item post_form =item mirror =item request =item www_form_urlencode =back =item LIMITATIONS =item SEE ALSO =item SUPPORT =over 4 =item Bugs / Feature Requests =item Source Code =back =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 Hash::Util - A selection of general-utility hash subroutines =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Restricted hashes B<lock_keys>, B<unlock_keys> =back =back B<lock_keys_plus> B<lock_value>, B<unlock_value> B<lock_hash>, B<unlock_hash> B<lock_hash_recurse>, B<unlock_hash_recurse> B<hash_unlocked> B<legal_keys>, B<hidden_keys>, B<all_keys>, B<hash_seed> B<hv_store> =over 4 =item Operating on references to hashes. lock_ref_keys, unlock_ref_keys, lock_ref_keys_plus, lock_ref_value, unlock_ref_value, lock_hashref, unlock_hashref, lock_hashref_recurse, unlock_hashref_recurse, hash_ref_unlocked, legal_ref_keys, hidden_ref_keys =back =over 4 =item CAVEATS =item BUGS =item AUTHOR =item SEE ALSO =back =head2 Hash::Util::FieldHash - Support for Inside-Out Classes =over 4 =item SYNOPSIS =item FUNCTIONS id, id_2obj, register, idhash, idhashes, fieldhash, fieldhashes =item DESCRIPTION =over 4 =item The Inside-out Technique =item Problems of Inside-out =item Solutions =item More Problems =item The Generic Object =item How to use Field Hashes =item Garbage-Collected Hashes =back =item EXAMPLES C<init()>, C<first()>, C<last()>, C<name()>, C<Name_hash>, C<Name_id>, C<Name_idhash>, C<Name_id_reg>, C<Name_idhash_reg>, C<Name_fieldhash> =over 4 =item Example 1 =item Example 2 =back =item GUTS =over 4 =item The C<PERL_MAGIC_uvar> interface for hashes =item Weakrefs call uvar magic =item How field hashes work =item Internal function Hash::Util::FieldHash::_fieldhash =back =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 I18N::Collate - compare 8-bit scalar data according to the current locale =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 I18N::LangTags - functions for dealing with RFC3066-style language tags =over 4 =item SYNOPSIS =item DESCRIPTION =back the function is_language_tag($lang1) the function extract_language_tags($whatever) the function same_language_tag($lang1, $lang2) the function similarity_language_tag($lang1, $lang2) the function is_dialect_of($lang1, $lang2) the function super_languages($lang1) the function locale2language_tag($locale_identifier) the function encode_language_tag($lang1) the function alternate_language_tags($lang1) the function @langs = panic_languages(@accept_languages) the function implicate_supers( ...languages... ), the function implicate_supers_strictly( ...languages... ) =over 4 =item ABOUT LOWERCASING =item ABOUT UNICODE PLAINTEXT LANGUAGE TAGS =item SEE ALSO =item COPYRIGHT =item AUTHOR =back =head2 I18N::LangTags::Detect - detect the user's language preferences =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS =item ENVIRONMENT =item SEE ALSO =item COPYRIGHT =item AUTHOR =back =head2 I18N::LangTags::List -- tags and names for human languages =over 4 =item SYNOPSIS =item DESCRIPTION =item ABOUT LANGUAGE TAGS =item LIST OF LANGUAGES {ab} : Abkhazian, {ace} : Achinese, {ach} : Acoli, {ada} : Adangme, {ady} : Adyghe, {aa} : Afar, {afh} : Afrihili, {af} : Afrikaans, [{afa} : Afro-Asiatic (Other)], {ak} : Akan, {akk} : Akkadian, {sq} : Albanian, {ale} : Aleut, [{alg} : Algonquian languages], [{tut} : Altaic (Other)], {am} : Amharic, {i-ami} : Ami, [{apa} : Apache languages], {ar} : Arabic, {arc} : Aramaic, {arp} : Arapaho, {arn} : Araucanian, {arw} : Arawak, {hy} : Armenian, {an} : Aragonese, [{art} : Artificial (Other)], {ast} : Asturian, {as} : Assamese, [{ath} : Athapascan languages], [{aus} : Australian languages], [{map} : Austronesian (Other)], {av} : Avaric, {ae} : Avestan, {awa} : Awadhi, {ay} : Aymara, {az} : Azerbaijani, {ban} : Balinese, [{bat} : Baltic (Other)], {bal} : Baluchi, {bm} : Bambara, [{bai} : Bamileke languages], {bad} : Banda, [{bnt} : Bantu (Other)], {bas} : Basa, {ba} : Bashkir, {eu} : Basque, {btk} : Batak (Indonesia), {bej} : Beja, {be} : Belarusian, {bem} : Bemba, {bn} : Bengali, [{ber} : Berber (Other)], {bho} : Bhojpuri, {bh} : Bihari, {bik} : Bikol, {bin} : Bini, {bi} : Bislama, {bs} : Bosnian, {bra} : Braj, {br} : Breton, {bug} : Buginese, {bg} : Bulgarian, {i-bnn} : Bunun, {bua} : Buriat, {my} : Burmese, {cad} : Caddo, {car} : Carib, {ca} : Catalan, [{cau} : Caucasian (Other)], {ceb} : Cebuano, [{cel} : Celtic (Other)], [{cai} : Central American Indian (Other)], {chg} : Chagatai, [{cmc} : Chamic languages], {ch} : Chamorro, {ce} : Chechen, {chr} : Cherokee, {chy} : Cheyenne, {chb} : Chibcha, {ny} : Chichewa, {zh} : Chinese, {chn} : Chinook Jargon, {chp} : Chipewyan, {cho} : Choctaw, {cu} : Church Slavic, {chk} : Chuukese, {cv} : Chuvash, {cop} : Coptic, {kw} : Cornish, {co} : Corsican, {cr} : Cree, {mus} : Creek, [{cpe} : English-based Creoles and pidgins (Other)], [{cpf} : French-based Creoles and pidgins (Other)], [{cpp} : Portuguese-based Creoles and pidgins (Other)], [{crp} : Creoles and pidgins (Other)], {hr} : Croatian, [{cus} : Cushitic (Other)], {cs} : Czech, {dak} : Dakota, {da} : Danish, {dar} : Dargwa, {day} : Dayak, {i-default} : Default (Fallthru) Language, {del} : Delaware, {din} : Dinka, {dv} : Divehi, {doi} : Dogri, {dgr} : Dogrib, [{dra} : Dravidian (Other)], {dua} : Duala, {nl} : Dutch, {dum} : Middle Dutch (ca.1050-1350), {dyu} : Dyula, {dz} : Dzongkha, {efi} : Efik, {egy} : Ancient Egyptian, {eka} : Ekajuk, {elx} : Elamite, {en} : English, {enm} : Old English (1100-1500), {ang} : Old English (ca.450-1100), {i-enochian} : Enochian (Artificial), {myv} : Erzya, {eo} : Esperanto, {et} : Estonian, {ee} : Ewe, {ewo} : Ewondo, {fan} : Fang, {fat} : Fanti, {fo} : Faroese, {fj} : Fijian, {fi} : Finnish, [{fiu} : Finno-Ugrian (Other)], {fon} : Fon, {fr} : French, {frm} : Middle French (ca.1400-1600), {fro} : Old French (842-ca.1400), {fy} : Frisian, {fur} : Friulian, {ff} : Fulah, {gaa} : Ga, {gd} : Scots Gaelic, {gl} : Gallegan, {lg} : Ganda, {gay} : Gayo, {gba} : Gbaya, {gez} : Geez, {ka} : Georgian, {de} : German, {gmh} : Middle High German (ca.1050-1500), {goh} : Old High German (ca.750-1050), [{gem} : Germanic (Other)], {gil} : Gilbertese, {gon} : Gondi, {gor} : Gorontalo, {got} : Gothic, {grb} : Grebo, {grc} : Ancient Greek, {el} : Modern Greek, {gn} : Guarani, {gu} : Gujarati, {gwi} : Gwich'in, {hai} : Haida, {ht} : Haitian, {ha} : Hausa, {haw} : Hawaiian, {he} : Hebrew, {hz} : Herero, {hil} : Hiligaynon, {him} : Himachali, {hi} : Hindi, {ho} : Hiri Motu, {hit} : Hittite, {hmn} : Hmong, {hu} : Hungarian, {hup} : Hupa, {iba} : Iban, {is} : Icelandic, {io} : Ido, {ig} : Igbo, {ijo} : Ijo, {ilo} : Iloko, [{inc} : Indic (Other)], [{ine} : Indo-European (Other)], {id} : Indonesian, {inh} : Ingush, {ia} : Interlingua (International Auxiliary Language Association), {ie} : Interlingue, {iu} : Inuktitut, {ik} : Inupiaq, [{ira} : Iranian (Other)], {ga} : Irish, {mga} : Middle Irish (900-1200), {sga} : Old Irish (to 900), [{iro} : Iroquoian languages], {it} : Italian, {ja} : Japanese, {jv} : Javanese, {jrb} : Judeo-Arabic, {jpr} : Judeo-Persian, {kbd} : Kabardian, {kab} : Kabyle, {kac} : Kachin, {kl} : Kalaallisut, {xal} : Kalmyk, {kam} : Kamba, {kn} : Kannada, {kr} : Kanuri, {krc} : Karachay-Balkar, {kaa} : Kara-Kalpak, {kar} : Karen, {ks} : Kashmiri, {csb} : Kashubian, {kaw} : Kawi, {kk} : Kazakh, {kha} : Khasi, {km} : Khmer, [{khi} : Khoisan (Other)], {kho} : Khotanese, {ki} : Kikuyu, {kmb} : Kimbundu, {rw} : Kinyarwanda, {ky} : Kirghiz, {i-klingon} : Klingon, {kv} : Komi, {kg} : Kongo, {kok} : Konkani, {ko} : Korean, {kos} : Kosraean, {kpe} : Kpelle, {kro} : Kru, {kj} : Kuanyama, {kum} : Kumyk, {ku} : Kurdish, {kru} : Kurukh, {kut} : Kutenai, {lad} : Ladino, {lah} : Lahnda, {lam} : Lamba, {lo} : Lao, {la} : Latin, {lv} : Latvian, {lb} : Letzeburgesch, {lez} : Lezghian, {li} : Limburgish, {ln} : Lingala, {lt} : Lithuanian, {nds} : Low German, {art-lojban} : Lojban (Artificial), {loz} : Lozi, {lu} : Luba-Katanga, {lua} : Luba-Lulua, {lui} : Luiseno, {lun} : Lunda, {luo} : Luo (Kenya and Tanzania), {lus} : Lushai, {mk} : Macedonian, {mad} : Madurese, {mag} : Magahi, {mai} : Maithili, {mak} : Makasar, {mg} : Malagasy, {ms} : Malay, {ml} : Malayalam, {mt} : Maltese, {mnc} : Manchu, {mdr} : Mandar, {man} : Mandingo, {mni} : Manipuri, [{mno} : Manobo languages], {gv} : Manx, {mi} : Maori, {mr} : Marathi, {chm} : Mari, {mh} : Marshall, {mwr} : Marwari, {mas} : Masai, [{myn} : Mayan languages], {men} : Mende, {mic} : Micmac, {min} : Minangkabau, {i-mingo} : Mingo, [{mis} : Miscellaneous languages], {moh} : Mohawk, {mdf} : Moksha, {mo} : Moldavian, [{mkh} : Mon-Khmer (Other)], {lol} : Mongo, {mn} : Mongolian, {mos} : Mossi, [{mul} : Multiple languages], [{mun} : Munda languages], {nah} : Nahuatl, {nap} : Neapolitan, {na} : Nauru, {nv} : Navajo, {nd} : North Ndebele, {nr} : South Ndebele, {ng} : Ndonga, {ne} : Nepali, {new} : Newari, {nia} : Nias, [{nic} : Niger-Kordofanian (Other)], [{ssa} : Nilo-Saharan (Other)], {niu} : Niuean, {nog} : Nogai, {non} : Old Norse, [{nai} : North American Indian], {no} : Norwegian, {nb} : Norwegian Bokmal, {nn} : Norwegian Nynorsk, [{nub} : Nubian languages], {nym} : Nyamwezi, {nyn} : Nyankole, {nyo} : Nyoro, {nzi} : Nzima, {oc} : Occitan (post 1500), {oj} : Ojibwa, {or} : Oriya, {om} : Oromo, {osa} : Osage, {os} : Ossetian; Ossetic, [{oto} : Otomian languages], {pal} : Pahlavi, {i-pwn} : Paiwan, {pau} : Palauan, {pi} : Pali, {pam} : Pampanga, {pag} : Pangasinan, {pa} : Panjabi, {pap} : Papiamento, [{paa} : Papuan (Other)], {fa} : Persian, {peo} : Old Persian (ca.600-400 B.C.), [{phi} : Philippine (Other)], {phn} : Phoenician, {pon} : Pohnpeian, {pl} : Polish, {pt} : Portuguese, [{pra} : Prakrit languages], {pro} : Old Provencal (to 1500), {ps} : Pushto, {qu} : Quechua, {rm} : Raeto-Romance, {raj} : Rajasthani, {rap} : Rapanui, {rar} : Rarotongan, [{qaa - qtz} : Reserved for local use.], [{roa} : Romance (Other)], {ro} : Romanian, {rom} : Romany, {rn} : Rundi, {ru} : Russian, [{sal} : Salishan languages], {sam} : Samaritan Aramaic, {se} : Northern Sami, {sma} : Southern Sami, {smn} : Inari Sami, {smj} : Lule Sami, {sms} : Skolt Sami, [{smi} : Sami languages (Other)], {sm} : Samoan, {sad} : Sandawe, {sg} : Sango, {sa} : Sanskrit, {sat} : Santali, {sc} : Sardinian, {sas} : Sasak, {sco} : Scots, {sel} : Selkup, [{sem} : Semitic (Other)], {sr} : Serbian, {srr} : Serer, {shn} : Shan, {sn} : Shona, {sid} : Sidamo, {sgn-...} : Sign Languages, {bla} : Siksika, {sd} : Sindhi, {si} : Sinhalese, [{sit} : Sino-Tibetan (Other)], [{sio} : Siouan languages], {den} : Slave (Athapascan), [{sla} : Slavic (Other)], {sk} : Slovak, {sl} : Slovenian, {sog} : Sogdian, {so} : Somali, {son} : Songhai, {snk} : Soninke, {wen} : Sorbian languages, {nso} : Northern Sotho, {st} : Southern Sotho, [{sai} : South American Indian (Other)], {es} : Spanish, {suk} : Sukuma, {sux} : Sumerian, {su} : Sundanese, {sus} : Susu, {sw} : Swahili, {ss} : Swati, {sv} : Swedish, {syr} : Syriac, {tl} : Tagalog, {ty} : Tahitian, [{tai} : Tai (Other)], {tg} : Tajik, {tmh} : Tamashek, {ta} : Tamil, {i-tao} : Tao, {tt} : Tatar, {i-tay} : Tayal, {te} : Telugu, {ter} : Tereno, {tet} : Tetum, {th} : Thai, {bo} : Tibetan, {tig} : Tigre, {ti} : Tigrinya, {tem} : Timne, {tiv} : Tiv, {tli} : Tlingit, {tpi} : Tok Pisin, {tkl} : Tokelau, {tog} : Tonga (Nyasa), {to} : Tonga (Tonga Islands), {tsi} : Tsimshian, {ts} : Tsonga, {i-tsu} : Tsou, {tn} : Tswana, {tum} : Tumbuka, [{tup} : Tupi languages], {tr} : Turkish, {ota} : Ottoman Turkish (1500-1928), {crh} : Crimean Turkish, {tk} : Turkmen, {tvl} : Tuvalu, {tyv} : Tuvinian, {tw} : Twi, {udm} : Udmurt, {uga} : Ugaritic, {ug} : Uighur, {uk} : Ukrainian, {umb} : Umbundu, {und} : Undetermined, {ur} : Urdu, {uz} : Uzbek, {vai} : Vai, {ve} : Venda, {vi} : Vietnamese, {vo} : Volapuk, {vot} : Votic, [{wak} : Wakashan languages], {wa} : Walloon, {wal} : Walamo, {war} : Waray, {was} : Washo, {cy} : Welsh, {wo} : Wolof, {x-...} : Unregistered (Semi-Private Use), {xh} : Xhosa, {sah} : Yakut, {yao} : Yao, {yap} : Yapese, {ii} : Sichuan Yi, {yi} : Yiddish, {yo} : Yoruba, [{ypk} : Yupik languages], {znd} : Zande, [{zap} : Zapotec], {zen} : Zenaga, {za} : Zhuang, {zu} : Zulu, {zun} : Zuni =item SEE ALSO =item COPYRIGHT AND DISCLAIMER =item AUTHOR =back =head2 I18N::Langinfo - query locale information =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item EXPORT =back =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 IO - load various IO modules =over 4 =item SYNOPSIS =item DESCRIPTION =item DEPRECATED =back =head2 IO::Compress::Base - Base Class for IO::Compress modules =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Compress::Bzip2 - Write bzip2 files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item bzip2 $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeIn => 0|1 >>, C<< Append => 0|1 >> =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< BlockSize100K => number >>, C<< WorkFactor => number >>, C<< Strict => 0|1 >> =item Examples =back =item Methods =over 4 =item print =item printf =item syswrite =item write =item flush =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item newStream([OPTS]) =back =item Importing :all =item EXAMPLES =over 4 =item Apache::GZip Revisited =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Compress::Deflate - Write RFC 1950 files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item deflate $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeIn => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< Merge => 0|1 >>, -Level, -Strategy, C<< Strict => 0|1 >> =item Examples =back =item Methods =over 4 =item print =item printf =item syswrite =item write =item flush =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item newStream([OPTS]) =item deflateParams =back =item Importing :all, :constants, :flush, :level, :strategy =item EXAMPLES =over 4 =item Apache::GZip Revisited =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Compress::FAQ -- Frequently Asked Questions about IO::Compress =over 4 =item DESCRIPTION =item GENERAL =over 4 =item Compatibility with Unix compress/uncompress. =item Accessing .tar.Z files =item How do I recompress using a different compression? =back =item ZIP =over 4 =item What Compression Types do IO::Compress::Zip & IO::Uncompress::Unzip support? Store (method 0), Deflate (method 8), Bzip2 (method 12), Lzma (method 14) =item Can I Read/Write Zip files larger the 4 Gig? =item Zip Resources =back =item GZIP =over 4 =item Gzip Resources =back =item ZLIB =over 4 =item Zlib Resources =back =item HTTP & NETWORK =over 4 =item Apache::GZip Revisited =item Compressed files and Net::FTP =back =item MISC =over 4 =item Using C<InputLength> to uncompress data embedded in a larger file/buffer. =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Compress::Gzip - Write RFC 1952 files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item gzip $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeIn => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< Merge => 0|1 >>, -Level, -Strategy, C<< Minimal => 0|1 >>, C<< Comment => $comment >>, C<< Name => $string >>, C<< Time => $number >>, C<< TextFlag => 0|1 >>, C<< HeaderCRC => 0|1 >>, C<< OS_Code => $value >>, C<< ExtraField => $data >>, C<< ExtraFlags => $value >>, C<< Strict => 0|1 >> =item Examples =back =item Methods =over 4 =item print =item printf =item syswrite =item write =item flush =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item newStream([OPTS]) =item deflateParams =back =item Importing :all, :constants, :flush, :level, :strategy =item EXAMPLES =over 4 =item Apache::GZip Revisited =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Compress::RawDeflate - Write RFC 1951 files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item rawdeflate $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeIn => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< Merge => 0|1 >>, -Level, -Strategy, C<< Strict => 0|1 >> =item Examples =back =item Methods =over 4 =item print =item printf =item syswrite =item write =item flush =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item newStream([OPTS]) =item deflateParams =back =item Importing :all, :constants, :flush, :level, :strategy =item EXAMPLES =over 4 =item Apache::GZip Revisited =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Compress::Zip - Write zip files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item zip $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeIn => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< Name => $string >>, C<< CanonicalName => 0|1 >>, C<< FilterName => sub { ... } >>, C<< Time => $number >>, C<< ExtAttr => $attr >>, C<< exTime => [$atime, $mtime, $ctime] >>, C<< exUnix2 => [$uid, $gid] >>, C<< exUnixN => [$uid, $gid] >>, C<< Comment => $comment >>, C<< ZipComment => $comment >>, C<< Method => $method >>, C<< Stream => 0|1 >>, C<< Zip64 => 0|1 >>, C<< TextFlag => 0|1 >>, C<< ExtraFieldLocal => $data >> =item C<< ExtraFieldCentral => $data >>, C<< Minimal => 1|0 >>, C<< BlockSize100K => number >>, C<< WorkFactor => number >>, C<< Preset => number >>, C<< Extreme => 0|1 >>, -Level, -Strategy, C<< Strict => 0|1 >> =item Examples =back =item Methods =over 4 =item print =item printf =item syswrite =item write =item flush =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item newStream([OPTS]) =item deflateParams =back =item Importing :all, :constants, :flush, :level, :strategy, :zip_method =item EXAMPLES =over 4 =item Apache::GZip Revisited =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Dir - supply object methods for directory handles =over 4 =item SYNOPSIS =item DESCRIPTION new ( [ DIRNAME ] ), open ( DIRNAME ), read (), seek ( POS ), tell (), rewind (), close (), tie %hash, 'IO::Dir', DIRNAME [, OPTIONS ] =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 IO::File - supply object methods for filehandles =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( FILENAME [,MODE [,PERMS]] ), new_tmpfile =item METHODS open( FILENAME [,MODE [,PERMS]] ), open( FILENAME, IOLAYERS ), binmode( [LAYER] ) =item NOTE =item SEE ALSO =item HISTORY =back =head2 IO::Handle - supply object methods for I/O handles =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new (), new_from_fd ( FD, MODE ) =item METHODS $io->fdopen ( FD, MODE ), $io->opened, $io->getline, $io->getlines, $io->ungetc ( ORD ), $io->write ( BUF, LEN [, OFFSET ] ), $io->error, $io->clearerr, $io->sync, $io->flush, $io->printflush ( ARGS ), $io->blocking ( [ BOOL ] ), $io->untaint =item NOTE =item SEE ALSO =item BUGS =item HISTORY =back =head2 IO::Pipe - supply object methods for pipes =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( [READER, WRITER] ) =item METHODS reader ([ARGS]), writer ([ARGS]), handles () =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 IO::Poll - Object interface to system poll call =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS mask ( IO [, EVENT_MASK ] ), poll ( [ TIMEOUT ] ), events ( IO ), remove ( IO ), handles( [ EVENT_MASK ] ) =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 IO::Seekable - supply seek based methods for I/O objects =over 4 =item SYNOPSIS =item DESCRIPTION $io->getpos, $io->setpos, $io->seek ( POS, WHENCE ), WHENCE=0 (SEEK_SET), WHENCE=1 (SEEK_CUR), WHENCE=2 (SEEK_END), $io->sysseek( POS, WHENCE ), $io->tell =item SEE ALSO =item HISTORY =back =head2 IO::Select - OO interface to the select system call =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( [ HANDLES ] ) =item METHODS add ( HANDLES ), remove ( HANDLES ), exists ( HANDLE ), handles, can_read ( [ TIMEOUT ] ), can_write ( [ TIMEOUT ] ), has_exception ( [ TIMEOUT ] ), count (), bits(), select ( READ, WRITE, EXCEPTION [, TIMEOUT ] ) =item EXAMPLE =item AUTHOR =item COPYRIGHT =back =head2 IO::Socket - Object interface to socket communications =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( [ARGS] ) =item METHODS accept([PKG]), socketpair(DOMAIN, TYPE, PROTOCOL), atmark, connected, protocol, sockdomain, sockopt(OPT [, VAL]), getsockopt(LEVEL, OPT), setsockopt(LEVEL, OPT, VAL), socktype, timeout([VAL]) =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 IO::Socket::INET - Object interface for AF_INET domain sockets =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( [ARGS] ) =over 4 =item METHODS sockaddr (), sockport (), sockhost (), peeraddr (), peerport (), peerhost () =back =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 IO::Socket::UNIX - Object interface for AF_UNIX domain sockets =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( [ARGS] ) =item METHODS hostpath(), peerpath() =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 IO::Uncompress::AnyInflate - Uncompress zlib-based (zip, gzip) file/buffer =over 4 =item SYNOPSIS =item DESCRIPTION RFC 1950, RFC 1951 (optionally), gzip (RFC 1952), zip =item Functional Interface =over 4 =item anyinflate $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeOut => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< MultiStream => 0|1 >>, C<< TrailingData => $scalar >> =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< MultiStream => 0|1 >>, C<< Prime => $string >>, C<< Transparent => 0|1 >>, C<< BlockSize => $num >>, C<< InputLength => $size >>, C<< Append => 0|1 >>, C<< Strict => 0|1 >>, C<< RawInflate => 0|1 >>, C<< ParseExtra => 0|1 >> If the gzip FEXTRA header field is present and this option is set, it will force the module to check that it conforms to the sub-field structure as defined in RFC 1952 =item Examples =back =item Methods =over 4 =item read =item read =item getline =item getc =item ungetc =item inflateSync =item getHeaderInfo =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item nextStream =item trailingData =back =item Importing :all =item EXAMPLES =over 4 =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Uncompress::AnyUncompress - Uncompress gzip, zip, bzip2 or lzop file/buffer =over 4 =item SYNOPSIS =item DESCRIPTION RFC 1950, RFC 1951 (optionally), gzip (RFC 1952), zip, bzip2, lzop, lzf, lzma, xz =item Functional Interface =over 4 =item anyuncompress $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeOut => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< MultiStream => 0|1 >>, C<< TrailingData => $scalar >> =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< MultiStream => 0|1 >>, C<< Prime => $string >>, C<< Transparent => 0|1 >>, C<< BlockSize => $num >>, C<< InputLength => $size >>, C<< Append => 0|1 >>, C<< Strict => 0|1 >>, C<< RawInflate => 0|1 >>, C<< UnLzma => 0|1 >> =item Examples =back =item Methods =over 4 =item read =item read =item getline =item getc =item ungetc =item getHeaderInfo =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item nextStream =item trailingData =back =item Importing :all =item EXAMPLES =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Uncompress::Base - Base Class for IO::Uncompress modules =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Uncompress::Bunzip2 - Read bzip2 files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item bunzip2 $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeOut => 0|1 >>, C<< Append => 0|1 >>, C<< MultiStream => 0|1 >>, C<< TrailingData => $scalar >> =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< MultiStream => 0|1 >>, C<< Prime => $string >>, C<< Transparent => 0|1 >>, C<< BlockSize => $num >>, C<< InputLength => $size >>, C<< Append => 0|1 >>, C<< Strict => 0|1 >>, C<< Small => 0|1 >> =item Examples =back =item Methods =over 4 =item read =item read =item getline =item getc =item ungetc =item getHeaderInfo =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item nextStream =item trailingData =back =item Importing :all =item EXAMPLES =over 4 =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Uncompress::Gunzip - Read RFC 1952 files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item gunzip $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeOut => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< MultiStream => 0|1 >>, C<< TrailingData => $scalar >> =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< MultiStream => 0|1 >>, C<< Prime => $string >>, C<< Transparent => 0|1 >>, C<< BlockSize => $num >>, C<< InputLength => $size >>, C<< Append => 0|1 >>, C<< Strict => 0|1 >>, C<< ParseExtra => 0|1 >> If the gzip FEXTRA header field is present and this option is set, it will force the module to check that it conforms to the sub-field structure as defined in RFC 1952 =item Examples =back =item Methods =over 4 =item read =item read =item getline =item getc =item ungetc =item inflateSync =item getHeaderInfo Name, Comment =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item nextStream =item trailingData =back =item Importing :all =item EXAMPLES =over 4 =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Uncompress::Inflate - Read RFC 1950 files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item inflate $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeOut => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< MultiStream => 0|1 >>, C<< TrailingData => $scalar >> =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< MultiStream => 0|1 >>, C<< Prime => $string >>, C<< Transparent => 0|1 >>, C<< BlockSize => $num >>, C<< InputLength => $size >>, C<< Append => 0|1 >>, C<< Strict => 0|1 >> =item Examples =back =item Methods =over 4 =item read =item read =item getline =item getc =item ungetc =item inflateSync =item getHeaderInfo =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item nextStream =item trailingData =back =item Importing :all =item EXAMPLES =over 4 =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Uncompress::RawInflate - Read RFC 1951 files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item rawinflate $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeOut => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< MultiStream => 0|1 >>, C<< TrailingData => $scalar >> =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< AutoClose => 0|1 >>, C<< MultiStream => 0|1 >>, C<< Prime => $string >>, C<< Transparent => 0|1 >>, C<< BlockSize => $num >>, C<< InputLength => $size >>, C<< Append => 0|1 >>, C<< Strict => 0|1 >> =item Examples =back =item Methods =over 4 =item read =item read =item getline =item getc =item ungetc =item inflateSync =item getHeaderInfo =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item nextStream =item trailingData =back =item Importing :all =item EXAMPLES =over 4 =item Working with Net::FTP =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Uncompress::Unzip - Read zip files/buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item Functional Interface =over 4 =item unzip $input => $output [, OPTS] A filename, A filehandle, A scalar reference, An array reference, An Input FileGlob string, A filename, A filehandle, A scalar reference, An Array Reference, An Output FileGlob =item Notes =item Optional Parameters C<< AutoClose => 0|1 >>, C<< BinModeOut => 0|1 >>, C<< Append => 0|1 >>, A Buffer, A Filename, A Filehandle, C<< MultiStream => 0|1 >>, C<< TrailingData => $scalar >> =item Examples =back =item OO Interface =over 4 =item Constructor A filename, A filehandle, A scalar reference =item Constructor Options C<< Name => "membername" >>, C<< AutoClose => 0|1 >>, C<< MultiStream => 0|1 >>, C<< Prime => $string >>, C<< Transparent => 0|1 >>, C<< BlockSize => $num >>, C<< InputLength => $size >>, C<< Append => 0|1 >>, C<< Strict => 0|1 >> =item Examples =back =item Methods =over 4 =item read =item read =item getline =item getc =item ungetc =item inflateSync =item getHeaderInfo =item tell =item eof =item seek =item binmode =item opened =item autoflush =item input_line_number =item fileno =item close =item nextStream =item trailingData =back =item Importing :all =item EXAMPLES =over 4 =item Working with Net::FTP =item Walking through a zip file =back =item SEE ALSO =item AUTHOR =item MODIFICATION HISTORY =item COPYRIGHT AND LICENSE =back =head2 IO::Zlib - IO:: style interface to L<Compress::Zlib> =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( [ARGS] ) =item OBJECT METHODS open ( FILENAME, MODE ), opened, close, getc, getline, getlines, print ( ARGS... ), read ( BUF, NBYTES, [OFFSET] ), eof, seek ( OFFSET, WHENCE ), tell, setpos ( POS ), getpos ( POS ) =item USING THE EXTERNAL GZIP =item CLASS METHODS has_Compress_Zlib, gzip_external, gzip_used, gzip_read_open, gzip_write_open =item DIAGNOSTICS IO::Zlib::getlines: must be called in list context, IO::Zlib::gzopen_external: mode '...' is illegal, IO::Zlib::import: '...' is illegal, IO::Zlib::import: ':gzip_external' requires an argument, IO::Zlib::import: 'gzip_read_open' requires an argument, IO::Zlib::import: 'gzip_read' '...' is illegal, IO::Zlib::import: 'gzip_write_open' requires an argument, IO::Zlib::import: 'gzip_write_open' '...' is illegal, IO::Zlib::import: no Compress::Zlib and no external gzip, IO::Zlib::open: needs a filename, IO::Zlib::READ: NBYTES must be specified, IO::Zlib::WRITE: too long LENGTH =item SEE ALSO =item HISTORY =item COPYRIGHT =back =head2 IPC::Cmd - finding and running system commands made easy =over 4 =item SYNOPSIS =item DESCRIPTION =item CLASS METHODS =over 4 =item $ipc_run_version = IPC::Cmd->can_use_ipc_run( [VERBOSE] ) =back =back =over 4 =item $ipc_open3_version = IPC::Cmd->can_use_ipc_open3( [VERBOSE] ) =back =over 4 =item $bool = IPC::Cmd->can_capture_buffer =back =over 4 =item $bool = IPC::Cmd->can_use_run_forked =back =over 4 =item FUNCTIONS =over 4 =item $path = can_run( PROGRAM ); =back =back =over 4 =item $ok | ($ok, $err, $full_buf, $stdout_buff, $stderr_buff) = run( command => COMMAND, [verbose => BOOL, buffer => \$SCALAR, timeout => DIGIT] ); command, verbose, buffer, timeout, success, error message, full_buffer, out_buffer, error_buffer =back =over 4 =item $hashref = run_forked( COMMAND, { child_stdin => SCALAR, timeout => DIGIT, stdout_handler => CODEREF, stderr_handler => CODEREF} ); C<timeout>, C<child_stdin>, C<stdout_handler>, C<stderr_handler>, C<discard_output>, C<terminate_on_parent_sudden_death>, C<exit_code>, C<timeout>, C<stdout>, C<stderr>, C<merged>, C<err_msg> =back =over 4 =item $q = QUOTE =back =over 4 =item HOW IT WORKS =item Global Variables =over 4 =item $IPC::Cmd::VERBOSE =item $IPC::Cmd::USE_IPC_RUN =item $IPC::Cmd::USE_IPC_OPEN3 =item $IPC::Cmd::WARN =item $IPC::Cmd::INSTANCES =item $IPC::Cmd::ALLOW_NULL_ARGS =back =item Caveats Whitespace and IPC::Open3 / system(), Whitespace and IPC::Run, IO Redirect, Interleaving STDOUT/STDERR =item See Also =item ACKNOWLEDGEMENTS =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 IPC::Msg - SysV Msg IPC object class =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS new ( KEY , FLAGS ), id, rcv ( BUF, LEN [, TYPE [, FLAGS ]] ), remove, set ( STAT ), set ( NAME => VALUE [, NAME => VALUE ...] ), snd ( TYPE, MSG [, FLAGS ] ), stat =item SEE ALSO =item AUTHORS =item COPYRIGHT =back =head2 IPC::Open2 - open a process for both reading and writing using open2() =over 4 =item SYNOPSIS =item DESCRIPTION =item WARNING =item SEE ALSO =back =head2 IPC::Open3 - open a process for reading, writing, and error handling using open3() =over 4 =item SYNOPSIS =item DESCRIPTION =item See Also L<IPC::Open2>, L<IPC::Run> =item WARNING =back =head2 IPC::Semaphore - SysV Semaphore IPC object class =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS new ( KEY , NSEMS , FLAGS ), getall, getncnt ( SEM ), getpid ( SEM ), getval ( SEM ), getzcnt ( SEM ), id, op ( OPLIST ), remove, set ( STAT ), set ( NAME => VALUE [, NAME => VALUE ...] ), setall ( VALUES ), setval ( N , VALUE ), stat =item SEE ALSO =item AUTHORS =item COPYRIGHT =back =head2 IPC::SharedMem - SysV Shared Memory IPC object class =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS new ( KEY , SIZE , FLAGS ), id, read ( POS, SIZE ), write ( STRING, POS, SIZE ), remove, is_removed, stat, attach ( [FLAG] ), detach, addr =item SEE ALSO =item AUTHORS =item COPYRIGHT =back =head2 IPC::SysV - System V IPC constants and system calls =over 4 =item SYNOPSIS =item DESCRIPTION ftok( PATH ), ftok( PATH, ID ), shmat( ID, ADDR, FLAG ), shmdt( ADDR ), memread( ADDR, VAR, POS, SIZE ), memwrite( ADDR, STRING, POS, SIZE ) =item SEE ALSO =item AUTHORS =item COPYRIGHT =back =head2 JSON::PP - JSON::XS compatible pure-Perl module. =over 4 =item SYNOPSIS =item VERSION =item NOTE =item DESCRIPTION =over 4 =item FEATURES correct unicode handling, round-trip integrity, strict checking of JSON correctness =back =item FUNCTIONAL INTERFACE =over 4 =item encode_json =item decode_json =item JSON::PP::is_bool =item JSON::PP::true =item JSON::PP::false =item JSON::PP::null =back =item HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER =item METHODS =over 4 =item new =item ascii =item latin1 =item utf8 =item pretty =item indent =item space_before =item space_after =item relaxed list items can have an end-comma, shell-style '#'-comments =item canonical =item allow_nonref =item allow_unknown =item allow_blessed =item convert_blessed =item filter_json_object =item filter_json_single_key_object =item shrink =item max_depth =item max_size =item encode =item decode =item decode_prefix =back =item INCREMENTAL PARSING =over 4 =item incr_parse =item incr_text =item incr_skip =item incr_reset =back =item JSON::PP OWN METHODS =over 4 =item allow_singlequote =item allow_barekey =item allow_bignum =item loose =item escape_slash =item indent_length =item sort_by =back =item INTERNAL PP_encode_box, PP_decode_box =item MAPPING =over 4 =item JSON -> PERL object, array, string, number, true, false, null =item PERL -> JSON hash references, array references, other references, JSON::PP::true, JSON::PP::false, JSON::PP::null, blessed objects, simple scalars, Big Number =back =item UNICODE HANDLING ON PERLS =over 4 =item Perl 5.8 and later =item Perl 5.6 =item Perl 5.005 =back =item TODO speed, memory saving =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 JSON::PP::Boolean - dummy module providing JSON::PP::Boolean =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item AUTHOR =back =head2 List::Util - A selection of general-utility list subroutines =over 4 =item SYNOPSIS =item DESCRIPTION first BLOCK LIST, max LIST, maxstr LIST, min LIST, minstr LIST, reduce BLOCK LIST, shuffle LIST, sum LIST =item KNOWN BUGS =item SUGGESTED ADDITIONS =item SEE ALSO =item COPYRIGHT =back =head2 List::Util::XS - Indicate if List::Util was compiled with a C compiler =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item COPYRIGHT =back =head2 Locale::Codes - a distribution of modules to handle locale codes =over 4 =item DESCRIPTION B<Locale::Codes::Country, Locale::Country>, B<Locale::Codes::Language, Locale::Language>, B<Locale::Codes::Currency, Locale::Currency>, B<Locale::Codes::Script, Locale::Script>, B<Locale::Codes::LangExt>, B<Locale::Codes::LangVar>, B<Locale::Codes::LangFam>, B<Locale::Codes>, B<Locale::Codes::Constants>, B<Locale::Codes::Country_codes>, B<Locale::Codes::Language_codes>, B<Locale::Codes::Currency_codes>, B<Locale::Codes::Script_codes>, B<Locale::Codes::LangExt_codes>, B<Locale::Codes::LangVar_codes>, B<Locale::Codes::LangFam_codes> =item NEW CODE SETS B<General-use code set>, B<An official source of data>, B<A free source of the data>, B<A reliable source of data> =item COMMON ALIASES =item DEPRECATED CODES =item SEE ALSO B<Locale::Codes::API>, B<Locale::Codes::Country>, B<Locale::Codes::Language>, B<Locale::Codes::Script>, B<Locale::Codes::Currency>, B<Locale::Codes::Changes> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::API - a description of the callable function in each module =over 4 =item DESCRIPTION =item ROUTINES B<code2XXX ( CODE [,CODESET] [,'retired'] )>, B<XXX2code ( NAME [,CODESET] [,'retired'] )>, B<XXX_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_XXX_codes ( [CODESET] [,'retired'] )>, B<all_XXX_names ( [CODESET] [,'retired'] )> =item SEMI-PRIVATE ROUTINES B<MODULE::rename_XXX ( CODE ,NEW_NAME [,CODESET] )>, B<MODULE::add_XXX ( CODE ,NAME [,CODESET] )>, B<MODULE::delete_XXX ( CODE [,CODESET] )>, B<MODULE::add_XXX_alias ( NAME ,NEW_NAME )>, B<MODULE::delete_XXX_alias ( NAME )>, B<MODULE::rename_XXX_code ( CODE ,NEW_CODE [,CODESET] )>, B<MODULE::add_XXX_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<MODULE::delete_XXX_code_alias ( CODE [,CODESET] )> =item KNOWN BUGS AND LIMITATIONS B<*>, B<*> =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Changes - details changes to Locale::Codes =over 4 =item SYNOPSIS =item VERSION 3.22 (yyyy-mm-dd; sbeck) =item VERSION 3.21 (2012-03-01; sbeck) =item VERSION 3.20 (2011-12-01; sbeck) B<Added limited support for deprecated codes>, B<Fixed capitalization>, B<Pod tests off by default>, B<Codesets may be specified by name>, B<alias_code deprecated>, B<Code cleanup>, B<Added LangFam module> =item VERSION 3.18 (2011-08-31; sbeck) B<No longer use CIA data> =item VERSION 3.17 (2011-06-28; sbeck) B<Added new types of codes>, B<Added new codeset(s)>, B<Bug fixes>, B<Reorganized code> =item VERSION 3.16 (2011-03-01; sbeck) =item VERSION 3.15 (2010-12-02; sbeck) B<Minor fixes> =item VERSION 3.14 (2010-09-28; sbeck) B<Bug fixes> =item VERSION 3.13 (2010-06-04; sbeck) =item VERSION 3.12 (2010-04-06; sbeck) B<Reorganized code> =item VERSION 3.11 (2010-03-01; sbeck) B<Added new codeset(s)>, B<Bug fixes> =item VERSION 3.10 (2010-02-18; sbeck) B<Reorganized code>, B<(!) Changed XXX_code2code behavior slightly>, B<Added many semi-private routines>, B<New aliases> =item VERSION 3.01 (2010-02-15; sbeck) B<Fixed Makefile.PL and Build.PL> =item VERSION 3.00 (2010-02-10; sbeck) B<New maintainer>, B<(*) (!) All codes are generated from standards>, B<Added new codeset(s)>, B<(*) (!) Locale::Script changed>, B<Added missing functions>, B<(!) Dropped support for _alias_code>, B<(!) All functions return the standard value>, B<(!) rename_country function altered> =item VERSION 2.07 (2004-06-10; neilb) =item VERSION 2.06 (2002-07-15; neilb) =item VERSION 2.05 (2002-07-08; neilb) =item VERSION 2.04 (2002-05-23; neilb) =item VERSION 2.03 (2002-03-24; neilb) =item VERSION 2.02 (2002-03-09; neilb) =item VERSION 2.01 (2002-02-18; neilb) =item VERSION 2.00 (2002-02-17; neilb) =item VERSION 1.06 (2001-03-04; neilb) =item VERSION 1.05 (2001-02-13; neilb) =item VERSION 1.04 (2000-12-21; neilb) =item VERSION 1.03 (2000-12-??; neilb) =item VERSION 1.02 (2000-05-04; neilb) =item VERSION 1.00 (1998-03-09; neilb) =item VERSION 0.003 (1997-05-09; neilb) =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Constants - constants for Locale codes =over 4 =item DESCRIPTION =item KNOWN BUGS AND LIMITATIONS =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Country - standard codes for country identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha-2, LOCALE_CODE_ALPHA_2>, B<alpha-3, LOCALE_CODE_ALPHA_3>, B<numeric, LOCALE_CODE_NUMERIC>, B<fips-10, LOCALE_CODE_FIPS>, B<dom, LOCALE_CODE_DOM> =item ROUTINES B<code2country ( CODE [,CODESET] )>, B<country2code ( NAME [,CODESET] )>, B<country_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_country_codes ( [CODESET] )>, B<all_country_names ( [CODESET] )>, B<Locale::Codes::Country::rename_country ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Codes::Country::add_country ( CODE ,NAME [,CODESET] )>, B<Locale::Codes::Country::delete_country ( CODE [,CODESET] )>, B<Locale::Codes::Country::add_country_alias ( NAME ,NEW_NAME )>, B<Locale::Codes::Country::delete_country_alias ( NAME )>, B<Locale::Codes::Country::rename_country_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::Country::add_country_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::Country::delete_country_code_alias ( CODE [,CODESET] )>, B<alias_code ( ALIAS, CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<Locale::SubCountry>, B<http://www.iso.org/iso/country_codes>, B<http://www.iso.org/iso/list-en1-semic-3.txt>, B<http://unstats.un.org/unsd/methods/m49/m49alpha.htm>, B<http://earth-info.nga.mil/gns/html/digraphs.htm>, B<http://www.iana.org/domains/>, B<https://www.cia.gov/library/publications/the-world-factbook/appendix/prin t_appendix-d.html>, B<http://www.statoids.com/wab.html> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Country_Codes - country codes for the Locale::Codes::Country module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Country_Retired - retired country codes for the Locale::Codes::Country module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Currency - standard codes for currency identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha, LOCALE_CURR_ALPHA>, B<num, LOCALE_CURR_NUMERIC> =item ROUTINES B<code2currency ( CODE [,CODESET] )>, B<currency2code ( NAME [,CODESET] )>, B<currency_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_currency_codes ( [CODESET] )>, B<all_currency_names ( [CODESET] )>, B<Locale::Codes::Currency::rename_currency ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Codes::Currency::add_currency ( CODE ,NAME [,CODESET] )>, B<Locale::Codes::Currency::delete_currency ( CODE [,CODESET] )>, B<Locale::Codes::Currency::add_currency_alias ( NAME ,NEW_NAME )>, B<Locale::Codes::Currency::delete_currency_alias ( NAME )>, B<Locale::Codes::Currency::rename_currency_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::Currency::add_currency_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::Currency::delete_currency_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.iso.org/iso/support/currency_codes_list-1.htm> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Currency_Codes - currency codes for the Locale::Codes::Currency module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Currency_Retired - retired currency codes for the Locale::Codes::Currency module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangExt - standard codes for language extension identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha> =item ROUTINES B<code2langext ( CODE [,CODESET] )>, B<langext2code ( NAME [,CODESET] )>, B<langext_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_langext_codes ( [CODESET] )>, B<all_langext_names ( [CODESET] )>, B<Locale::Codes::LangExt::rename_langext ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Codes::LangExt::add_langext ( CODE ,NAME [,CODESET] )>, B<Locale::Codes::LangExt::delete_langext ( CODE [,CODESET] )>, B<Locale::Codes::LangExt::add_langext_alias ( NAME ,NEW_NAME )>, B<Locale::Codes::LangExt::delete_langext_alias ( NAME )>, B<Locale::Codes::LangExt::rename_langext_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::LangExt::add_langext_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::LangExt::delete_langext_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.iana.org/assignments/language-subtag-registry> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangExt_Codes - langext codes for the Locale::Codes::LangExt module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangExt_Retired - retired langext codes for the Locale::Codes::LangExt module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangFam - standard codes for language extension identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha> =item ROUTINES B<code2langfam ( CODE [,CODESET] )>, B<langfam2code ( NAME [,CODESET] )>, B<langfam_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_langfam_codes ( [CODESET] )>, B<all_langfam_names ( [CODESET] )>, B<Locale::Codes::LangFam::rename_langfam ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Codes::LangFam::add_langfam ( CODE ,NAME [,CODESET] )>, B<Locale::Codes::LangFam::delete_langfam ( CODE [,CODESET] )>, B<Locale::Codes::LangFam::add_langfam_alias ( NAME ,NEW_NAME )>, B<Locale::Codes::LangFam::delete_langfam_alias ( NAME )>, B<Locale::Codes::LangFam::rename_langfam_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::LangFam::add_langfam_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::LangFam::delete_langfam_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.loc.gov/standards/iso639-5/id.php> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangFam_Codes - langfam codes for the Locale::Codes::LangFam module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangFam_Retired - retired langfam codes for the Locale::Codes::LangFam module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangVar - standard codes for language variation identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha> =item ROUTINES B<code2langvar ( CODE [,CODESET] )>, B<langvar2code ( NAME [,CODESET] )>, B<langvar_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_langvar_codes ( [CODESET] )>, B<all_langvar_names ( [CODESET] )>, B<Locale::Codes::LangVar::rename_langvar ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Codes::LangVar::add_langvar ( CODE ,NAME [,CODESET] )>, B<Locale::Codes::LangVar::delete_langvar ( CODE [,CODESET] )>, B<Locale::Codes::LangVar::add_langvar_alias ( NAME ,NEW_NAME )>, B<Locale::Codes::LangVar::delete_langvar_alias ( NAME )>, B<Locale::Codes::LangVar::rename_langvar_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::LangVar::add_langvar_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::LangVar::delete_langvar_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.iana.org/assignments/language-subtag-registry> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangVar_Codes - langvar codes for the Locale::Codes::LangVar module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::LangVar_Retired - retired langvar codes for the Locale::Codes::LangVar module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Language - standard codes for language identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha-2, LOCALE_LANG_ALPHA_2>, B<alpha-3, LOCALE_LANG_ALPHA_3>, B<term, LOCALE_LANG_TERM> =item ROUTINES B<code2language ( CODE [,CODESET] )>, B<language2code ( NAME [,CODESET] )>, B<language_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_language_codes ( [CODESET] )>, B<all_language_names ( [CODESET] )>, B<Locale::Codes::Language::rename_language ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Codes::Language::add_language ( CODE ,NAME [,CODESET] )>, B<Locale::Codes::Language::delete_language ( CODE [,CODESET] )>, B<Locale::Codes::Language::add_language_alias ( NAME ,NEW_NAME )>, B<Locale::Codes::Language::delete_language_alias ( NAME )>, B<Locale::Codes::Language::rename_language_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::Language::add_language_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::Language::delete_language_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.loc.gov/standards/iso639-2/>, B<http://www.loc.gov/standards/iso639-5/>, B<http://www.iana.org/assignments/language-subtag-registry> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Language_Codes - language codes for the Locale::Codes::Language module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Language_Retired - retired language codes for the Locale::Codes::Language module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Script - standard codes for script identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha, LOCALE_SCRIPT_ALPHA>, B<num, LOCALE_SCRIPT_NUMERIC> =item ROUTINES B<code2script ( CODE [,CODESET] )>, B<script2code ( NAME [,CODESET] )>, B<script_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_script_codes ( [CODESET] )>, B<all_script_names ( [CODESET] )>, B<Locale::Codes::Script::rename_script ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Codes::Script::add_script ( CODE ,NAME [,CODESET] )>, B<Locale::Codes::Script::delete_script ( CODE [,CODESET] )>, B<Locale::Codes::Script::add_script_alias ( NAME ,NEW_NAME )>, B<Locale::Codes::Script::delete_script_alias ( NAME )>, B<Locale::Codes::Script::rename_script_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::Script::add_script_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Codes::Script::delete_script_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.unicode.org/iso15924/>, B<http://www.iana.org/assignments/language-subtag-registry> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Script_Codes - script codes for the Locale::Codes::Script module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Codes::Script_Retired - retired script codes for the Locale::Codes::Script module =over 4 =item SYNOPSIS =item AUTHOR =item COPYRIGHT =back =head2 Locale::Country - standard codes for country identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha-2, LOCALE_CODE_ALPHA_2>, B<alpha-3, LOCALE_CODE_ALPHA_3>, B<numeric, LOCALE_CODE_NUMERIC>, B<fips-10, LOCALE_CODE_FIPS>, B<dom, LOCALE_CODE_DOM> =item ROUTINES B<code2country ( CODE [,CODESET] )>, B<country2code ( NAME [,CODESET] )>, B<country_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_country_codes ( [CODESET] )>, B<all_country_names ( [CODESET] )>, B<Locale::Country::rename_country ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Country::add_country ( CODE ,NAME [,CODESET] )>, B<Locale::Country::delete_country ( CODE [,CODESET] )>, B<Locale::Country::add_country_alias ( NAME ,NEW_NAME )>, B<Locale::Country::delete_country_alias ( NAME )>, B<Locale::Country::rename_country_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Country::add_country_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Country::delete_country_code_alias ( CODE [,CODESET] )>, B<alias_code ( ALIAS, CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<Locale::SubCountry>, B<http://www.iso.org/iso/country_codes>, B<http://www.iso.org/iso/list-en1-semic-3.txt>, B<http://unstats.un.org/unsd/methods/m49/m49alpha.htm>, B<http://earth-info.nga.mil/gns/html/digraphs.htm>, B<http://www.iana.org/domains/>, B<https://www.cia.gov/library/publications/the-world-factbook/appendix/prin t_appendix-d.html>, B<http://www.statoids.com/wab.html> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Currency - standard codes for currency identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha, LOCALE_CURR_ALPHA>, B<num, LOCALE_CURR_NUMERIC> =item ROUTINES B<code2currency ( CODE [,CODESET] )>, B<currency2code ( NAME [,CODESET] )>, B<currency_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_currency_codes ( [CODESET] )>, B<all_currency_names ( [CODESET] )>, B<Locale::Currency::rename_currency ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Currency::add_currency ( CODE ,NAME [,CODESET] )>, B<Locale::Currency::delete_currency ( CODE [,CODESET] )>, B<Locale::Currency::add_currency_alias ( NAME ,NEW_NAME )>, B<Locale::Currency::delete_currency_alias ( NAME )>, B<Locale::Currency::rename_currency_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Currency::add_currency_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Currency::delete_currency_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.iso.org/iso/support/currency_codes_list-1.htm> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Language - standard codes for language identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha-2, LOCALE_LANG_ALPHA_2>, B<alpha-3, LOCALE_LANG_ALPHA_3>, B<term, LOCALE_LANG_TERM> =item ROUTINES B<code2language ( CODE [,CODESET] )>, B<language2code ( NAME [,CODESET] )>, B<language_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_language_codes ( [CODESET] )>, B<all_language_names ( [CODESET] )>, B<Locale::Language::rename_language ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Language::add_language ( CODE ,NAME [,CODESET] )>, B<Locale::Language::delete_language ( CODE [,CODESET] )>, B<Locale::Language::add_language_alias ( NAME ,NEW_NAME )>, B<Locale::Language::delete_language_alias ( NAME )>, B<Locale::Language::rename_language_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Language::add_language_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Language::delete_language_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.loc.gov/standards/iso639-2/>, B<http://www.loc.gov/standards/iso639-5/>, B<http://www.iana.org/assignments/language-subtag-registry> =item AUTHOR =item COPYRIGHT =back =head2 Locale::Maketext - framework for localization =over 4 =item SYNOPSIS =item DESCRIPTION =item QUICK OVERVIEW =item METHODS =over 4 =item Construction Methods =item The "maketext" Method $lh->fail_with I<or> $lh->fail_with(I<PARAM>), $lh->failure_handler_auto =item Utility Methods $language->quant($number, $singular), $language->quant($number, $singular, $plural), $language->quant($number, $singular, $plural, $negative), $language->numf($number), $language->numerate($number, $singular, $plural, $negative), $language->sprintf($format, @items), $language->language_tag(), $language->encoding() =item Language Handle Attributes and Internals =back =item LANGUAGE CLASS HIERARCHIES =item ENTRIES IN EACH LEXICON =item BRACKET NOTATION =item AUTO LEXICONS =item READONLY LEXICONS =item CONTROLLING LOOKUP FAILURE =item HOW TO USE MAKETEXT =item SEE ALSO =item COPYRIGHT AND DISCLAIMER =item AUTHOR =back =head2 Locale::Maketext::Cookbook - recipes for using Locale::Maketext =over 4 =item INTRODUCTION =item ONESIDED LEXICONS =item DECIMAL PLACES IN NUMBER FORMATTING =back =head2 Locale::Maketext::Guts - Deprecated module to load Locale::Maketext utf8 code =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 Locale::Maketext::GutsLoader - Deprecated module to load Locale::Maketext utf8 code =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 Locale::Maketext::Simple - Simple interface to Locale::Maketext::Lexicon =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item OPTIONS =over 4 =item Class =item Path =item Style =item Export =item Subclass =item Decode =item Encoding =back =back =over 4 =item ACKNOWLEDGMENTS =item SEE ALSO =item AUTHORS =item COPYRIGHT =over 4 =item The "MIT" License =back =back =head2 Locale::Maketext::TPJ13 -- article about software localization =over 4 =item SYNOPSIS =item DESCRIPTION =item Localization and Perl: gettext breaks, Maketext fixes =over 4 =item A Localization Horror Story: It Could Happen To You =item The Linguistic View =item Breaking gettext =item Replacing gettext =item Buzzwords: Abstraction and Encapsulation =item Buzzword: Isomorphism =item Buzzword: Inheritance =item Buzzword: Concision =item The Devil in the Details =item The Proof in the Pudding: Localizing Web Sites =item References =back =back =head2 Locale::Script - standard codes for script identification =over 4 =item SYNOPSIS =item DESCRIPTION =item SUPPORTED CODE SETS B<alpha, LOCALE_SCRIPT_ALPHA>, B<num, LOCALE_SCRIPT_NUMERIC> =item ROUTINES B<code2script ( CODE [,CODESET] )>, B<script2code ( NAME [,CODESET] )>, B<script_code2code ( CODE ,CODESET ,CODESET2 )>, B<all_script_codes ( [CODESET] )>, B<all_script_names ( [CODESET] )>, B<Locale::Script::rename_script ( CODE ,NEW_NAME [,CODESET] )>, B<Locale::Script::add_script ( CODE ,NAME [,CODESET] )>, B<Locale::Script::delete_script ( CODE [,CODESET] )>, B<Locale::Script::add_script_alias ( NAME ,NEW_NAME )>, B<Locale::Script::delete_script_alias ( NAME )>, B<Locale::Script::rename_script_code ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Script::add_script_code_alias ( CODE ,NEW_CODE [,CODESET] )>, B<Locale::Script::delete_script_code_alias ( CODE [,CODESET] )> =item SEE ALSO B<Locale::Codes>, B<Locale::Codes::API>, B<http://www.unicode.org/iso15924/>, B<http://www.iana.org/assignments/language-subtag-registry> =item AUTHOR =item COPYRIGHT =back =head2 Log::Message - A generic message storing mechanism; =over 4 =item SYNOPSIS =item DESCRIPTION =item Hierarchy Log::Message, Log::Message::Item, Log::Message::Handlers, Log::Message::Config =item Options config, private, verbose, tag, level, remove, chrono =back =over 4 =item Methods =over 4 =item new =back =back =over 4 =item store message, tag, level, extra =back =over 4 =item retrieve tag, level, message, amount, chrono, remove =back =over 4 =item first =back =over 4 =item last =back =over 4 =item flush =back =over 4 =item SEE ALSO =item AUTHOR =item Acknowledgements =item COPYRIGHT =back =head2 Log::Message::Config - Configuration options for Log::Message =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =item Acknowledgements =item COPYRIGHT =back =head2 Log::Message::Handlers - Message handlers for Log::Message =over 4 =item SYNOPSIS =item DESCRIPTION =item Default Handlers =over 4 =item log =back =back =over 4 =item carp =back =over 4 =item croak =back =over 4 =item cluck =back =over 4 =item confess =back =over 4 =item die =back =over 4 =item warn =back =over 4 =item trace =back =over 4 =item Custom Handlers =item SEE ALSO =item AUTHOR =item Acknowledgements =item COPYRIGHT =back =head2 Log::Message::Item - Message objects for Log::Message =over 4 =item SYNOPSIS =item DESCRIPTION =item Methods and Accessors =over 4 =item remove =item id =item when =item message =item level =item tag =item shortmess =item longmess =item parent =back =item SEE ALSO =item AUTHOR =item Acknowledgements =item COPYRIGHT =back =head2 Log::Message::Simple - Simplified interface to Log::Message =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS =over 4 =item msg("message string" [,VERBOSE]) =item debug("message string" [,VERBOSE]) =item error("error string" [,VERBOSE]) =back =back =over 4 =item carp(); =item croak(); =item confess(); =item cluck(); =back =over 4 =item CLASS METHODS =over 4 =item Log::Message::Simple->stack() =item Log::Message::Simple->stack_as_string([TRACE]) =item Log::Message::Simple->flush() =back =back =over 4 =item GLOBAL VARIABLES $ERROR_FH, $MSG_FH, $DEBUG_FH, $STACKTRACE_ON_ERROR =back =head2 MIME::Base64 - Encoding and decoding of base64 strings =over 4 =item SYNOPSIS =item DESCRIPTION encode_base64( $bytes ), encode_base64( $bytes, $eol );, decode_base64( $str ), encode_base64url( $bytes ), decode_base64url( $str ), encoded_base64_length( $bytes ), encoded_base64_length( $bytes, $eol ), decoded_base64_length( $str ) =item EXAMPLES =item COPYRIGHT =item SEE ALSO =back =head2 MIME::QuotedPrint - Encoding and decoding of quoted-printable strings =over 4 =item SYNOPSIS =item DESCRIPTION encode_qp( $str), encode_qp( $str, $eol), encode_qp( $str, $eol, $binmode ), decode_qp( $str ) =item COPYRIGHT =item SEE ALSO =back =head2 Math::BigFloat - Arbitrary size floating point math package =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Canonical notation =item Output =item C<mantissa()>, C<exponent()> and C<parts()> =item Accuracy vs. Precision =item Rounding ffround ( +$scale ), ffround ( -$scale ), ffround ( 0 ), fround ( +$scale ), fround ( -$scale ) and fround ( 0 ) =back =item METHODS =over 4 =item accuracy =item precision() =item bexp() =item bnok() =item bpi() =item bcos() =item bsin() =item batan2() =item batan() =item bmuladd() =back =item Autocreating constants =over 4 =item Math library =item Using Math::BigInt::Lite =back =item EXPORTS =item BUGS =item CAVEATS stringify, bstr(), bdiv, brsft, Modifying and =, bpow, precision() vs. accuracy() =item SEE ALSO =item LICENSE =item AUTHORS =back =head2 Math::BigInt - Arbitrary size integer/float math package =over 4 =item SYNOPSIS =item DESCRIPTION Input, Output =item METHODS =over 4 =item config() =item accuracy() =item precision() =item brsft() =item new() =item from_oct() =item from_hex() =item from_bin() =item bnan() =item bzero() =item binf() =item bone() =item is_one()/is_zero()/is_nan()/is_inf() =item is_pos()/is_neg()/is_positive()/is_negative() =item is_odd()/is_even()/is_int() =item bcmp() =item bacmp() =item sign() =item digit() =item bneg() =item babs() =item bsgn() =item bnorm() =item bnot() =item binc() =item bdec() =item badd() =item bsub() =item bmul() =item bmuladd() =item bdiv() =item bmod() =item bmodinv() =item bmodpow() =item bpow() =item blog() =item bexp() =item bnok() =item bpi() =item bcos() =item bsin() =item batan2() =item batan() =item blsft() =item brsft() =item band() =item bior() =item bxor() =item bnot() =item bsqrt() =item broot() =item bfac() =item round() =item bround() =item bfround() =item bfloor() =item bceil() =item bgcd() =item blcm() =item exponent() =item mantissa() =item parts() =item copy() =item as_int()/as_number() =item bstr() =item bsstr() =item as_hex() =item as_bin() =item as_oct() =item numify() =item modify() =item upgrade()/downgrade() =item div_scale() =item round_mode() =back =item ACCURACY and PRECISION =over 4 =item Precision P =item Accuracy A =item Fallback F =item Rounding mode R 'trunc', 'even', 'odd', '+inf', '-inf', 'zero', 'common', Precision, Accuracy (significant digits), Setting/Accessing, Creating numbers, Usage, Precedence, Overriding globals, Local settings, Rounding, Default values, Remarks =back =item Infinity and Not a Number oct()/hex(), log(-inf), exp(), cos(), sin(), atan2() =item INTERNALS =over 4 =item MATH LIBRARY =item SIGN =item mantissa(), exponent() and parts() =back =item EXAMPLES =item Autocreating constants =item PERFORMANCE =over 4 =item Alternative math libraries =back =item SUBCLASSING =over 4 =item Subclassing Math::BigInt =back =item UPGRADING =over 4 =item Auto-upgrade bsqrt(), div(), blog(), bexp() =back =item EXPORTS =item CAVEATS bstr(), bsstr() and 'cmp', int(), length, bdiv, infinity handling, Modifying and =, bpow, Overloading -$x, Mixing different object types, bsqrt(), brsft() =item LICENSE =item SEE ALSO =item AUTHORS =back =head2 Math::BigInt::Calc - Pure Perl module to support Math::BigInt =over 4 =item SYNOPSIS =item DESCRIPTION =item THE Math::BigInt API =over 4 =item General Notes =item API version 1 I<api_version()>, I<_new(STR)>, I<_zero()>, I<_one()>, I<_two()>, I<_ten()>, I<_from_bin(STR)>, I<_from_oct(STR)>, I<_from_hex(STR)>, I<_add(OBJ1, OBJ2)>, I<_mul(OBJ1, OBJ2)>, I<_div(OBJ1, OBJ2)>, I<_sub(OBJ1, OBJ2, FLAG)>, I<_sub(OBJ1, OBJ2)>, I<_dec(OBJ)>, I<_inc(OBJ)>, I<_mod(OBJ1, OBJ2)>, I<_sqrt(OBJ)>, I<_root(OBJ, N)>, I<_fac(OBJ)>, I<_pow(OBJ1, OBJ2)>, I<_modinv(OBJ1, OBJ2)>, I<_modpow(OBJ1, OBJ2, OBJ3)>, I<_rsft(OBJ, N, B)>, I<_lsft(OBJ, N, B)>, I<_log_int(OBJ, B)>, I<_gcd(OBJ1, OBJ2)>, I<_and(OBJ1, OBJ2)>, I<_or(OBJ1, OBJ2)>, I<_xor(OBJ1, OBJ2)>, I<_is_zero(OBJ)>, I<_is_one(OBJ)>, I<_is_two(OBJ)>, I<_is_ten(OBJ)>, I<_is_even(OBJ)>, I<_is_odd(OBJ)>, I<_acmp(OBJ1, OBJ2)>, I<_str(OBJ)>, I<_as_bin(OBJ)>, I<_as_oct(OBJ)>, I<_as_hex(OBJ)>, I<_num(OBJ)>, I<_copy(OBJ)>, I<_len(OBJ)>, I<_zeros(OBJ)>, I<_digit(OBJ, N)>, I<_check(OBJ)> =item API version 2 I<_1ex(N)>, I<_nok(OBJ1, OBJ2)>, I<_alen(OBJ)> =item API optional methods I<_signed_or(OBJ1, OBJ2, SIGN1, SIGN2)>, I<_signed_and(OBJ1, OBJ2, SIGN1, SIGN2)>, I<_signed_xor(OBJ1, OBJ2, SIGN1, SIGN2)> =back =item WRAP YOUR OWN =item LICENSE =item AUTHORS =item SEE ALSO =back =head2 Math::BigInt::CalcEmu - Emulate low-level math with BigInt code =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item __emu_bxor =item __emu_band =item __emu_bior =back =item LICENSE =item AUTHORS =item SEE ALSO =back =head2 Math::BigInt::FastCalc - Math::BigInt::Calc with some XS for more speed =over 4 =item SYNOPSIS =item DESCRIPTION =item STORAGE =item METHODS =item LICENSE =item AUTHORS =item SEE ALSO =back =head2 Math::BigRat - Arbitrary big rational numbers =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item MATH LIBRARY =back =item METHODS =over 4 =item new() =item numerator() =item denominator() =item parts() =item numify() =item as_int()/as_number() =item as_float() =item as_hex() =item as_bin() =item as_oct() =item from_hex()/from_bin()/from_oct() =item length() =item digit() =item bnorm() =item bfac() =item bround()/round()/bfround() =item bmod() =item bneg() =item is_one() =item is_zero() =item is_pos()/is_positive() =item is_neg()/is_negative() =item is_int() =item is_odd() =item is_even() =item bceil() =item bfloor() =item bsqrt() =item broot() =item badd()/bmul()/bsub()/bdiv()/bdec()/binc() =item copy() =item bstr()/bsstr() =item bacmp()/bcmp() =item blsft()/brsft() =item bpow() =item bexp() =item bnok() =item config() =item objectify() =back =item BUGS inf handling (partial), NaN handling (partial), rounding (not implemented except for bceil/bfloor), $x ** $y where $y is not an integer, bmod(), blog(), bmodinv() and bmodpow() (partial) =item LICENSE =item SEE ALSO =item AUTHORS =back =head2 Math::Complex - complex numbers and associated mathematical functions =over 4 =item SYNOPSIS =item DESCRIPTION =item OPERATIONS =item CREATION =item DISPLAYING =over 4 =item CHANGED IN PERL 5.6 =back =item USAGE =item CONSTANTS =over 4 =item PI =item Inf =back =item ERRORS DUE TO DIVISION BY ZERO OR LOGARITHM OF ZERO =item ERRORS DUE TO INDIGESTIBLE ARGUMENTS =item BUGS =item SEE ALSO =item AUTHORS =item LICENSE =back =head2 Math::Trig - trigonometric functions =over 4 =item SYNOPSIS =item DESCRIPTION =item TRIGONOMETRIC FUNCTIONS B<tan> =over 4 =item ERRORS DUE TO DIVISION BY ZERO =item SIMPLE (REAL) ARGUMENTS, COMPLEX RESULTS =back =item PLANE ANGLE CONVERSIONS deg2rad, grad2rad, rad2deg, grad2deg, deg2grad, rad2grad, rad2rad, deg2deg, grad2grad =item RADIAL COORDINATE CONVERSIONS =over 4 =item COORDINATE SYSTEMS =item 3-D ANGLE CONVERSIONS cartesian_to_cylindrical, cartesian_to_spherical, cylindrical_to_cartesian, cylindrical_to_spherical, spherical_to_cartesian, spherical_to_cylindrical =back =item GREAT CIRCLE DISTANCES AND DIRECTIONS =over 4 =item great_circle_distance =item great_circle_direction =item great_circle_bearing =item great_circle_destination =item great_circle_midpoint =item great_circle_waypoint =back =item EXAMPLES =over 4 =item CAVEAT FOR GREAT CIRCLE FORMULAS =item Real-valued asin and acos asin_real, acos_real =back =item BUGS =item AUTHORS =item LICENSE =back =head2 Memoize - Make functions faster by trading space for time =over 4 =item SYNOPSIS =item DESCRIPTION =item DETAILS =item OPTIONS =over 4 =item INSTALL =item NORMALIZER =item C<SCALAR_CACHE>, C<LIST_CACHE> C<MEMORY>, C<HASH>, C<TIE>, C<FAULT>, C<MERGE> =back =item OTHER FACILITIES =over 4 =item C<unmemoize> =item C<flush_cache> =back =item CAVEATS =item PERSISTENT CACHE SUPPORT =item EXPIRATION SUPPORT =item BUGS =item MAILING LIST =item AUTHOR =item COPYRIGHT AND LICENSE =item THANK YOU =back =head2 Memoize::AnyDBM_File - glue to provide EXISTS for AnyDBM_File for Storable use =over 4 =item DESCRIPTION =back =head2 Memoize::Expire - Plug-in module for automatic expiration of memoized values =over 4 =item SYNOPSIS =item DESCRIPTION =item INTERFACE TIEHASH, EXISTS, STORE =item ALTERNATIVES =item CAVEATS =item AUTHOR =item SEE ALSO =back =head2 Memoize::ExpireFile - test for Memoize expiration semantics =over 4 =item DESCRIPTION =back =head2 Memoize::ExpireTest - test for Memoize expiration semantics =over 4 =item DESCRIPTION =back =head2 Memoize::NDBM_File - glue to provide EXISTS for NDBM_File for Storable use =over 4 =item DESCRIPTION =back =head2 Memoize::SDBM_File - glue to provide EXISTS for SDBM_File for Storable use =over 4 =item DESCRIPTION =back =head2 Memoize::Storable - store Memoized data in Storable database =over 4 =item DESCRIPTION =back =head2 Module::Build - Build and install Perl modules =over 4 =item SYNOPSIS =item DESCRIPTION =item GUIDE TO DOCUMENTATION General Usage (L<Module::Build>), Authoring Reference (L<Module::Build::Authoring>), API Reference (L<Module::Build::API>), Cookbook (L<Module::Build::Cookbook>) =item ACTIONS build, clean, code, config_data, diff, dist, distcheck, distclean, distdir, distinstall, distmeta, distsign, disttest, docs, fakeinstall, help, html, install, installdeps, manifest, manifest_skip, manpages, pardist, ppd, ppmdist, prereq_data, prereq_report, pure_install, realclean, retest, skipcheck, test, testall, testcover, testdb, testpod, testpodcoverage, versioninstall =item OPTIONS =over 4 =item Command Line Options quiet, verbose, cpan_client, use_rcfile, allow_mb_mismatch, debug =item Default Options File (F<.modulebuildrc>) =item Environment variables MODULEBUILDRC, PERL_MB_OPT =back =item INSTALL PATHS lib, arch, script, bin, bindoc, libdoc, binhtml, libhtml, installdirs, install_path, install_base, destdir, prefix =item MOTIVATIONS +, + =item TO DO =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 Module::Build::API - API Reference for Module Authors =over 4 =item DESCRIPTION =over 4 =item CONSTRUCTORS current(), new(), add_to_cleanup, auto_configure_requires, auto_features, autosplit, build_class, build_requires, create_packlist, c_source, conflicts, create_license, create_makefile_pl, create_readme, dist_abstract, dist_author, dist_name, dist_suffix, dist_version, dist_version_from, dynamic_config, extra_compiler_flags, extra_linker_flags, get_options, type, store, default, include_dirs, install_path, installdirs, license, apache, apache_1_1, artistic, artistic_2, bsd, gpl, lgpl, mit, mozilla, open_source, perl, restrictive, unrestricted, meta_add, meta_merge, module_name, needs_compiler, PL_files, pm_files, pod_files, recommends, recursive_test_files, release_status, requires, script_files, share_dir, sign, test_files, use_tap_harness, tap_harness_args, xs_files, new_from_context(%args), resume(), subclass(), add_property, C<default>, C<check>, property_error =item METHODS add_build_element($type), add_to_cleanup(@files), args(), autosplit_file($from, $to), base_dir(), build_requires(), can_action( $action ), cbuilder(), check_installed_status($module, $version), check_installed_version($module, $version), compare_versions($v1, $op, $v2), config($key), config($key, $value), config() [deprecated], config_data($name), config_data($name => $value), conflicts(), contains_pod($file) [deprecated], copy_if_modified(%parameters), create_build_script(), current_action(), depends_on(@actions), dir_contains($first_dir, $second_dir), dispatch($action, %args), dist_dir(), dist_name(), dist_version(), do_system($cmd, @args), feature($name), feature($name => $value), fix_shebang_line(@files), have_c_compiler(), install_base_relpaths(), install_base_relpaths($type), install_base_relpaths($type => $path), install_destination($type), install_path(), install_path($type), install_path($type => $path), install_types(), invoked_action(), notes(), notes($key), notes($key => $value), orig_dir(), os_type(), is_vmsish(), is_windowsish(), is_unixish(), prefix_relpaths(), prefix_relpaths($installdirs), prefix_relpaths($installdirs, $type), prefix_relpaths($installdirs, $type => $path), get_metadata(), prepare_metadata() [deprecated], prereq_failures(), prereq_data(), prereq_report(), prompt($message, $default), recommends(), requires(), rscan_dir($dir, $pattern), runtime_params(), runtime_params($key), script_files(), up_to_date($source_file, $derived_file), up_to_date(\@source_files, \@derived_files), y_n($message, $default) =item Autogenerated Accessors PL_files(), allow_mb_mismatch(), auto_configure_requires(), autosplit(), base_dir(), bindoc_dirs(), blib(), build_bat(), build_class(), build_elements(), build_requires(), build_script(), bundle_inc(), bundle_inc_preload(), c_source(), config_dir(), configure_requires(), conflicts(), cpan_client(), create_license(), create_makefile_pl(), create_packlist(), create_readme(), debug(), debugger(), destdir(), dynamic_config(), get_options(), html_css(), include_dirs(), install_base(), installdirs(), libdoc_dirs(), license(), magic_number(), mb_version(), meta_add(), meta_merge(), metafile(), metafile2(), module_name(), mymetafile(), mymetafile2(), needs_compiler(), orig_dir(), perl(), pm_files(), pod_files(), pollute(), prefix(), prereq_action_types(), program_name(), quiet(), recommends(), recurse_into(), recursive_test_files(), requires(), scripts(), sign(), tap_harness_args(), test_file_exts(), use_rcfile(), use_tap_harness(), verbose(), xs_files() =back =item MODULE METADATA keywords, resources =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 Module::Build::Authoring - Authoring Module::Build modules =over 4 =item DESCRIPTION =item STRUCTURE =item SUBCLASSING =item PREREQUISITES =over 4 =item Types of prerequisites configure_requires, build_requires, requires, recommends, conflicts =item Format of prerequisites =item XS Extensions =back =item SAVING CONFIGURATION INFORMATION =item STARTING MODULE DEVELOPMENT =item AUTOMATION =item MIGRATION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Base - Default methods for Module::Build =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 Module::Build::Bundling - How to bundle Module::Build with a distribution =over 4 =item SYNOPSIS =item DESCRIPTION =item BUNDLING OTHER CONFIGURATION DEPENDENCIES =over 4 =item WARNING -- How to Manage Dependency Chains =back =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Compat - Compatibility with ExtUtils::MakeMaker =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS create_makefile_pl($style, $build), traditional, small, passthrough (DEPRECATED), run_build_pl(args => \@ARGV), args, script, write_makefile(), makefile =item SCENARIOS =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 Module::Build::ConfigData - Configuration for Module::Build =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS config($name), feature($name), set_config($name, $value), set_feature($name, $value), config_names(), feature_names(), auto_feature_names(), write() =item AUTHOR =back =head2 Module::Build::Cookbook - Examples of Module::Build Usage =over 4 =item DESCRIPTION =item BASIC RECIPES =over 4 =item Installing modules that use Module::Build =item Modifying Config.pm values =item Installing modules using the programmatic interface =item Installing to a temporary directory =item Installing to a non-standard directory =item Installing in the same location as ExtUtils::MakeMaker =item Running a single test file =back =item ADVANCED RECIPES =over 4 =item Making a CPAN.pm-compatible distribution =item Changing the order of the build process =item Adding new file types to the build process =item Adding new elements to the install process =back =item EXAMPLES ON CPAN =over 4 =item SVN-Notify-Mirror 1. Using C<auto_features>, I check to see whether two optional modules are available - SVN::Notify::Config and Net::SSH;, 2. If the S::N::Config module is loaded, I automatically generate test files for it during Build (using the C<PL_files> property), 3. If the C<ssh_feature> is available, I ask if the user wishes to perform the ssh tests (since it requires a little preliminary setup);, 4. Only if the user has C<ssh_feature> and answers yes to the testing, do I generate a test file =item Modifying an action =item Adding an action =item Bundling Module::Build =back =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 Module::Build::ModuleInfo - DEPRECATED =over 4 =item DESCRIPTION =item SEE ALSO =back =head2 Module::Build::Notes - Create persistent distribution configuration modules =over 4 =item DESCRIPTION =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 Module::Build::Notes, NOTES_NAME - Configuration for MODULE_NAME =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS config($name), feature($name), set_config($name, $value), set_feature($name, $value), config_names(), feature_names(), auto_feature_names(), write() =item AUTHOR =back =head2 Module::Build::PPMMaker - Perl Package Manager file creation =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR =item COPYRIGHT =item SEE ALSO =back =head2 Module::Build::Platform::Amiga - Builder class for Amiga platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::Default - Stub class for unknown platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::EBCDIC - Builder class for EBCDIC platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::MPEiX - Builder class for MPEiX platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::MacOS - Builder class for MacOS platforms =over 4 =item DESCRIPTION =over 4 =item Overridden Methods new(), make_executable(), dispatch(), ACTION_realclean() =back =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::RiscOS - Builder class for RiscOS platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::Unix - Builder class for Unix platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::VMS - Builder class for VMS platforms =over 4 =item DESCRIPTION =over 4 =item Overridden Methods _set_defaults =back =back cull_args manpage_separator prefixify _quote_args have_forkpipe _backticks find_command _maybe_command (override) do_system oneliner _infer_xs_spec rscan_dir dist_dir man3page_name expand_test_dir _detildefy find_perl_interpreter localize_file_path localize_dir_path ACTION_clean =over 4 =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::VOS - Builder class for VOS platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::Windows - Builder class for Windows platforms =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::aix - Builder class for AIX platform =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::cygwin - Builder class for Cygwin platform =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::darwin - Builder class for Mac OS X platform =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Platform::os2 - Builder class for OS/2 platform =over 4 =item DESCRIPTION =item AUTHOR =item SEE ALSO =back =head2 Module::Build::Version - DEPRECATED =over 4 =item DESCRIPTION =back =head2 Module::Build::YAML - DEPRECATED =over 4 =item DESCRIPTION =back =head2 Module::CoreList - what modules shipped with versions of perl =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS API C<first_release( MODULE )>, C<first_release_by_date( MODULE )>, C<find_modules( REGEX, [ LIST OF PERLS ] )>, C<find_version( PERL_VERSION )>, C<is_deprecated( MODULE, PERL_VERSION )>, C<removed_from( MODULE )>, C<removed_from_by_date( MODULE )>, C<changes_between( PERL_VERSION, PERL_VERSION )> =item DATA STRUCTURES C<%Module::CoreList::version>, C<%Module::CoreList::released>, C<%Module::CoreList::families>, C<%Module::CoreList::deprecated>, C<%Module::CoreList::upstream>, C<%Module::CoreList::bug_tracker> =item CAVEATS =item HISTORY =item AUTHOR =item LICENSE =item SEE ALSO =back =head2 Module::Load - runtime require of both modules and files =over 4 =item SYNOPSIS =item DESCRIPTION =item Rules =item Caveats =item ACKNOWLEDGEMENTS =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 Module::Load::Conditional - Looking up module information / loading at runtime =over 4 =item SYNOPSIS =item DESCRIPTION =item Methods =over 4 =item $href = check_install( module => NAME [, version => VERSION, verbose => BOOL ] ); module, version, verbose, file, dir, version, uptodate =back =back =over 4 =item $bool = can_load( modules => { NAME => VERSION [,NAME => VERSION] }, [verbose => BOOL, nocache => BOOL] ) modules, verbose, nocache =back =over 4 =item @list = requires( MODULE ); =back =over 4 =item Global Variables =over 4 =item $Module::Load::Conditional::VERBOSE =item $Module::Load::Conditional::FIND_VERSION =item $Module::Load::Conditional::CHECK_INC_HASH =item $Module::Load::Conditional::CACHE =item $Module::Load::Conditional::ERROR =item $Module::Load::Conditional::DEPRECATED =back =item See Also =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 Module::Loaded - mark modules as loaded or unloaded =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS =over 4 =item $bool = mark_as_loaded( PACKAGE ); =back =back =over 4 =item $bool = mark_as_unloaded( PACKAGE ); =back =over 4 =item $loc = is_loaded( PACKAGE ); =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 Module::Metadata - Gather package and POD information from perl module files =over 4 =item SYNOPSIS =item DESCRIPTION =item USAGE =over 4 =item Class methods C<< new_from_file($filename, collect_pod => 1) >>, C<< new_from_handle($handle, $filename, collect_pod => 1) >>, C<< new_from_module($module, collect_pod => 1, inc => \@dirs) >>, C<< find_module_by_name($module, \@dirs) >>, C<< find_module_dir_by_name($module, \@dirs) >>, C<< provides( %options ) >>, version B<(required)>, dir, files, prefix, C<< package_versions_from_directory($dir, \@files?) >>, C<< log_info (internal) >> =item Object methods C<< name() >>, C<< version($package) >>, C<< filename() >>, C<< packages_inside() >>, C<< pod_inside() >>, C<< contains_pod() >>, C<< pod($section) >> =back =item AUTHOR =item COPYRIGHT =back =head2 Module::Pluggable - automatically give your module the ability to have plugins =over 4 =item SYNOPSIS =item EXAMPLE =item DESCRIPTION =item ADVANCED USAGE =item INNER PACKAGES =item OPTIONS =over 4 =item sub_name =item search_path =item search_dirs =item instantiate =item require =item inner =item only =item except =item package =item file_regex =item include_editor_junk =back =item METHODs =over 4 =item search_path =back =item FUTURE PLANS =item AUTHOR =item COPYING =item BUGS =item SEE ALSO =back =head2 Module::Pluggable::Object - automatically give your module the ability to have plugins =over 4 =item SYNOPSIS =item DESCRIPTION =item OPTIONS =item AUTHOR =item COPYING =item BUGS =item SEE ALSO =back =head2 NDBM_File - Tied access to ndbm files =over 4 =item SYNOPSIS =item DESCRIPTION C<O_RDONLY>, C<O_WRONLY>, C<O_RDWR> =item DIAGNOSTICS =over 4 =item C<ndbm store returned -1, errno 22, key "..." at ...> =back =item BUGS AND WARNINGS =back =head2 NEXT - Provide a pseudo-class NEXT (et al) that allows method redispatch =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Enforcing redispatch =item Avoiding repetitions =item Invoking all versions of a method with a single call =item Using C<EVERY> methods =back =item AUTHOR =item BUGS AND IRRITATIONS =item COPYRIGHT =back =head2 Net::Cmd - Network Command class (as used by FTP, SMTP etc) =over 4 =item SYNOPSIS =item DESCRIPTION =item USER METHODS debug ( VALUE ), message (), code (), ok (), status (), datasend ( DATA ), dataend () =item CLASS METHODS debug_print ( DIR, TEXT ), debug_text ( TEXT ), command ( CMD [, ARGS, ... ]), unsupported (), response (), parse_response ( TEXT ), getline (), ungetline ( TEXT ), rawdatasend ( DATA ), read_until_dot (), tied_fh () =item EXPORTS =item AUTHOR =item COPYRIGHT =back =head2 Net::Config - Local configuration data for libnet =over 4 =item SYNOPSYS =item DESCRIPTION =item METHODS requires_firewall HOST =item NetConfig VALUES nntp_hosts, snpp_hosts, pop3_hosts, smtp_hosts, ph_hosts, daytime_hosts, time_hosts, inet_domain, ftp_firewall, ftp_firewall_type, ftp_ext_passive, ftp_int_passive, local_netmask, test_hosts, test_exists =back =head2 Net::Domain - Attempt to evaluate the current host's internet name and domain =over 4 =item SYNOPSIS =item DESCRIPTION hostfqdn (), domainname (), hostname (), hostdomain () =item AUTHOR =item COPYRIGHT =back =head2 Net::FTP - FTP Client class =over 4 =item SYNOPSIS =item DESCRIPTION =item OVERVIEW =item CONSTRUCTOR new ([ HOST ] [, OPTIONS ]) =item METHODS login ([LOGIN [,PASSWORD [, ACCOUNT] ] ]), authorize ( [AUTH [, RESP]]), site (ARGS), ascii, binary, rename ( OLDNAME, NEWNAME ), delete ( FILENAME ), cwd ( [ DIR ] ), cdup (), pwd (), restart ( WHERE ), rmdir ( DIR [, RECURSE ]), mkdir ( DIR [, RECURSE ]), alloc ( SIZE [, RECORD_SIZE] ), ls ( [ DIR ] ), dir ( [ DIR ] ), get ( REMOTE_FILE [, LOCAL_FILE [, WHERE]] ), put ( LOCAL_FILE [, REMOTE_FILE ] ), put_unique ( LOCAL_FILE [, REMOTE_FILE ] ), append ( LOCAL_FILE [, REMOTE_FILE ] ), unique_name (), mdtm ( FILE ), size ( FILE ), supported ( CMD ), hash ( [FILEHANDLE_GLOB_REF],[ BYTES_PER_HASH_MARK] ), feature ( NAME ), nlst ( [ DIR ] ), list ( [ DIR ] ), retr ( FILE ), stor ( FILE ), stou ( FILE ), appe ( FILE ), port ( [ PORT ] ), pasv (), pasv_xfer ( SRC_FILE, DEST_SERVER [, DEST_FILE ] ), pasv_xfer_unique ( SRC_FILE, DEST_SERVER [, DEST_FILE ] ), pasv_wait ( NON_PASV_SERVER ), abort (), quit () =over 4 =item Methods for the adventurous quot (CMD [,ARGS]) =back =item THE dataconn CLASS read ( BUFFER, SIZE [, TIMEOUT ] ), write ( BUFFER, SIZE [, TIMEOUT ] ), bytes_read (), abort (), close () =item UNIMPLEMENTED B<SMNT>, B<HELP>, B<MODE>, B<SYST>, B<STAT>, B<STRU>, B<REIN> =item REPORTING BUGS =item AUTHOR =item SEE ALSO =item USE EXAMPLES http://www.csh.rit.edu/~adam/Progs/ =item CREDITS =item COPYRIGHT =back =head2 Net::NNTP - NNTP Client class =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( [ HOST ] [, OPTIONS ]) =item METHODS article ( [ MSGID|MSGNUM ], [FH] ), body ( [ MSGID|MSGNUM ], [FH] ), head ( [ MSGID|MSGNUM ], [FH] ), articlefh ( [ MSGID|MSGNUM ] ), bodyfh ( [ MSGID|MSGNUM ] ), headfh ( [ MSGID|MSGNUM ] ), nntpstat ( [ MSGID|MSGNUM ] ), group ( [ GROUP ] ), ihave ( MSGID [, MESSAGE ]), last (), date (), postok (), authinfo ( USER, PASS ), list (), newgroups ( SINCE [, DISTRIBUTIONS ]), newnews ( SINCE [, GROUPS [, DISTRIBUTIONS ]]), next (), post ( [ MESSAGE ] ), postfh (), slave (), quit () =over 4 =item Extension methods newsgroups ( [ PATTERN ] ), distributions (), subscriptions (), overview_fmt (), active_times (), active ( [ PATTERN ] ), xgtitle ( PATTERN ), xhdr ( HEADER, MESSAGE-SPEC ), xover ( MESSAGE-SPEC ), xpath ( MESSAGE-ID ), xpat ( HEADER, PATTERN, MESSAGE-SPEC), xrover, listgroup ( [ GROUP ] ), reader =back =item UNSUPPORTED =item DEFINITIONS MESSAGE-SPEC, PATTERN, Examples, C<[^]-]>, C<*bdc>, C<[0-9a-zA-Z]>, C<a??d> =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 Net::Netrc - OO interface to users netrc file =over 4 =item SYNOPSIS =item DESCRIPTION =item THE .netrc FILE machine name, default, login name, password string, account string, macdef name =item CONSTRUCTOR lookup ( MACHINE [, LOGIN ]) =item METHODS login (), password (), account (), lpa () =item AUTHOR =item SEE ALSO =item COPYRIGHT =back =head2 Net::POP3 - Post Office Protocol 3 Client class (RFC1939) =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR new ( [ HOST ] [, OPTIONS ] 0 =item METHODS auth ( USERNAME, PASSWORD ), user ( USER ), pass ( PASS ), login ( [ USER [, PASS ]] ), apop ( [ USER [, PASS ]] ), banner (), capa (), capabilities (), top ( MSGNUM [, NUMLINES ] ), list ( [ MSGNUM ] ), get ( MSGNUM [, FH ] ), getfh ( MSGNUM ), last (), popstat (), ping ( USER ), uidl ( [ MSGNUM ] ), delete ( MSGNUM ), reset (), quit () =item NOTES =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 Net::Ping - check a remote host for reachability =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Functions Net::Ping->new([$proto [, $def_timeout [, $bytes [, $device [, $tos ]]]]]);, $p->ping($host [, $timeout]);, $p->source_verify( { 0 | 1 } );, $p->service_check( { 0 | 1 } );, $p->tcp_service_check( { 0 | 1 } );, $p->hires( { 0 | 1 } );, $p->bind($local_addr);, $p->open($host);, $p->ack( [ $host ] );, $p->nack( $failed_ack_host );, $p->close();, $p->port_number([$port_number]), pingecho($host [, $timeout]); =back =item NOTES =item INSTALL =item BUGS =item AUTHORS =item COPYRIGHT =back =head2 Net::SMTP - Simple Mail Transfer Protocol Client =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLES =item CONSTRUCTOR new ( [ HOST ] [, OPTIONS ] ) =item METHODS banner (), domain (), hello ( DOMAIN ), host (), etrn ( DOMAIN ), starttls ( SSLARGS ), auth ( USERNAME, PASSWORD ), mail ( ADDRESS [, OPTIONS] ), send ( ADDRESS ), send_or_mail ( ADDRESS ), send_and_mail ( ADDRESS ), reset (), recipient ( ADDRESS [, ADDRESS, [...]] [, OPTIONS ] ), to ( ADDRESS [, ADDRESS [...]] ), cc ( ADDRESS [, ADDRESS [...]] ), bcc ( ADDRESS [, ADDRESS [...]] ), data ( [ DATA ] ), expand ( ADDRESS ), verify ( ADDRESS ), help ( [ $subject ] ), quit () =item ADDRESSES =item SEE ALSO =item AUTHOR =item COPYRIGHT =back =head2 Net::Time - time and daytime network client interface =over 4 =item SYNOPSIS =item DESCRIPTION inet_time ( [HOST [, PROTOCOL [, TIMEOUT]]]), inet_daytime ( [HOST [, PROTOCOL [, TIMEOUT]]]) =item AUTHOR =item COPYRIGHT =back =head2 Net::hostent - by-name interface to Perl's built-in gethost*() functions =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLES =item NOTE =item AUTHOR =back =head2 Net::libnetFAQ, libnetFAQ - libnet Frequently Asked Questions =over 4 =item DESCRIPTION =over 4 =item Where to get this document =item How to contribute to this document =back =item Author and Copyright Information =over 4 =item Disclaimer =back =item Obtaining and installing libnet =over 4 =item What is libnet ? =item Which version of perl do I need ? =item What other modules do I need ? =item What machines support libnet ? =item Where can I get the latest libnet release =back =item Using Net::FTP =over 4 =item How do I download files from an FTP server ? =item How do I transfer files in binary mode ? =item How can I get the size of a file on a remote FTP server ? =item How can I get the modification time of a file on a remote FTP server ? =item How can I change the permissions of a file on a remote server ? =item Can I do a reget operation like the ftp command ? =item How do I get a directory listing from an FTP server ? =item Changing directory to "" does not fail ? =item I am behind a SOCKS firewall, but the Firewall option does not work ? =item I am behind an FTP proxy firewall, but cannot access machines outside ? =item My ftp proxy firewall does not listen on port 21 =item Is it possible to change the file permissions of a file on an FTP server ? =item I have seen scripts call a method message, but cannot find it documented ? =item Why does Net::FTP not implement mput and mget methods =back =item Using Net::SMTP =over 4 =item Why can't the part of an Email address after the @ be used as the hostname ? =item Why does Net::SMTP not do DNS MX lookups ? =item The verify method always returns true ? =back =item Debugging scripts =over 4 =item How can I debug my scripts that use Net::* modules ? =back =item AUTHOR AND COPYRIGHT =back =head2 Net::netent - by-name interface to Perl's built-in getnet*() functions =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLES =item NOTE =item AUTHOR =back =head2 Net::protoent - by-name interface to Perl's built-in getproto*() functions =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTE =item AUTHOR =back =head2 Net::servent - by-name interface to Perl's built-in getserv*() functions =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLES =item NOTE =item AUTHOR =back =head2 O - Generic interface to Perl Compiler backends =over 4 =item SYNOPSIS =item DESCRIPTION =item CONVENTIONS =item IMPLEMENTATION =item BUGS =item AUTHOR =back =head2 ODBM_File - Tied access to odbm files =over 4 =item SYNOPSIS =item DESCRIPTION C<O_RDONLY>, C<O_WRONLY>, C<O_RDWR> =item DIAGNOSTICS =over 4 =item C<odbm store returned -1, errno 22, key "..." at ...> =back =item BUGS AND WARNINGS =back =head2 Object::Accessor - interface to create per object accessors =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item $object = Object::Accessor->new( [ARGS] ); =back =back =over 4 =item $bool = $object->mk_accessors( @ACCESSORS | \%ACCESSOR_MAP ); =back =over 4 =item @list = $self->ls_accessors; =back =over 4 =item $ref = $self->ls_allow(KEY) =back =over 4 =item $bool = $self->mk_aliases( alias => method, [alias2 => method2, ...] ); =back =over 4 =item $clone = $self->mk_clone; =back =over 4 =item $bool = $self->mk_flush; =back =over 4 =item $bool = $self->mk_verify; =back =over 4 =item $bool = $self->register_callback( sub { ... } ); =back =over 4 =item $bool = $self->can( METHOD_NAME ) =back =over 4 =item $val = $self->___get( METHOD_NAME ); =back =over 4 =item $bool = $self->___set( METHOD_NAME => VALUE ); =back =over 4 =item $bool = $self->___alias( ALIAS => METHOD ); =back =over 4 =item LVALUE ACCESSORS =over 4 =item CAVEATS Allow handlers, Callbacks =back =back =over 4 =item GLOBAL VARIABLES =over 4 =item $Object::Accessor::FATAL =item $Object::Accessor::DEBUG =back =item TODO =over 4 =item Create read-only accessors =back =item CAVEATS =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 Opcode - Disable named opcodes when compiling perl code =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTE =item WARNING =item Operator Names and Operator Lists an operator name (opname), an operator tag name (optag), a negated opname or optag, an operator set (opset) =item Opcode Functions opcodes, opset (OP, ...), opset_to_ops (OPSET), opset_to_hex (OPSET), full_opset, empty_opset, invert_opset (OPSET), verify_opset (OPSET, ...), define_optag (OPTAG, OPSET), opmask_add (OPSET), opmask, opdesc (OP, ...), opdump (PAT) =item Manipulating Opsets =item TO DO (maybe) =back =over 4 =item Predefined Opcode Tags :base_core, :base_mem, :base_loop, :base_io, :base_orig, :base_math, :base_thread, :default, :filesys_read, :sys_db, :browse, :filesys_open, :filesys_write, :subprocess, :ownprocess, :others, :load, :still_to_be_decided, :dangerous =item SEE ALSO =item AUTHORS =back =head2 POSIX - Perl interface to IEEE Std 1003.1 =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEATS =item FUNCTIONS _exit, abort, abs, access, acos, alarm, asctime, asin, assert, atan, atan2, atexit, atof, atoi, atol, bsearch, calloc, ceil, chdir, chmod, chown, clearerr, clock, close, closedir, cos, cosh, creat, ctermid, ctime, cuserid, difftime, div, dup, dup2, errno, execl, execle, execlp, execv, execve, execvp, exit, exp, fabs, fclose, fcntl, fdopen, feof, ferror, fflush, fgetc, fgetpos, fgets, fileno, floor, fmod, fopen, fork, fpathconf, fprintf, fputc, fputs, fread, free, freopen, frexp, fscanf, fseek, fsetpos, fstat, fsync, ftell, fwrite, getc, getchar, getcwd, getegid, getenv, geteuid, getgid, getgrgid, getgrnam, getgroups, getlogin, getpgrp, getpid, getppid, getpwnam, getpwuid, gets, getuid, gmtime, isalnum, isalpha, isatty, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, kill, labs, lchown, ldexp, ldiv, link, localeconv, localtime, log, log10, longjmp, lseek, malloc, mblen, mbstowcs, mbtowc, memchr, memcmp, memcpy, memmove, memset, mkdir, mkfifo, mktime, modf, nice, offsetof, open, opendir, pathconf, pause, perror, pipe, pow, printf, putc, putchar, puts, qsort, raise, rand, read, readdir, realloc, remove, rename, rewind, rewinddir, rmdir, scanf, setgid, setjmp, setlocale, setpgid, setsid, setuid, sigaction, siglongjmp, sigpending, sigprocmask, sigsetjmp, sigsuspend, sin, sinh, sleep, sprintf, sqrt, srand, sscanf, stat, strcat, strchr, strcmp, strcoll, strcpy, strcspn, strerror, strftime, strlen, strncat, strncmp, strncpy, strpbrk, strrchr, strspn, strstr, strtod, strtok, strtol, strtoul, strxfrm, sysconf, system, tan, tanh, tcdrain, tcflow, tcflush, tcgetpgrp, tcsendbreak, tcsetpgrp, time, times, tmpfile, tmpnam, tolower, toupper, ttyname, tzname, tzset, umask, uname, ungetc, unlink, utime, vfprintf, vprintf, vsprintf, wait, waitpid, wcstombs, wctomb, write =item CLASSES =over 4 =item POSIX::SigAction new, handler, mask, flags, safe =item POSIX::SigRt %SIGRT, SIGRTMIN, SIGRTMAX =item POSIX::SigSet new, addset, delset, emptyset, fillset, ismember =item POSIX::Termios new, getattr, getcc, getcflag, getiflag, getispeed, getlflag, getoflag, getospeed, setattr, setcc, setcflag, setiflag, setispeed, setlflag, setoflag, setospeed, Baud rate values, Terminal interface values, c_cc field values, c_cflag field values, c_iflag field values, c_lflag field values, c_oflag field values =back =item PATHNAME CONSTANTS Constants =item POSIX CONSTANTS Constants =item SYSTEM CONFIGURATION Constants =item ERRNO Constants =item FCNTL Constants =item FLOAT Constants =item LIMITS Constants =item LOCALE Constants =item MATH Constants =item SIGNAL Constants =item STAT Constants, Macros =item STDLIB Constants =item STDIO Constants =item TIME Constants =item UNISTD Constants =item WAIT Constants, WNOHANG, WUNTRACED, Macros, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WIFSTOPPED, WSTOPSIG =back =head2 Package::Constants - List all constants declared in a package =over 4 =item SYNOPSIS =item DESCRIPTION =item CLASS METHODS =over 4 =item @const = Package::Constants->list( PACKAGE_NAME ); =back =back =over 4 =item GLOBAL VARIABLES =over 4 =item $Package::Constants::DEBUG =back =back =over 4 =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 Params::Check - A generic input parsing/checking mechanism. =over 4 =item SYNOPSIS =item DESCRIPTION =item Template default, required, strict_type, defined, no_override, store, allow =item Functions =over 4 =item check( \%tmpl, \%args, [$verbose] ); Template, Arguments, Verbose =back =back =over 4 =item allow( $test_me, \@criteria ); string, regexp, subroutine, array ref =back =over 4 =item last_error() =back =over 4 =item Global Variables =over 4 =item $Params::Check::VERBOSE =item $Params::Check::STRICT_TYPE =item $Params::Check::ALLOW_UNKNOWN =item $Params::Check::STRIP_LEADING_DASHES =item $Params::Check::NO_DUPLICATES =item $Params::Check::PRESERVE_CASE =item $Params::Check::ONLY_ALLOW_DEFINED =item $Params::Check::SANITY_CHECK_TEMPLATE =item $Params::Check::WARNINGS_FATAL =item $Params::Check::CALLER_DEPTH =back =item Acknowledgements =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 Parse::CPAN::Meta - Parse META.yml and META.json CPAN metadata files =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item load_file =item load_yaml_string =item load_json_string =item yaml_backend =item json_backend =back =item FUNCTIONS =over 4 =item Load =item LoadFile =back =item ENVIRONMENT =over 4 =item PERL_JSON_BACKEND =item PERL_YAML_BACKEND =back =item SUPPORT =item AUTHOR =item COPYRIGHT =back =head2 Perl::OSType - Map Perl operating system names to generic types =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item USAGE =over 4 =item os_type() =item is_os_type() =back =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 PerlIO - On demand loader for PerlIO layers and root of PerlIO::* name space =over 4 =item SYNOPSIS =item DESCRIPTION :unix, :stdio, :perlio, :crlf, :utf8, :bytes, :raw, :pop, :win32 =over 4 =item Custom Layers :encoding, :mmap, :via =item Alternatives to raw =item Defaults and how to override them =item Querying the layers of filehandles =back =item AUTHOR =item SEE ALSO =back =head2 PerlIO::encoding - encoding layer =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =back =head2 PerlIO::mmap - Memory mapped IO =over 4 =item SYNOPSIS =item DESCRIPTION =item IMPLEMENTATION NOTE =back =head2 PerlIO::scalar - in-memory IO, scalar IO =over 4 =item SYNOPSIS =item DESCRIPTION =item IMPLEMENTATION NOTE =back =head2 PerlIO::via - Helper class for PerlIO layers implemented in perl =over 4 =item SYNOPSIS =item DESCRIPTION =item EXPECTED METHODS $class->PUSHED([$mode,[$fh]]), $obj->POPPED([$fh]), $obj->UTF8($belowFlag,[$fh]), $obj->OPEN($path,$mode,[$fh]), $obj->BINMODE([$fh]), $obj->FDOPEN($fd,[$fh]), $obj->SYSOPEN($path,$imode,$perm,[$fh]), $obj->FILENO($fh), $obj->READ($buffer,$len,$fh), $obj->WRITE($buffer,$fh), $obj->FILL($fh), $obj->CLOSE($fh), $obj->SEEK($posn,$whence,$fh), $obj->TELL($fh), $obj->UNREAD($buffer,$fh), $obj->FLUSH($fh), $obj->SETLINEBUF($fh), $obj->CLEARERR($fh), $obj->ERROR($fh), $obj->EOF($fh) =item EXAMPLES =over 4 =item Example - a Hexadecimal Handle =back =back =head2 PerlIO::via::QuotedPrint - PerlIO layer for quoted-printable strings =over 4 =item SYNOPSIS =item DESCRIPTION =item REQUIRED MODULES =item SEE ALSO =item ACKNOWLEDGEMENTS =item COPYRIGHT =back =head2 Pod::Checker, podchecker() - check pod documents for syntax errors =over 4 =item SYNOPSIS =item OPTIONS/ARGUMENTS =over 4 =item podchecker() B<-warnings> =E<gt> I<val> =back =item DESCRIPTION =item DIAGNOSTICS =over 4 =item Errors empty =headn, =over on line I<N> without closing =back, =item without previous =over, =back without previous =over, No argument for =begin, =end without =begin, Nested =begin's, =for without formatter specification, Apparent command =foo not preceded by blank line, unresolved internal link I<NAME>, Unknown command "I<CMD>", Unknown interior-sequence "I<SEQ>", nested commands I<CMD>E<lt>...I<CMD>E<lt>...E<gt>...E<gt>, garbled entity I<STRING>, Entity number out of range, malformed link LE<lt>E<gt>, nonempty ZE<lt>E<gt>, empty XE<lt>E<gt>, Spurious text after =pod / =cut, Spurious =cut command, Spurious =pod command, Spurious character(s) after =back =item Warnings multiple occurrence of link target I<name>, line containing nothing but whitespace in paragraph, file does not start with =head, previous =item has no contents, preceding non-item paragraph(s), =item type mismatch (I<one> vs. I<two>), I<N> unescaped C<E<lt>E<gt>> in paragraph, Unknown entity, No items in =over, No argument for =item, empty section in previous paragraph, Verbatim paragraph in NAME section, =headI<n> without preceding higher level =item Hyperlinks ignoring leading/trailing whitespace in link, (section) in '$page' deprecated, alternative text/node '%s' contains non-escaped | or / =back =item RETURN VALUE =item EXAMPLES =item INTERFACE =back C<Pod::Checker-E<gt>new( %options )> C<$checker-E<gt>poderror( @args )>, C<$checker-E<gt>poderror( {%opts}, @args )> C<$checker-E<gt>num_errors()> C<$checker-E<gt>num_warnings()> C<$checker-E<gt>name()> C<$checker-E<gt>node()> C<$checker-E<gt>idx()> C<$checker-E<gt>hyperlink()> =over 4 =item AUTHOR =back =head2 Pod::Escapes -- for resolving Pod EE<lt>...E<gt> sequences =over 4 =item SYNOPSIS =item DESCRIPTION =item GOODIES e2char($e_content), e2charnum($e_content), $Name2character{I<name>}, $Name2character_number{I<name>}, $Latin1Code_to_fallback{I<integer>}, $Latin1Char_to_fallback{I<character>}, $Code2USASCII{I<integer>} =item CAVEATS =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Find - find POD documents in directory trees =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item C<pod_find( { %opts } , @directories )> C<-verbose =E<gt> 1>, C<-perl =E<gt> 1>, C<-script =E<gt> 1>, C<-inc =E<gt> 1> =back =over 4 =item C<simplify_name( $str )> =back =over 4 =item C<pod_where( { %opts }, $pod )> C<-inc =E<gt> 1>, C<-dirs =E<gt> [ $dir1, $dir2, ... ]>, C<-verbose =E<gt> 1> =back =over 4 =item C<contains_pod( $file , $verbose )> =back =over 4 =item AUTHOR =item SEE ALSO =back =head2 Pod::Html - module to convert pod files to HTML =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS =over 4 =item pod2html backlink, cachedir, css, flush, header, help, htmldir, htmlroot, index, infile, outfile, poderrors, podpath, podroot, quiet, recurse, title, verbose =item htmlify =item anchorify =back =item ENVIRONMENT =item AUTHOR =item SEE ALSO =item COPYRIGHT =back =head2 Pod::InputObjects - objects representing POD input paragraphs, commands, etc. =over 4 =item SYNOPSIS =item REQUIRES =item EXPORTS =item DESCRIPTION package B<Pod::InputSource>, package B<Pod::Paragraph>, package B<Pod::InteriorSequence>, package B<Pod::ParseTree> =back =over 4 =item B<Pod::InputSource> =back =over 4 =item B<new()> =back =over 4 =item B<name()> =back =over 4 =item B<handle()> =back =over 4 =item B<was_cutting()> =back =over 4 =item B<Pod::Paragraph> =back =over 4 =item Pod::Paragraph-E<gt>B<new()> =back =over 4 =item $pod_para-E<gt>B<cmd_name()> =back =over 4 =item $pod_para-E<gt>B<text()> =back =over 4 =item $pod_para-E<gt>B<raw_text()> =back =over 4 =item $pod_para-E<gt>B<cmd_prefix()> =back =over 4 =item $pod_para-E<gt>B<cmd_separator()> =back =over 4 =item $pod_para-E<gt>B<parse_tree()> =back =over 4 =item $pod_para-E<gt>B<file_line()> =back =over 4 =item B<Pod::InteriorSequence> =back =over 4 =item Pod::InteriorSequence-E<gt>B<new()> =back =over 4 =item $pod_seq-E<gt>B<cmd_name()> =back =over 4 =item $pod_seq-E<gt>B<prepend()> =back =over 4 =item $pod_seq-E<gt>B<append()> =back =over 4 =item $pod_seq-E<gt>B<nested()> =back =over 4 =item $pod_seq-E<gt>B<raw_text()> =back =over 4 =item $pod_seq-E<gt>B<left_delimiter()> =back =over 4 =item $pod_seq-E<gt>B<right_delimiter()> =back =over 4 =item $pod_seq-E<gt>B<parse_tree()> =back =over 4 =item $pod_seq-E<gt>B<file_line()> =back =over 4 =item Pod::InteriorSequence::B<DESTROY()> =back =over 4 =item B<Pod::ParseTree> =back =over 4 =item Pod::ParseTree-E<gt>B<new()> =back =over 4 =item $ptree-E<gt>B<top()> =back =over 4 =item $ptree-E<gt>B<children()> =back =over 4 =item $ptree-E<gt>B<prepend()> =back =over 4 =item $ptree-E<gt>B<append()> =back =over 4 =item $ptree-E<gt>B<raw_text()> =back =over 4 =item Pod::ParseTree::B<DESTROY()> =back =over 4 =item SEE ALSO =item AUTHOR =back =head2 Pod::LaTeX - Convert Pod data to formatted Latex =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item OBJECT METHODS C<initialize> =back =over 4 =item Data Accessors B<AddPreamble> =back B<AddPostamble> B<Head1Level> B<Label> B<LevelNoNum> B<MakeIndex> B<ReplaceNAMEwithSection> B<StartWithNewPage> B<TableOfContents> B<UniqueLabels> B<UserPreamble> B<UserPostamble> B<Lists> =over 4 =item Subclassed methods =back B<begin_pod> B<end_pod> B<command> B<verbatim> B<textblock> B<interior_sequence> =over 4 =item List Methods B<begin_list> =back B<end_list> B<add_item> =over 4 =item Methods for headings B<head> =back =over 4 =item Internal methods B<_output> =back B<_replace_special_chars> B<_replace_special_chars_late> B<_create_label> B<_create_index> B<_clean_latex_commands> B<_split_delimited> =over 4 =item NOTES =item SEE ALSO =item AUTHORS =item COPYRIGHT =item REVISION =back =head2 Pod::Man - Convert POD data to formatted *roff input =over 4 =item SYNOPSIS =item DESCRIPTION center, date, fixed, fixedbold, fixeditalic, fixedbolditalic, name, quotes, release, section, stderr, utf8 =item DIAGNOSTICS roff font should be 1 or 2 chars, not "%s", Invalid quote specification "%s" =item BUGS =item CAVEATS =item AUTHOR =item COPYRIGHT AND LICENSE =item SEE ALSO =back =head2 Pod::ParseLink - Parse an LE<lt>E<gt> formatting code in POD text =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 Pod::ParseUtils - helpers for POD parsing and conversion =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item Pod::List Pod::List-E<gt>new() =back $list-E<gt>file() $list-E<gt>start() $list-E<gt>indent() $list-E<gt>type() $list-E<gt>rx() $list-E<gt>item() $list-E<gt>parent() $list-E<gt>tag() =over 4 =item Pod::Hyperlink Pod::Hyperlink-E<gt>new() =back $link-E<gt>parse($string) $link-E<gt>markup($string) $link-E<gt>text() $link-E<gt>warning() $link-E<gt>file(), $link-E<gt>line() $link-E<gt>page() $link-E<gt>node() $link-E<gt>alttext() $link-E<gt>type() $link-E<gt>link() =over 4 =item Pod::Cache Pod::Cache-E<gt>new() =back $cache-E<gt>item() $cache-E<gt>find_page($name) =over 4 =item Pod::Cache::Item Pod::Cache::Item-E<gt>new() =back $cacheitem-E<gt>page() $cacheitem-E<gt>description() $cacheitem-E<gt>path() $cacheitem-E<gt>file() $cacheitem-E<gt>nodes() $cacheitem-E<gt>find_node($name) $cacheitem-E<gt>idx() =over 4 =item AUTHOR =item SEE ALSO =back =head2 Pod::Parser - base class for creating POD filters and translators =over 4 =item SYNOPSIS =item REQUIRES =item EXPORTS =item DESCRIPTION =item QUICK OVERVIEW =item PARSING OPTIONS B<-want_nonPODs> (default: unset), B<-process_cut_cmd> (default: unset), B<-warnings> (default: unset) =back =over 4 =item RECOMMENDED SUBROUTINE/METHOD OVERRIDES =back =over 4 =item B<command()> C<$cmd>, C<$text>, C<$line_num>, C<$pod_para> =back =over 4 =item B<verbatim()> C<$text>, C<$line_num>, C<$pod_para> =back =over 4 =item B<textblock()> C<$text>, C<$line_num>, C<$pod_para> =back =over 4 =item B<interior_sequence()> =back =over 4 =item OPTIONAL SUBROUTINE/METHOD OVERRIDES =back =over 4 =item B<new()> =back =over 4 =item B<initialize()> =back =over 4 =item B<begin_pod()> =back =over 4 =item B<begin_input()> =back =over 4 =item B<end_input()> =back =over 4 =item B<end_pod()> =back =over 4 =item B<preprocess_line()> =back =over 4 =item B<preprocess_paragraph()> =back =over 4 =item METHODS FOR PARSING AND PROCESSING =back =over 4 =item B<parse_text()> B<-expand_seq> =E<gt> I<code-ref>|I<method-name>, B<-expand_text> =E<gt> I<code-ref>|I<method-name>, B<-expand_ptree> =E<gt> I<code-ref>|I<method-name> =back =over 4 =item B<interpolate()> =back =over 4 =item B<parse_paragraph()> =back =over 4 =item B<parse_from_filehandle()> =back =over 4 =item B<parse_from_file()> =back =over 4 =item ACCESSOR METHODS =back =over 4 =item B<errorsub()> =back =over 4 =item B<cutting()> =back =over 4 =item B<parseopts()> =back =over 4 =item B<output_file()> =back =over 4 =item B<output_handle()> =back =over 4 =item B<input_file()> =back =over 4 =item B<input_handle()> =back =over 4 =item B<input_streams()> =back =over 4 =item B<top_stream()> =back =over 4 =item PRIVATE METHODS AND DATA =back =over 4 =item B<_push_input_stream()> =back =over 4 =item B<_pop_input_stream()> =back =over 4 =item TREE-BASED PARSING =item CAVEATS =item SEE ALSO =item AUTHOR =item LICENSE =back =head2 Pod::Perldoc - Look up Perl documentation in Pod format. =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::BaseTo - Base for Pod::Perldoc formatters =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::GetOptsOO - Customized option parser for Pod::Perldoc =over 4 =item SYNOPSIS =item DESCRIPTION Call Pod::Perldoc::GetOptsOO::getopts($object, \@ARGV, $truth), Given -n, if there's a opt_n_with, it'll call $object->opt_n_with( ARGUMENT ) (e.g., "-n foo" => $object->opt_n_with('foo'). Ditto "-nfoo"), Otherwise (given -n) if there's an opt_n, we'll call it $object->opt_n($truth) (Truth defaults to 1), Otherwise we try calling $object->handle_unknown_option('n') (and we increment the error count by the return value of it), If there's no handle_unknown_option, then we just warn, and then increment the error counter =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToANSI - render Pod with ANSI color escapes =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEAT =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToChecker - let Perldoc check Pod for errors =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToMan - let Perldoc render Pod as man pages =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEAT =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToNroff - let Perldoc convert Pod to nroff =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEAT =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToPod - let Perldoc render Pod as ... Pod! =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToRtf - let Perldoc render Pod as RTF =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToTerm - render Pod with terminal escapes =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEAT =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToText - let Perldoc render Pod as plaintext =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEAT =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::Perldoc::ToTk - let Perldoc use Tk::Pod to render Pod =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item AUTHOR =back =head2 Pod::Perldoc::ToXml - let Perldoc render Pod as XML =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item COPYRIGHT AND DISCLAIMERS =item AUTHOR =back =head2 Pod::PlainText - Convert POD data to formatted ASCII text =over 4 =item SYNOPSIS =item DESCRIPTION alt, indent, loose, sentence, width =item DIAGNOSTICS Bizarre space in item, Can't open %s for reading: %s, Unknown escape: %s, Unknown sequence: %s, Unmatched =back =item RESTRICTIONS =item NOTES =item SEE ALSO =item AUTHOR =back =head2 Pod::Select, podselect() - extract selected sections of POD from input =over 4 =item SYNOPSIS =item REQUIRES =item EXPORTS =item DESCRIPTION =item SECTION SPECIFICATIONS =item RANGE SPECIFICATIONS =back =over 4 =item OBJECT METHODS =back =over 4 =item B<curr_headings()> =back =over 4 =item B<select()> =back =over 4 =item B<add_selection()> =back =over 4 =item B<clear_selections()> =back =over 4 =item B<match_section()> =back =over 4 =item B<is_selected()> =back =over 4 =item EXPORTED FUNCTIONS =back =over 4 =item B<podselect()> B<-output>, B<-sections>, B<-ranges> =back =over 4 =item PRIVATE METHODS AND DATA =back =over 4 =item B<_compile_section_spec()> =back =over 4 =item $self->{_SECTION_HEADINGS} =back =over 4 =item $self->{_SELECTED_SECTIONS} =back =over 4 =item SEE ALSO =item AUTHOR =back =head2 Pod::Simple - framework for parsing Pod =over 4 =item SYNOPSIS =item DESCRIPTION =item MAIN METHODS C<< $parser = I<SomeClass>->new(); >>, C<< $parser->output_fh( *OUT ); >>, C<< $parser->output_string( \$somestring ); >>, C<< $parser->parse_file( I<$some_filename> ); >>, C<< $parser->parse_file( *INPUT_FH ); >>, C<< $parser->parse_string_document( I<$all_content> ); >>, C<< $parser->parse_lines( I<...@lines...>, undef ); >>, C<< $parser->content_seen >>, C<< I<SomeClass>->filter( I<$filename> ); >>, C<< I<SomeClass>->filter( I<*INPUT_FH> ); >>, C<< I<SomeClass>->filter( I<\$document_content> ); >> =item SECONDARY METHODS C<< $parser->no_whining( I<SOMEVALUE> ) >>, C<< $parser->no_errata_section( I<SOMEVALUE> ) >>, C<< $parser->complain_stderr( I<SOMEVALUE> ) >>, C<< $parser->source_filename >>, C<< $parser->doc_has_started >>, C<< $parser->source_dead >>, C<< $parser->strip_verbatim_indent( I<SOMEVALUE> ) >> =item TERTIARY METHODS C<< $parser->abandon_output_fh() >>X<abandon_output_fh>, C<< $parser->abandon_output_string() >>X<abandon_output_string>, C<< $parser->accept_code( @codes ) >>X<accept_code>, C<< $parser->accept_codes( @codes ) >>X<accept_codes>, C<< $parser->accept_directive_as_data( @directives ) >>X<accept_directive_as_data>, C<< $parser->accept_directive_as_processed( @directives ) >>X<accept_directive_as_processed>, C<< $parser->accept_directive_as_verbatim( @directives ) >>X<accept_directive_as_verbatim>, C<< $parser->accept_target( @targets ) >>X<accept_target>, C<< $parser->accept_target_as_text( @targets ) >>X<accept_target_as_text>, C<< $parser->accept_targets( @targets ) >>X<accept_targets>, C<< $parser->accept_targets_as_text( @targets ) >>X<accept_targets_as_text>, C<< $parser->any_errata_seen() >>X<any_errata_seen>, C<< $parser->parse_from_file( $source, $to ) >>X<parse_from_file>, C<< $parser->scream( @error_messages ) >>X<scream>, C<< $parser->unaccept_code( @codes ) >>X<unaccept_code>, C<< $parser->unaccept_codes( @codes ) >>X<unaccept_codes>, C<< $parser->unaccept_directive( @directives ) >>X<unaccept_directive>, C<< $parser->unaccept_directives( @directives ) >>X<unaccept_directives>, C<< $parser->unaccept_target( @targets ) >>X<unaccept_target>, C<< $parser->unaccept_targets( @targets ) >>X<unaccept_targets>, C<< $parser->version_report() >>X<version_report>, C<< $parser->whine( @error_messages ) >>X<whine> =item CAVEATS =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org>, Gabor Szabo C<szabgab@gmail.com>, Shawn H Corey C<SHCOREY at cpan.org> =back =head2 Pod::Simple::Checker -- check the Pod syntax of a document =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::Debug -- put Pod::Simple into trace/debug mode =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEATS =item GUTS =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::DumpAsText -- dump Pod-parsing events as text =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::DumpAsXML -- turn Pod into XML =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::HTML - convert Pod to HTML =over 4 =item SYNOPSIS =item DESCRIPTION =item CALLING FROM THE COMMAND LINE =item CALLING FROM PERL =over 4 =item Minimal code =item More detailed example =back =item METHODS =over 4 =item html_css =item html_javascript =item title_prefix =item title_postfix =item html_header_before_title =item html_h_level =item index =item html_header_after_title =item html_footer =back =item SUBCLASSING =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item ACKNOWLEDGEMENTS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::HTMLBatch - convert several Pod files to several HTML files =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item FROM THE COMMAND LINE =back =item MAIN METHODS $batchconv = Pod::Simple::HTMLBatch->new;, $batchconv->batch_convert( I<indirs>, I<outdir> );, $batchconv->batch_convert( undef , ...);, $batchconv->batch_convert( q{@INC}, ...);, $batchconv->batch_convert( \@dirs , ...);, $batchconv->batch_convert( "somedir" , ...);, $batchconv->batch_convert( 'somedir:someother:also' , ...);, $batchconv->batch_convert( ... , undef );, $batchconv->batch_convert( ... , 'somedir' ); =over 4 =item ACCESSOR METHODS $batchconv->verbose( I<nonnegative_integer> );, $batchconv->index( I<true-or-false> );, $batchconv->contents_file( I<filename> );, $batchconv->contents_page_start( I<HTML_string> );, $batchconv->contents_page_end( I<HTML_string> );, $batchconv->add_css( $url );, $batchconv->add_javascript( $url );, $batchconv->css_flurry( I<true-or-false> );, $batchconv->javascript_flurry( I<true-or-false> );, $batchconv->no_contents_links( I<true-or-false> );, $batchconv->html_render_class( I<classname> );, $batchconv->search_class( I<classname> ); =back =item NOTES ON CUSTOMIZATION =item ASK ME! =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::LinkSection -- represent "section" attributes of L codes =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::Methody -- turn Pod::Simple events into method calls =over 4 =item SYNOPSIS =item DESCRIPTION =item METHOD CALLING =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::PullParser -- a pull-parser interface to parsing Pod =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS my $token = $parser->get_token, $parser->unget_token( $token ), $parser->unget_token( $token1, $token2, ... ), $parser->set_source( $filename ), $parser->set_source( $filehandle_object ), $parser->set_source( \$document_source ), $parser->set_source( \@document_lines ), $parser->parse_file(...), $parser->parse_string_document(...), $parser->filter(...), $parser->parse_from_file(...), my $title_string = $parser->get_title, my $title_string = $parser->get_short_title, $author_name = $parser->get_author, $description_name = $parser->get_description, $version_block = $parser->get_version =item NOTE =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::PullParserEndToken -- end-tokens from Pod::Simple::PullParser =over 4 =item SYNOPSIS =item DESCRIPTION $token->tagname, $token->tagname(I<somestring>), $token->tag(...), $token->is_tag(I<somestring>) or $token->is_tagname(I<somestring>) =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::PullParserStartToken -- start-tokens from Pod::Simple::PullParser =over 4 =item SYNOPSIS =item DESCRIPTION $token->tagname, $token->tagname(I<somestring>), $token->tag(...), $token->is_tag(I<somestring>) or $token->is_tagname(I<somestring>), $token->attr(I<attrname>), $token->attr(I<attrname>, I<newvalue>), $token->attr_hash =item SEE ALSO =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::PullParserTextToken -- text-tokens from Pod::Simple::PullParser =over 4 =item SYNOPSIS =item DESCRIPTION $token->text, $token->text(I<somestring>), $token->text_r() =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::PullParserToken -- tokens from Pod::Simple::PullParser =over 4 =item SYNOPSIS =item DESCRIPTION $token->type, $token->is_start, $token->is_text, $token->is_end, $token->dump =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::RTF -- format Pod as RTF =over 4 =item SYNOPSIS =item DESCRIPTION =item FORMAT CONTROL ATTRIBUTES $parser->head1_halfpoint_size( I<halfpoint_integer> );, $parser->head2_halfpoint_size( I<halfpoint_integer> );, $parser->head3_halfpoint_size( I<halfpoint_integer> );, $parser->head4_halfpoint_size( I<halfpoint_integer> );, $parser->codeblock_halfpoint_size( I<halfpoint_integer> );, $parser->header_halfpoint_size( I<halfpoint_integer> );, $parser->normal_halfpoint_size( I<halfpoint_integer> );, $parser->no_proofing_exemptions( I<true_or_false> );, $parser->doc_lang( I<microsoft_decimal_language_code> ) =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::Search - find POD documents in directory trees =over 4 =item SYNOPSIS =item DESCRIPTION =item CONSTRUCTOR =item ACCESSORS $search->inc( I<true-or-false> );, $search->verbose( I<nonnegative-number> );, $search->limit_glob( I<some-glob-string> );, $search->callback( I<\&some_routine> );, $search->laborious( I<true-or-false> );, $search->shadows( I<true-or-false> );, $search->limit_re( I<some-regxp> );, $search->dir_prefix( I<some-string-value> );, $search->progress( I<some-progress-object> );, $name2path = $self->name2path;, $path2name = $self->path2name; =item MAIN SEARCH METHODS =over 4 =item C<< $search->survey( @directories ) >> C<name2path>, C<path2name> =item C<< $search->simplify_name( $str ) >> =item C<< $search->find( $pod ) >> =item C<< $search->find( $pod, @search_dirs ) >> =item C<< $self->contains_pod( $file ) >> =back =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::SimpleTree -- parse Pod into a simple parse tree =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =item Tree Contents =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::Subclassing -- write a formatter as a Pod::Simple subclass =over 4 =item SYNOPSIS =item DESCRIPTION =item Events C<< $parser->_handle_element_start( I<element_name>, I<attr_hashref> ) >>, C<< $parser->_handle_element_end( I<element_name> ) >>, C<< $parser->_handle_text( I<text_string> ) >>, events with an element_name of Document, events with an element_name of Para, events with an element_name of B, C, F, or I, events with an element_name of S, events with an element_name of X, events with an element_name of L, events with an element_name of E or Z, events with an element_name of Verbatim, events with an element_name of head1 .. head4, events with an element_name of over-bullet, events with an element_name of over-number, events with an element_name of over-text, events with an element_name of over-block, events with an element_name of over-empty, events with an element_name of item-bullet, events with an element_name of item-number, events with an element_name of item-text, events with an element_name of for, events with an element_name of Data =item More Pod::Simple Methods C<< $parser->accept_targets( I<SOMEVALUE> ) >>, C<< $parser->accept_targets_as_text( I<SOMEVALUE> ) >>, C<< $parser->accept_codes( I<Codename>, I<Codename>... ) >>, C<< $parser->accept_directive_as_data( I<directive_name> ) >>, C<< $parser->accept_directive_as_verbatim( I<directive_name> ) >>, C<< $parser->accept_directive_as_processed( I<directive_name> ) >>, C<< $parser->nbsp_for_S( I<BOOLEAN> ); >>, C<< $parser->version_report() >>, C<< $parser->pod_para_count() >>, C<< $parser->line_count() >>, C<< $parser->nix_X_codes( I<SOMEVALUE> ) >>, C<< $parser->merge_text( I<SOMEVALUE> ) >>, C<< $parser->code_handler( I<CODE_REF> ) >>, C<< $parser->cut_handler( I<CODE_REF> ) >>, C<< $parser->pod_handler( I<CODE_REF> ) >>, C<< $parser->whiteline_handler( I<CODE_REF> ) >>, C<< $parser->whine( I<linenumber>, I<complaint string> ) >>, C<< $parser->scream( I<linenumber>, I<complaint string> ) >>, C<< $parser->source_dead(1) >>, C<< $parser->hide_line_numbers( I<SOMEVALUE> ) >>, C<< $parser->no_whining( I<SOMEVALUE> ) >>, C<< $parser->no_errata_section( I<SOMEVALUE> ) >>, C<< $parser->complain_stderr( I<SOMEVALUE> ) >>, C<< $parser->bare_output( I<SOMEVALUE> ) >>, C<< $parser->preserve_whitespace( I<SOMEVALUE> ) >>, C<< $parser->parse_empty_lists( I<SOMEVALUE> ) >> =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::Text -- format Pod as plaintext =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::TextContent -- get the text content of Pod =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::XHTML -- format Pod as validating XHTML =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Minimal code =back =back =over 4 =item METHODS =over 4 =item perldoc_url_prefix =item perldoc_url_postfix =item man_url_prefix =item man_url_postfix =item title_prefix, title_postfix =item html_css =item html_javascript =item html_doctype =item html_charset =item html_header_tags =item html_h_level =item default_title =item force_title =item html_header, html_footer =item index =item anchor_items =item backlink =back =back =over 4 =item SUBCLASSING =back =over 4 =item handle_text =item accept_targets_as_html =back =over 4 =item resolve_pod_page_link =back =over 4 =item resolve_man_page_link =back =over 4 =item idify =back =over 4 =item batch_mode_page_object_init =back =over 4 =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item ACKNOWLEDGEMENTS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Simple::XMLOutStream -- turn Pod into XML =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =item ABOUT EXTENDING POD =item ASK ME! =item SEE ALSO =item SUPPORT =item COPYRIGHT AND DISCLAIMERS =item AUTHOR Allison Randal C<allison@perl.org>, Hans Dieter Pearcey C<hdp@cpan.org>, David E. Wheeler C<dwheeler@cpan.org> =back =head2 Pod::Text - Convert POD data to formatted ASCII text =over 4 =item SYNOPSIS =item DESCRIPTION alt, code, indent, loose, margin, quotes, sentence, stderr, utf8, width =item DIAGNOSTICS Bizarre space in item, Item called without tag, Can't open %s for reading: %s, Invalid quote specification "%s" =item BUGS =item CAVEATS =item NOTES =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 Pod::Text::Color - Convert POD data to formatted color ASCII text =over 4 =item SYNOPSIS =item DESCRIPTION =item BUGS =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 Pod::Text::Overstrike, =for stopwords overstrike =over 4 =item SYNOPSIS =item DESCRIPTION =item BUGS =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 Pod::Text::Termcap - Convert POD data to ASCII text with format escapes =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTES =item SEE ALSO =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 Pod::Usage, pod2usage() - print a usage message from embedded pod documentation =over 4 =item SYNOPSIS =item ARGUMENTS C<-message>, C<-msg>, C<-exitval>, C<-verbose>, C<-sections>, C<-output>, C<-input>, C<-pathlist>, C<-noperldoc> =over 4 =item Pass-through options =back =item DESCRIPTION =item EXAMPLES =over 4 =item Recommended Use =back =item CAVEATS =item AUTHOR =item ACKNOWLEDGMENTS =item SEE ALSO =back =head2 SDBM_File - Tied access to sdbm files =over 4 =item SYNOPSIS =item DESCRIPTION C<O_RDONLY>, C<O_WRONLY>, C<O_RDWR> =item DIAGNOSTICS =over 4 =item C<sdbm store returned -1, errno 22, key "..." at ...> =back =item BUGS AND WARNINGS =back =head2 Safe - Compile and execute code in restricted compartments =over 4 =item SYNOPSIS =item DESCRIPTION a new namespace, an operator mask =item WARNING =item METHODS =over 4 =item permit (OP, ...) =item permit_only (OP, ...) =item deny (OP, ...) =item deny_only (OP, ...) =item trap (OP, ...) =item untrap (OP, ...) =item share (NAME, ...) =item share_from (PACKAGE, ARRAYREF) =item varglob (VARNAME) =item reval (STRING, STRICT) =item rdo (FILENAME) =item root (NAMESPACE) =item mask (MASK) =item wrap_code_ref (CODEREF) =item wrap_code_refs_within (...) =back =item RISKS Memory, CPU, Snooping, Signals, State Changes =item AUTHOR =back =head2 Scalar::Util - A selection of general-utility scalar subroutines =over 4 =item SYNOPSIS =item DESCRIPTION blessed EXPR, dualvar NUM, STRING, isvstring EXPR, isweak EXPR, looks_like_number EXPR, openhandle FH, refaddr EXPR, reftype EXPR, set_prototype CODEREF, PROTOTYPE, tainted EXPR, weaken REF =item DIAGNOSTICS Weak references are not implemented in the version of perl, Vstrings are not implemented in the version of perl, C<NAME> is only available with the XS version of Scalar::Util =item KNOWN BUGS =item SEE ALSO =item COPYRIGHT =back =head2 Search::Dict - look - search for key in dictionary file =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 SelectSaver - save and restore selected file handle =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 SelfLoader - load functions only on demand =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item The __DATA__ token =item SelfLoader autoloading =item Autoloading and package lexicals =item SelfLoader and AutoLoader =item __DATA__, __END__, and the FOOBAR::DATA filehandle. =item Classes and inherited methods. =back =item Multiple packages and fully qualified subroutine names =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 Socket, C<Socket> - networking constants and support functions =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item CONSTANTS =back =over 4 =item PF_INET, PF_INET6, PF_UNIX, ... =item AF_INET, AF_INET6, AF_UNIX, ... =item SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, ... =item SOL_SOCKET =item SO_ACCEPTCONN, SO_BROADCAST, SO_ERROR, ... =item IP_OPTIONS, IP_TOS, IP_TTL, ... =item MSG_BCAST, MSG_OOB, MSG_TRUNC, ... =item SHUT_RD, SHUT_RDWR, SHUT_WR =item INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE =item IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, ... =item TCP_CORK, TCP_KEEPALIVE, TCP_NODELAY, ... =item IN6ADDR_ANY, IN6ADDR_LOOPBACK =item IPV6_ADD_MEMBERSHIP, IPV6_MTU, IPV6_V6ONLY, ... =back =over 4 =item STRUCTURE MANIPULATORS =back =over 4 =item $family = sockaddr_family $sockaddr =item $sockaddr = pack_sockaddr_in $port, $ip_address =item ($port, $ip_address) = unpack_sockaddr_in $sockaddr =item $sockaddr = sockaddr_in $port, $ip_address =item ($port, $ip_address) = sockaddr_in $sockaddr =item $sockaddr = pack_sockaddr_in6 $port, $ip6_address, [$scope_id, [$flowinfo]] =item ($port, $ip6_address, $scope_id, $flowinfo) = unpack_sockaddr_in6 $sockaddr =item $sockaddr = sockaddr_in6 $port, $ip6_address, [$scope_id, [$flowinfo]] =item ($port, $ip6_address, $scope_id, $flowinfo) = sockaddr_in6 $sockaddr =item $sockaddr = pack_sockaddr_un $path =item ($path) = unpack_sockaddr_un $sockaddr =item $sockaddr = sockaddr_un $path =item ($path) = sockaddr_un $sockaddr =item $ipv6_mreq = pack_ipv6_mreq $ip6_address, $ifindex =item ($ip6_address, $ifindex) = unpack_ipv6_mreq $ipv6_mreq =back =over 4 =item FUNCTIONS =back =over 4 =item $ip_address = inet_aton $string =item $string = inet_ntoa $ip_address =item $address = inet_pton $family, $string =item $string = inet_ntop $family, $address =item ($err, @result) = getaddrinfo $host, $service, [$hints] flags => INT, family => INT, socktype => INT, protocol => INT, family => INT, socktype => INT, protocol => INT, addr => STRING, canonname => STRING, AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST =item ($err, $hostname, $servicename) = getnameinfo $sockaddr, [$flags, [$xflags]] NI_NUMERICHOST, NI_NUMERICSERV, NI_NAMEREQD, NI_DGRAM, NIx_NOHOST, NIx_NOSERV =back =over 4 =item getaddrinfo() / getnameinfo() ERROR CONSTANTS EAI_AGAIN, EAI_BADFLAGS, EAI_FAMILY, EAI_NODATA, EAI_NONAME, EAI_SERVICE =back =over 4 =item EXAMPLES =over 4 =item Lookup for connect() =item Making a human-readable string out of an address =item Resolving hostnames into IP addresses =item Accessing socket options =back =back =over 4 =item AUTHOR =back =head2 Storable - persistence for Perl data structures =over 4 =item SYNOPSIS =item DESCRIPTION =item MEMORY STORE =item ADVISORY LOCKING =item SPEED =item CANONICAL REPRESENTATION =item CODE REFERENCES =item FORWARD COMPATIBILITY utf8 data, restricted hashes, files from future versions of Storable =item ERROR REPORTING =item WIZARDS ONLY =over 4 =item Hooks C<STORABLE_freeze> I<obj>, I<cloning>, C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, .., C<STORABLE_attach> I<class>, I<cloning>, I<serialized> =item Predicates C<Storable::last_op_in_netorder>, C<Storable::is_storing>, C<Storable::is_retrieving> =item Recursion =item Deep Cloning =back =item Storable magic $info = Storable::file_magic( $filename ), C<version>, C<version_nv>, C<major>, C<minor>, C<hdrsize>, C<netorder>, C<byteorder>, C<intsize>, C<longsize>, C<ptrsize>, C<nvsize>, C<file>, $info = Storable::read_magic( $buffer ), $info = Storable::read_magic( $buffer, $must_be_file ) =item EXAMPLES =item WARNING =item BUGS =over 4 =item 64 bit data in perl 5.6.0 and 5.6.1 =back =item CREDITS =item AUTHOR =item SEE ALSO =back =head2 Symbol - manipulate Perl symbols and their names =over 4 =item SYNOPSIS =item DESCRIPTION =item BUGS =back =head2 Sys::Hostname - Try every conceivable way to get hostname =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR =back =head2 Sys::Syslog - Perl interface to the UNIX syslog(3) calls =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item EXPORTS =item FUNCTIONS B<openlog($ident, $logopt, $facility)>, B<syslog($priority, $message)>, B<syslog($priority, $format, @args)>, B<Note>, B<setlogmask($mask_priority)>, B<setlogsock()>, B<Note>, B<closelog()> =item THE RULES OF SYS::SYSLOG =item EXAMPLES =item CONSTANTS =over 4 =item Facilities =item Levels =back =item DIAGNOSTICS C<Invalid argument passed to setlogsock>, C<eventlog passed to setlogsock, but no Win32 API available>, C<no connection to syslog available>, C<stream passed to setlogsock, but %s is not writable>, C<stream passed to setlogsock, but could not find any device>, C<tcp passed to setlogsock, but tcp service unavailable>, C<syslog: expecting argument %s>, C<syslog: invalid level/facility: %s>, C<syslog: too many levels given: %s>, C<syslog: too many facilities given: %s>, C<syslog: level must be given>, C<udp passed to setlogsock, but udp service unavailable>, C<unix passed to setlogsock, but path not available> =item HISTORY =item SEE ALSO =over 4 =item Manual Pages =item RFCs =item Articles =item Event Log =back =item AUTHORS & ACKNOWLEDGEMENTS =item BUGS =item SUPPORT AnnoCPAN: Annotated CPAN documentation, CPAN Ratings, RT: CPAN's request tracker, Search CPAN, Kobes' CPAN Search, Perl Documentation =item COPYRIGHT =item LICENSE =back =head2 TAP::Base - Base class that provides common functionality to L<TAP::Parser> and L<TAP::Harness> =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =head2 TAP::Formatter::Base - Base class for harness output delegates =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =back =over 4 =item METHODS =over 4 =item Class Methods C<verbosity>, C<verbose>, C<timer>, C<failures>, C<comments>, C<quiet>, C<really_quiet>, C<silent>, C<errors>, C<directives>, C<stdout>, C<color>, C<jobs>, C<show_count> =back =back =head2 TAP::Formatter::Color - Run Perl test scripts with color =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =item METHODS =over 4 =item Class Methods =back =back =head2 TAP::Formatter::Console - Harness output delegate for default console output =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =over 4 =item C<< open_test >> =back =back =head2 TAP::Formatter::Console::ParallelSession - Harness output delegate for parallel console output =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =back =over 4 =item METHODS =over 4 =item Class Methods =back =back =head2 TAP::Formatter::Console::Session - Harness output delegate for default console output =over 4 =item VERSION =back =over 4 =item DESCRIPTION =back =over 4 =item C<< clear_for_close >> =item C<< close_test >> =item C<< header >> =item C<< result >> =back =head2 TAP::Formatter::File - Harness output delegate for file output =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =over 4 =item C<< open_test >> =back =back =head2 TAP::Formatter::File::Session - Harness output delegate for file output =over 4 =item VERSION =back =over 4 =item DESCRIPTION =back =over 4 =item METHODS =over 4 =item result =back =back =over 4 =item close_test =back =head2 TAP::Formatter::Session - Abstract base class for harness output delegate =over 4 =item VERSION =back =over 4 =item METHODS =over 4 =item Class Methods C<formatter>, C<parser>, C<name>, C<show_count> =back =back =head2 TAP::Harness - Run test scripts with statistics =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item SYNOPSIS =back =over 4 =item METHODS =over 4 =item Class Methods C<verbosity>, C<timer>, C<failures>, C<comments>, C<show_count>, C<normalize>, C<lib>, C<switches>, C<test_args>, C<color>, C<exec>, C<merge>, C<sources>, C<aggregator_class>, C<version>, C<formatter_class>, C<multiplexer_class>, C<parser_class>, C<scheduler_class>, C<formatter>, C<errors>, C<directives>, C<ignore_exit>, C<jobs>, C<rules>, C<stdout>, C<trap> =back =back =over 4 =item Instance Methods =back the source name of a test to run, a reference to a [ source name, display name ] array =over 4 =item CONFIGURING =over 4 =item Plugins =item C<Module::Build> =item C<ExtUtils::MakeMaker> =item C<prove> =back =item WRITING PLUGINS Customize how TAP gets into the parser, Customize how TAP results are output from the parser =item SUBCLASSING =over 4 =item Methods L</new>, L</runtests>, L</summary> =back =back =over 4 =item REPLACING =item SEE ALSO =back =head2 TAP::Object - Base class that provides common functionality to all C<TAP::*> modules =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Instance Methods =back =head2 TAP::Parser - Parse L<TAP|Test::Harness::TAP> output =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods C<source>, C<tap>, C<exec>, C<sources>, C<callback>, C<switches>, C<test_args>, C<spool>, C<merge>, C<grammar_class>, C<result_factory_class>, C<iterator_factory_class> =back =back =over 4 =item Instance Methods =back =over 4 =item INDIVIDUAL RESULTS =over 4 =item Result types Version, Plan, Pragma, Test, Comment, Bailout, Unknown =item Common type methods =item C<plan> methods =item C<pragma> methods =item C<bailout> methods =item C<unknown> methods =item C<test> methods =back =item TOTAL RESULTS =over 4 =item Individual Results =back =back =over 4 =item Pragmas =back =over 4 =item Summary Results =back =over 4 =item C<ignore_exit> =back Misplaced plan, No plan, More than one plan, Test numbers out of sequence =over 4 =item CALLBACKS C<test>, C<version>, C<plan>, C<comment>, C<bailout>, C<yaml>, C<unknown>, C<ELSE>, C<ALL>, C<EOF> =item TAP GRAMMAR =item BACKWARDS COMPATIBILITY =over 4 =item Differences TODO plans, 'Missing' tests =back =item SUBCLASSING =over 4 =item Parser Components option 1, option 2 =back =item ACKNOWLEDGMENTS Michael Schwern, Andy Lester, chromatic, GEOFFR, Shlomi Fish, Torsten Schoenfeld, Jerry Gay, Aristotle, Adam Kennedy, Yves Orton, Adrian Howard, Sean & Lil, Andreas J. Koenig, Florian Ragwitz, Corion, Mark Stosberg, Matt Kraai, David Wheeler, Alex Vandiver, Cosimo Streppone, Ville Skyttä =item AUTHORS =item BUGS =item COPYRIGHT & LICENSE =back =head2 TAP::Parser::Aggregator - Aggregate TAP::Parser results =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Instance Methods =back =over 4 =item Summary methods failed, parse_errors, passed, planned, skipped, todo, todo_passed, wait, exit =back Failed tests, Parse errors, Bad exit or wait status =over 4 =item See Also =back =head2 TAP::Parser::Grammar - A grammar for the Test Anything Protocol. =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Instance Methods =back =over 4 =item TAP GRAMMAR =item SUBCLASSING =item SEE ALSO =back =head2 TAP::Parser::Iterator - Base class for TAP source iterators =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =item Instance Methods =back =back =over 4 =item SUBCLASSING =over 4 =item Example =back =item SEE ALSO =back =head2 TAP::Parser::Iterator::Array - Iterator for array-based TAP sources =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =item Instance Methods =back =back =over 4 =item ATTRIBUTION =item SEE ALSO =back =head2 TAP::Parser::Iterator::Process - Iterator for process-based TAP sources =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =item Instance Methods =back =back =over 4 =item ATTRIBUTION =item SEE ALSO =back =head2 TAP::Parser::Iterator::Stream - Iterator for filehandle-based TAP sources =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Instance Methods =back =over 4 =item ATTRIBUTION =item SEE ALSO =back =head2 TAP::Parser::IteratorFactory - Figures out which SourceHandler objects to use for a given Source =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Instance Methods =back =over 4 =item SUBCLASSING =over 4 =item Example =back =item AUTHORS =item ATTRIBUTION =item SEE ALSO =back =head2 TAP::Parser::Multiplexer - Multiplex multiple TAP::Parsers =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Instance Methods =back =over 4 =item See Also =back =head2 TAP::Parser::Result - Base class for TAP::Parser output objects =over 4 =item VERSION =back =over 4 =item SYNOPSIS =over 4 =item DESCRIPTION =item METHODS =back =back =over 4 =item Boolean methods C<is_plan>, C<is_pragma>, C<is_test>, C<is_comment>, C<is_bailout>, C<is_version>, C<is_unknown>, C<is_yaml> =back =over 4 =item SUBCLASSING =over 4 =item Example =back =item SEE ALSO =back =head2 TAP::Parser::Result::Bailout - Bailout result token. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item OVERRIDDEN METHODS C<as_string> =back =over 4 =item Instance Methods =back =head2 TAP::Parser::Result::Comment - Comment result token. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item OVERRIDDEN METHODS C<as_string> =back =over 4 =item Instance Methods =back =head2 TAP::Parser::Result::Plan - Plan result token. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item OVERRIDDEN METHODS C<as_string>, C<raw> =back =over 4 =item Instance Methods =back =head2 TAP::Parser::Result::Pragma - TAP pragma token. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item OVERRIDDEN METHODS C<as_string>, C<raw> =back =over 4 =item Instance Methods =back =head2 TAP::Parser::Result::Test - Test result token. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item OVERRIDDEN METHODS =over 4 =item Instance Methods =back =back =head2 TAP::Parser::Result::Unknown - Unknown result token. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item OVERRIDDEN METHODS C<as_string>, C<raw> =back =head2 TAP::Parser::Result::Version - TAP syntax version token. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item OVERRIDDEN METHODS C<as_string>, C<raw> =back =over 4 =item Instance Methods =back =head2 TAP::Parser::Result::YAML - YAML result token. =over 4 =item VERSION =back =over 4 =item DESCRIPTION =item OVERRIDDEN METHODS C<as_string>, C<raw> =back =over 4 =item Instance Methods =back =head2 TAP::Parser::ResultFactory - Factory for creating TAP::Parser output objects =over 4 =item SYNOPSIS =item VERSION =back =over 4 =item DESCRIPTION =item METHODS =item Class Methods =back =over 4 =item SUBCLASSING =over 4 =item Example =back =item SEE ALSO =back =head2 TAP::Parser::Scheduler - Schedule tests during parallel testing =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =head2 TAP::Parser::Scheduler::Job - A single testing job. =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =head2 TAP::Parser::Scheduler::Spinner - A no-op job. =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =head2 TAP::Parser::Source - a TAP source & meta data about it =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item Instance Methods =back =over 4 =item AUTHORS =item SEE ALSO =back =head2 TAP::Parser::SourceHandler - Base class for different TAP source handlers =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item SUBCLASSING =over 4 =item Example =back =item AUTHORS =item SEE ALSO =back =head2 TAP::Parser::SourceHandler::Executable - Stream output from an executable TAP source =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item SUBCLASSING =over 4 =item Example =back =item SEE ALSO =back =head2 TAP::Parser::SourceHandler::File - Stream TAP from a text file. =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item CONFIGURATION =item SUBCLASSING =item SEE ALSO =back =head2 TAP::Parser::SourceHandler::Handle - Stream TAP from an IO::Handle or a GLOB. =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item SUBCLASSING =item SEE ALSO =back =head2 TAP::Parser::SourceHandler::Perl - Stream TAP from a Perl executable =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item SUBCLASSING =over 4 =item Example =back =item SEE ALSO =back =head2 TAP::Parser::SourceHandler::RawTAP - Stream output from raw TAP in a scalar/array ref. =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =back =back =over 4 =item SUBCLASSING =item SEE ALSO =back =head2 TAP::Parser::Utils - Internal TAP::Parser utilities =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item INTERFACE =back =back =head2 TAP::Parser::YAMLish::Reader - Read YAMLish data from iterator =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =item Instance Methods =back =item AUTHOR =item SEE ALSO =item COPYRIGHT =back =head2 TAP::Parser::YAMLish::Writer - Write YAMLish data =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item Class Methods =item Instance Methods a reference to a scalar to append YAML to, the handle of an open file, a reference to an array into which YAML will be pushed, a code reference =back =item AUTHOR =item SEE ALSO =item COPYRIGHT =back =head2 Term::ANSIColor - Color screen output using ANSI escape sequences =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Supported Colors =item Function Interface color(ATTR[, ATTR ...]), colored(STRING, ATTRIBUTES), colored(ATTR-REF, STRING[, STRING...]), uncolor(ESCAPE), colorstrip(STRING[, STRING ...]), colorvalid(ATTR[, ATTR ...]) =item Constant Interface =item The Color Stack =back =item DIAGNOSTICS Bad escape sequence %s, Bareword "%s" not allowed while "strict subs" in use, Invalid attribute name %s, Name "%s" used only once: possible typo, No comma allowed after filehandle, No name for escape sequence %s =item ENVIRONMENT ANSI_COLORS_DISABLED =item RESTRICTIONS =item NOTES =item SEE ALSO =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 Term::Cap - Perl termcap interface =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item METHODS =back =back B<Tgetent>, OSPEED, TERM B<Tpad>, B<$string>, B<$cnt>, B<$FH> B<Tputs>, B<$cap>, B<$cnt>, B<$FH> B<Tgoto>, B<$cap>, B<$col>, B<$row>, B<$FH> B<Trequire> =over 4 =item EXAMPLES =item COPYRIGHT AND LICENSE =item AUTHOR =item SEE ALSO =back =head2 Term::Complete - Perl word completion module =over 4 =item SYNOPSIS =item DESCRIPTION E<lt>tabE<gt>, ^D, ^U, E<lt>delE<gt>, E<lt>bsE<gt> =item DIAGNOSTICS =item BUGS =item AUTHOR =back =head2 Term::ReadLine - Perl interface to various C<readline> packages. If no real package is found, substitutes stubs instead of basic functions. =over 4 =item SYNOPSIS =item DESCRIPTION =item Minimal set of supported functions C<ReadLine>, C<new>, C<readline>, C<addhistory>, C<IN>, C<OUT>, C<MinLine>, C<findConsole>, Attribs, C<Features> =item Additional supported functions C<tkRunning>, C<event_loop>, C<ornaments>, C<newTTY> =item EXPORTS =item ENVIRONMENT =back =head2 Term::UI - Term::ReadLine UI made easy =over 4 =item SYNOPSIS =item DESCRIPTION =item HOW IT WORKS =item METHODS =over 4 =item $reply = $term->get_reply( prompt => 'question?', [choices => \@list, default => $list[0], multi => BOOL, print_me => "extra text to print & record", allow => $ref] ); =back =back =over 4 =item $bool = $term->ask_yn( prompt => "your question", [default => (y|1,n|0), print_me => "extra text to print & record"] ) =back =over 4 =item ($opts, $munged) = $term->parse_options( STRING ); =back =over 4 =item $str = $term->history_as_string =back =over 4 =item GLOBAL VARIABLES =over 4 =item $Term::UI::VERBOSE =item $Term::UI::AUTOREPLY =item $Term::UI::INVALID =item $Term::UI::History::HISTORY_FH =back =item EXAMPLES =over 4 =item Basic get_reply sample =item get_reply with choices =item get_reply with choices and default =item get_reply using print_me & multi =item get_reply & allow =item an elaborate ask_yn sample =back =item See Also =item BUG REPORTS =item AUTHOR =item COPYRIGHT =back =head2 Term::UI::History - history function =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS =over 4 =item history("message string" [,VERBOSE]) =back =back =over 4 =item GLOBAL VARIABLES $HISTORY_FH =item See Also =item AUTHOR =item COPYRIGHT =back =head2 Test - provides a simple framework for writing test scripts =over 4 =item SYNOPSIS =item DESCRIPTION =item QUICK START GUIDE =over 4 =item Functions C<plan(...)>, C<tests =E<gt> I<number>>, C<todo =E<gt> [I<1,5,14>]>, C<onfail =E<gt> sub { ... }>, C<onfail =E<gt> \&some_sub> =back =back B<_to_value> C<ok(...)> C<skip(I<skip_if_true>, I<args...>)> =over 4 =item TEST TYPES NORMAL TESTS, SKIPPED TESTS, TODO TESTS =item ONFAIL =item BUGS and CAVEATS =item ENVIRONMENT =item NOTE =item SEE ALSO =item AUTHOR =back =head2 Test::Builder - Backend for building test libraries =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Construction B<new> =back =back B<create> B<child> B<subtest> B<_plan_handled>, Explicitly setting the number of tests, Setting 'no_plan', Set 'skip_all' B<finalize> B<parent> B<name> B<reset> =over 4 =item Setting up tests B<plan> =back B<expected_tests> B<no_plan> B<_output_plan> B<done_testing> B<has_plan> B<skip_all> B<exported_to> =over 4 =item Running tests B<ok> =back B<is_eq>, B<is_num> B<isnt_eq>, B<isnt_num> B<like>, B<unlike> B<cmp_ok> =over 4 =item Other Testing Methods B<BAIL_OUT> =back B<skip> B<todo_skip> B<skip_rest> =over 4 =item Test building utility methods B<maybe_regex> =back B<_try> B<is_fh> =over 4 =item Test style B<level> =back B<use_numbers> B<no_diag>, B<no_ending>, B<no_header> =over 4 =item Output B<diag> =back B<note> B<explain> B<_print> B<output>, B<failure_output>, B<todo_output> reset_outputs carp, croak =over 4 =item Test Status and Info B<current_test> =back B<is_passing> B<summary> B<details> B<todo> B<find_TODO> B<in_todo> B<todo_start> C<todo_end> B<caller> B<_sanity_check> B<_whoa> B<_my_exit> =over 4 =item EXIT CODES =item THREADS =item MEMORY =item EXAMPLES =item SEE ALSO =item AUTHORS =item COPYRIGHT =back =head2 Test::Builder::Module - Base class for test modules =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Importing =back =back =over 4 =item Builder =back =head2 Test::Builder::Tester - test testsuites that have been built with Test::Builder =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item Functions test_out, test_err =back test_fail test_diag test_test, title (synonym 'name', 'label'), skip_out, skip_err line_num color =over 4 =item BUGS =item AUTHOR =item NOTES =item SEE ALSO =back =head2 Test::Builder::Tester::Color - turn on colour in Test::Builder::Tester =over 4 =item SYNOPSIS =item DESCRIPTION =back =over 4 =item AUTHOR =item BUGS =item SEE ALSO =back =head2 Test::Harness - Run Perl standard test scripts with statistics =over 4 =item VERSION =back =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS =over 4 =item runtests( @test_files ) =back =back =over 4 =item execute_tests( tests => \@test_files, out => \*FH ) =back =over 4 =item EXPORT =item ENVIRONMENT VARIABLES THAT TAP::HARNESS::COMPATIBLE SETS C<HARNESS_ACTIVE>, C<HARNESS_VERSION> =item ENVIRONMENT VARIABLES THAT AFFECT TEST::HARNESS C<HARNESS_TIMER>, C<HARNESS_VERBOSE>, C<HARNESS_OPTIONS>, C<< j<n> >>, C<< c >>, C<HARNESS_SUBCLASS> =item Taint Mode =item SEE ALSO =item BUGS =item AUTHORS =item LICENCE AND COPYRIGHT =back =head2 Test::More - yet another framework for writing test scripts =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item I love it when a plan comes together =back =back B<done_testing> =over 4 =item Test names =item I'm ok, you're not ok. B<ok> =back B<is>, B<isnt> B<like> B<unlike> B<cmp_ok> B<can_ok> B<isa_ok> B<new_ok> B<subtest> B<pass>, B<fail> =over 4 =item Module tests B<use_ok> =back B<require_ok> =over 4 =item Complex data structures B<is_deeply> =back =over 4 =item Diagnostics B<diag>, B<note> =back B<explain> =over 4 =item Conditional tests B<SKIP: BLOCK> =back B<TODO: BLOCK>, B<todo_skip> When do I use SKIP vs. TODO? =over 4 =item Test control B<BAIL_OUT> =back =over 4 =item Discouraged comparison functions B<eq_array> =back B<eq_hash> B<eq_set> =over 4 =item Extending and Embedding Test::More B<builder> =back =over 4 =item EXIT CODES =item CAVEATS and NOTES Backwards compatibility, utf8 / "Wide character in print", Overloaded objects, Threads =item HISTORY =item SEE ALSO =item AUTHORS =item BUGS =item SOURCE =item COPYRIGHT =back =head2 Test::Simple - Basic utilities for writing tests. =over 4 =item SYNOPSIS =item DESCRIPTION B<ok> =back =over 4 =item EXAMPLE =item CAVEATS =item NOTES =item HISTORY =item SEE ALSO L<Test::More> =item AUTHORS =item COPYRIGHT =back =head2 Test::Tutorial - A tutorial about writing really basic tests =over 4 =item DESCRIPTION =over 4 =item Nuts and bolts of testing. =item Where to start? =item Names =item Test the manual =item Sometimes the tests are wrong =item Testing lots of values =item Informative names =item Skipping tests =item Todo tests =item Testing with taint mode. =back =item FOOTNOTES =item AUTHORS =item COPYRIGHT =back =head2 Text::Abbrev - abbrev - create an abbreviation table from a list =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLE =back =head2 Text::Balanced - Extract delimited text sequences from strings. =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item General behaviour in list contexts [0], [1], [2] =item General behaviour in scalar and void contexts =item A note about prefixes =item C<extract_delimited> =item C<extract_bracketed> =item C<extract_variable> [0], [1], [2] =item C<extract_tagged> C<reject =E<gt> $listref>, C<ignore =E<gt> $listref>, C<fail =E<gt> $str>, [0], [1], [2], [3], [4], [5] =item C<gen_extract_tagged> =item C<extract_quotelike> [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10] =item C<extract_quotelike> and "here documents" [0], [1], [2], [3], [4], [5], [6], [7..10] =item C<extract_codeblock> =item C<extract_multiple> =item C<gen_delimited_pat> =item C<delimited_pat> =back =item DIAGNOSTICS C<Did not find a suitable bracket: "%s">, C<Did not find prefix: /%s/>, C<Did not find opening bracket after prefix: "%s">, C<No quotelike operator found after prefix: "%s">, C<Unmatched closing bracket: "%c">, C<Unmatched opening bracket(s): "%s">, C<Unmatched embedded quote (%s)>, C<Did not find closing delimiter to match '%s'>, C<Mismatched closing bracket: expected "%c" but found "%s">, C<No block delimiter found after quotelike "%s">, C<Did not find leading dereferencer>, C<Bad identifier after dereferencer>, C<Did not find expected opening bracket at %s>, C<Improperly nested codeblock at %s>, C<Missing second block for quotelike "%s">, C<No match found for opening bracket>, C<Did not find opening tag: /%s/>, C<Unable to construct closing tag to match: /%s/>, C<Found invalid nested tag: %s>, C<Found unbalanced nested tag: %s>, C<Did not find closing tag> =item AUTHOR =item BUGS AND IRRITATIONS =item COPYRIGHT =back =head2 Text::ParseWords - parse text into an array of tokens or array of arrays =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLES =item AUTHORS =back =head2 Text::Soundex - Implementation of the soundex algorithm. =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLES =item LIMITATIONS =item MAINTAINER =item HISTORY =back =head2 Text::Tabs -- expand and unexpand tabs per the unix expand(1) and unexpand(1) =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLE =item LICENSE =back =head2 Text::Wrap - line wrapping to form simple paragraphs =over 4 =item SYNOPSIS =item DESCRIPTION =item OVERRIDES =item EXAMPLES =item SEE ALSO =item LICENSE =back =head2 Thread - Manipulate threads in Perl (for old code only) =over 4 =item DEPRECATED =item HISTORY =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS $thread = Thread->new(\&start_sub), $thread = Thread->new(\&start_sub, LIST), lock VARIABLE, async BLOCK;, Thread->self, Thread->list, cond_wait VARIABLE, cond_signal VARIABLE, cond_broadcast VARIABLE, yield =item METHODS join, detach, equal, tid, done =item DEFUNCT lock(\&sub), eval, flags =item SEE ALSO =back =head2 Thread::Queue - Thread-safe queues =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION Ordinary scalars, Array refs, Hash refs, Scalar refs, Objects based on the above =item QUEUE CREATION ->new(), ->new(LIST) =item BASIC METHODS ->enqueue(LIST), ->dequeue(), ->dequeue(COUNT), ->dequeue_nb(), ->dequeue_nb(COUNT), ->pending() =item ADVANCED METHODS ->peek(), ->peek(INDEX), ->insert(INDEX, LIST), ->extract(), ->extract(INDEX), ->extract(INDEX, COUNT) =item NOTES =item LIMITATIONS =item SEE ALSO =item MAINTAINER =item LICENSE =back =head2 Thread::Semaphore - Thread-safe semaphores =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS ->new(), ->new(NUMBER), ->down(), ->down(NUMBER), ->down_nb(), ->down_nb(NUMBER), ->down_force(), ->down_force(NUMBER), ->up(), ->up(NUMBER) =item NOTES =item SEE ALSO =item MAINTAINER =item LICENSE =back =head2 Tie::Array - base class for tied arrays =over 4 =item SYNOPSIS =item DESCRIPTION TIEARRAY classname, LIST, STORE this, index, value, FETCH this, index, FETCHSIZE this, STORESIZE this, count, EXTEND this, count, EXISTS this, key, DELETE this, key, CLEAR this, DESTROY this, PUSH this, LIST, POP this, SHIFT this, UNSHIFT this, LIST, SPLICE this, offset, length, LIST =item CAVEATS =item AUTHOR =back =head2 Tie::File - Access the lines of a disk file via a Perl array =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item C<recsep> =item C<autochomp> =item C<mode> =item C<memory> =item C<dw_size> =item Option Format =back =item Public Methods =over 4 =item C<flock> =item C<autochomp> =item C<defer>, C<flush>, C<discard>, and C<autodefer> =item C<offset> =back =item Tying to an already-opened filehandle =item Deferred Writing =over 4 =item Autodeferring =back =item CONCURRENT ACCESS TO FILES =item CAVEATS =item SUBCLASSING =item WHAT ABOUT C<DB_File>? =item AUTHOR =item LICENSE =item WARRANTY =item THANKS =item TODO =back =head2 Tie::Handle - base class definitions for tied handles =over 4 =item SYNOPSIS =item DESCRIPTION TIEHANDLE classname, LIST, WRITE this, scalar, length, offset, PRINT this, LIST, PRINTF this, format, LIST, READ this, scalar, length, offset, READLINE this, GETC this, CLOSE this, OPEN this, filename, BINMODE this, EOF this, TELL this, SEEK this, offset, whence, DESTROY this =item MORE INFORMATION =item COMPATIBILITY =back =head2 Tie::Hash, Tie::StdHash, Tie::ExtraHash - base class definitions for tied hashes =over 4 =item SYNOPSIS =item DESCRIPTION TIEHASH classname, LIST, STORE this, key, value, FETCH this, key, FIRSTKEY this, NEXTKEY this, lastkey, EXISTS this, key, DELETE this, key, CLEAR this, SCALAR this =item Inheriting from B<Tie::StdHash> =item Inheriting from B<Tie::ExtraHash> =item C<SCALAR>, C<UNTIE> and C<DESTROY> =item MORE INFORMATION =back =head2 Tie::Hash::NamedCapture - Named regexp capture buffers =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO =back =head2 Tie::Memoize - add data to hash when needed =over 4 =item SYNOPSIS =item DESCRIPTION =item Inheriting from B<Tie::Memoize> =item EXAMPLE =item BUGS =item AUTHOR =back =head2 Tie::RefHash - use references as hash keys =over 4 =item SYNOPSIS =item DESCRIPTION =item EXAMPLE =item THREAD SUPPORT =item STORABLE SUPPORT =item RELIC SUPPORT =item LICENSE =item MAINTAINER =item AUTHOR =item SEE ALSO =back =head2 Tie::Scalar, Tie::StdScalar - base class definitions for tied scalars =over 4 =item SYNOPSIS =item DESCRIPTION TIESCALAR classname, LIST, FETCH this, STORE this, value, DESTROY this =over 4 =item Tie::Scalar vs Tie::StdScalar =back =item MORE INFORMATION =back =head2 Tie::StdHandle - base class definitions for tied handles =over 4 =item SYNOPSIS =item DESCRIPTION =back =head2 Tie::SubstrHash - Fixed-table-size, fixed-key-length hashing =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEATS =back =head2 Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers =over 4 =item SYNOPSIS =item DESCRIPTION gettimeofday (), usleep ( $useconds ), nanosleep ( $nanoseconds ), ualarm ( $useconds [, $interval_useconds ] ), tv_interval, time (), sleep ( $floating_seconds ), alarm ( $floating_seconds [, $interval_floating_seconds ] ), setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] ), getitimer ( $which ), clock_gettime ( $which ), clock_getres ( $which ), clock_nanosleep ( $which, $nanoseconds, $flags = 0), clock(), stat, stat FH, stat EXPR =item EXAMPLES =item C API =item DIAGNOSTICS =over 4 =item useconds or interval more than ... =item negative time not invented yet =item internal error: useconds < 0 (unsigned ... signed ...) =item useconds or uinterval equal to or more than 1000000 =item unimplemented in this platform =back =item CAVEATS =item SEE ALSO =item AUTHORS =item COPYRIGHT AND LICENSE =back =head2 Time::Local - efficiently compute time from local and GMT time =over 4 =item SYNOPSIS =item DESCRIPTION =item FUNCTIONS =over 4 =item C<timelocal()> and C<timegm()> =item C<timelocal_nocheck()> and C<timegm_nocheck()> =item Year Value Interpretation =item Limits of time_t =item Ambiguous Local Times (DST) =item Non-Existent Local Times (DST) =item Negative Epoch Values =back =item IMPLEMENTATION =item BUGS =item SUPPORT =item COPYRIGHT =item AUTHOR =back =head2 Time::Piece - Object Oriented time objects =over 4 =item SYNOPSIS =item DESCRIPTION =item USAGE =over 4 =item Local Locales =item Date Calculations =item Date Comparisons =item Date Parsing =item YYYY-MM-DDThh:mm:ss =item Week Number =item Global Overriding =back =item CAVEATS =over 4 =item Setting $ENV{TZ} in Threads on Win32 =item Use of epoch seconds =back =item AUTHOR =item License =item SEE ALSO =item BUGS =back =head2 Time::Seconds - a simple API to convert seconds to other date values =over 4 =item SYNOPSIS =item DESCRIPTION =item METHODS =item AUTHOR =item LICENSE =item Bugs =back =head2 Time::gmtime - by-name interface to Perl's built-in gmtime() function =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTE =item AUTHOR =back =head2 Time::localtime - by-name interface to Perl's built-in localtime() function =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTE =item AUTHOR =back =head2 Time::tm - internal object used by Time::gmtime and Time::localtime =over 4 =item SYNOPSIS =item DESCRIPTION =item AUTHOR =back =head2 UNIVERSAL - base class for ALL classes (blessed references) =over 4 =item SYNOPSIS =item DESCRIPTION C<< $obj->isa( TYPE ) >>, C<< CLASS->isa( TYPE ) >>, C<< eval { VAL->isa( TYPE ) } >>, C<TYPE>, C<$obj>, C<CLASS>, C<VAL>, C<< $obj->DOES( ROLE ) >>, C<< CLASS->DOES( ROLE ) >>, C<< $obj->can( METHOD ) >>, C<< CLASS->can( METHOD ) >>, C<< eval { VAL->can( METHOD ) } >>, C<VERSION ( [ REQUIRE ] )> =item WARNINGS =item EXPORTS =back =head2 Unicode::Collate - Unicode Collation Algorithm =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Constructor and Tailoring UCA_Version, alternate, backwards, entry, hangul_terminator, ignoreChar, ignoreName, ignore_level2, katakana_before_hiragana, level, normalization, overrideCJK, overrideHangul, preprocess, rearrange, rewrite, suppress, table, undefChar, undefName, upper_before_lower, variable =item Methods for Collation C<@sorted = $Collator-E<gt>sort(@not_sorted)>, C<$result = $Collator-E<gt>cmp($a, $b)>, C<$result = $Collator-E<gt>eq($a, $b)>, C<$result = $Collator-E<gt>ne($a, $b)>, C<$result = $Collator-E<gt>lt($a, $b)>, C<$result = $Collator-E<gt>le($a, $b)>, C<$result = $Collator-E<gt>gt($a, $b)>, C<$result = $Collator-E<gt>ge($a, $b)>, C<$sortKey = $Collator-E<gt>getSortKey($string)>, C<$sortKeyForm = $Collator-E<gt>viewSortKey($string)> =item Methods for Searching C<$position = $Collator-E<gt>index($string, $substring[, $position])>, C<($position, $length) = $Collator-E<gt>index($string, $substring[, $position])>, C<$match_ref = $Collator-E<gt>match($string, $substring)>, C<($match) = $Collator-E<gt>match($string, $substring)>, C<@match = $Collator-E<gt>gmatch($string, $substring)>, C<$count = $Collator-E<gt>subst($string, $substring, $replacement)>, C<$count = $Collator-E<gt>gsubst($string, $substring, $replacement)> =item Other Methods C<%old_tailoring = $Collator-E<gt>change(%new_tailoring)>, C<$modified_collator = $Collator-E<gt>change(%new_tailoring)>, C<$version = $Collator-E<gt>version()>, C<UCA_Version()>, C<Base_Unicode_Version()> =back =item EXPORT =item INSTALL =item CAVEATS Normalization, Conformance Test =item AUTHOR, COPYRIGHT AND LICENSE =item SEE ALSO Unicode Collation Algorithm - UTS #10, The Default Unicode Collation Element Table (DUCET), The conformance test for the UCA, Hangul Syllable Type, Unicode Normalization Forms - UAX #15, Unicode Locale Data Markup Language (LDML) - UTS #35 =back =head2 Unicode::Collate::CJK::Big5 - weighting CJK Unified Ideographs for Unicode::Collate =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO CLDR - Unicode Common Locale Data Repository, Unicode Locale Data Markup Language (LDML) - UTS #35, L<Unicode::Collate>, L<Unicode::Collate::Locale> =back =head2 Unicode::Collate::CJK::GB2312 - weighting CJK Unified Ideographs for Unicode::Collate =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEAT =item SEE ALSO CLDR - Unicode Common Locale Data Repository, Unicode Locale Data Markup Language (LDML) - UTS #35, L<Unicode::Collate>, L<Unicode::Collate::Locale> =back =head2 Unicode::Collate::CJK::JISX0208 - weighting JIS KANJI for Unicode::Collate =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO L<Unicode::Collate>, L<Unicode::Collate::Locale> =back =head2 Unicode::Collate::CJK::Korean - weighting CJK Unified Ideographs for Unicode::Collate =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO CLDR - Unicode Common Locale Data Repository, Unicode Locale Data Markup Language (LDML) - UTS #35, L<Unicode::Collate>, L<Unicode::Collate::Locale> =back =head2 Unicode::Collate::CJK::Pinyin - weighting CJK Unified Ideographs for Unicode::Collate =over 4 =item SYNOPSIS =item DESCRIPTION =item CAVEAT =item SEE ALSO CLDR - Unicode Common Locale Data Repository, Unicode Locale Data Markup Language (LDML) - UTS #35, L<Unicode::Collate>, L<Unicode::Collate::Locale> =back =head2 Unicode::Collate::CJK::Stroke - weighting CJK Unified Ideographs for Unicode::Collate =over 4 =item SYNOPSIS =item DESCRIPTION =item SEE ALSO CLDR - Unicode Common Locale Data Repository, Unicode Locale Data Markup Language (LDML) - UTS #35, L<Unicode::Collate>, L<Unicode::Collate::Locale> =back =head2 Unicode::Collate::Locale - Linguistic tailoring for DUCET via Unicode::Collate =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Constructor =item Methods C<$Collator-E<gt>getlocale>, C<$Collator-E<gt>locale_version> =item A list of tailorable locales =back =item INSTALL =item CAVEAT tailoring is not maximum =item AUTHOR =item SEE ALSO Unicode Collation Algorithm - UTS #10, The Default Unicode Collation Element Table (DUCET), Unicode Locale Data Markup Language (LDML) - UTS #35, CLDR - Unicode Common Locale Data Repository, L<Unicode::Collate>, L<Unicode::Normalize> =back =head2 Unicode::Normalize - Unicode Normalization Forms =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item Normalization Forms C<$NFD_string = NFD($string)>, C<$NFC_string = NFC($string)>, C<$NFKD_string = NFKD($string)>, C<$NFKC_string = NFKC($string)>, C<$FCD_string = FCD($string)>, C<$FCC_string = FCC($string)>, C<$normalized_string = normalize($form_name, $string)> =item Decomposition and Composition C<$decomposed_string = decompose($string [, $useCompatMapping])>, C<$reordered_string = reorder($string)>, C<$composed_string = compose($string)>, C<($processed, $unprocessed) = splitOnLastStarter($normalized)>, C<$processed = normalize_partial($form, $unprocessed)>, C<$processed = NFD_partial($unprocessed)>, C<$processed = NFC_partial($unprocessed)>, C<$processed = NFKD_partial($unprocessed)>, C<$processed = NFKC_partial($unprocessed)> =item Quick Check C<$result = checkNFD($string)>, C<$result = checkNFC($string)>, C<$result = checkNFKD($string)>, C<$result = checkNFKC($string)>, C<$result = checkFCD($string)>, C<$result = checkFCC($string)>, C<$result = check($form_name, $string)> =item Character Data C<$canonical_decomposition = getCanon($code_point)>, C<$compatibility_decomposition = getCompat($code_point)>, C<$code_point_composite = getComposite($code_point_here, $code_point_next)>, C<$combining_class = getCombinClass($code_point)>, C<$may_be_composed_with_prev_char = isComp2nd($code_point)>, C<$is_exclusion = isExclusion($code_point)>, C<$is_singleton = isSingleton($code_point)>, C<$is_non_starter_decomposition = isNonStDecomp($code_point)>, C<$is_Full_Composition_Exclusion = isComp_Ex($code_point)>, C<$NFD_is_NO = isNFD_NO($code_point)>, C<$NFC_is_NO = isNFC_NO($code_point)>, C<$NFC_is_MAYBE = isNFC_MAYBE($code_point)>, C<$NFKD_is_NO = isNFKD_NO($code_point)>, C<$NFKC_is_NO = isNFKC_NO($code_point)>, C<$NFKC_is_MAYBE = isNFKC_MAYBE($code_point)> =back =item EXPORT =item CAVEATS Perl's version vs. Unicode version, Correction of decomposition mapping, Revised definition of canonical composition =item AUTHOR =item SEE ALSO http://www.unicode.org/reports/tr15/, http://www.unicode.org/Public/UNIDATA/CompositionExclusions.txt, http://www.unicode.org/Public/UNIDATA/DerivedNormalizationProps.txt, http://www.unicode.org/Public/UNIDATA/NormalizationCorrections.txt, http://www.unicode.org/review/pr-29.html, http://www.unicode.org/notes/tn5/ =back =head2 Unicode::UCD - Unicode character database =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item code point argument =back =back =over 4 =item B<charinfo()> B<code>, B<name>, B<category>, B<combining>, B<bidi>, B<decomposition>, B<decimal>, B<digit>, B<numeric>, B<mirrored>, B<unicode10>, B<comment>, B<upper>, B<lower>, B<title>, B<block>, B<script> =back =over 4 =item B<charblock()> =back =over 4 =item B<charscript()> =back =over 4 =item B<charblocks()> =back =over 4 =item B<charscripts()> =back =over 4 =item B<charinrange()> =back =over 4 =item B<general_categories()> =back =over 4 =item B<bidi_types()> =back =over 4 =item B<compexcl()> =back =over 4 =item B<casefold()> B<code>, B<full>, B<simple>, B<mapping>, B<status>, B<*> If you use this C<I> mapping, B<*> If you exclude this C<I> mapping, B<turkic> =back =over 4 =item B<casespec()> B<code>, B<lower>, B<title>, B<upper>, B<condition> =back =over 4 =item B<namedseq()> =back =over 4 =item B<num()> =back =over 4 =item B<prop_aliases()> =back =over 4 =item B<prop_value_aliases()> =back =over 4 =item B<prop_invlist()> =back =over 4 =item B<prop_invmap()> B<C<s>>, B<C<sl>>, C<correction>, C<control>, C<alternate>, C<figment>, C<abbreviation>, B<C<a>>, B<C<al>>, B<C<ae>>, B<C<ale>>, B<C<ar>>, B<C<n>>, B<C<ad>> =back =over 4 =item Unicode::UCD::UnicodeVersion =back =over 4 =item B<Blocks versus Scripts> =item B<Matching Scripts and Blocks> =item Old-style versus new-style block names =back =over 4 =item BUGS =item AUTHOR =back =head2 User::grent - by-name interface to Perl's built-in getgr*() functions =over 4 =item SYNOPSIS =item DESCRIPTION =item NOTE =item AUTHOR =back =head2 User::pwent - by-name interface to Perl's built-in getpw*() functions =over 4 =item SYNOPSIS =item DESCRIPTION =over 4 =item System Specifics =back =item NOTE =item AUTHOR =item HISTORY March 18th, 2000 =back =head2 Version::Requirements - a set of version requirements for a CPAN dist =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =item METHODS =over 4 =item new =item add_minimum =item add_maximum =item add_exclusion =item exact_version =item add_requirements =item accepts_module =item clear_requirement =item required_modules =item clone =item is_simple =item is_finalized =item finalize =item as_string_hash =item from_string_hash =back =item AUTHOR =item COPYRIGHT AND LICENSE =back =head2 XSLoader - Dynamically load C libraries into Perl code =over 4 =item VERSION =item SYNOPSIS =item DESCRIPTION =over 4 =item Migration from C<DynaLoader> =item Backward compatible boilerplate =back =item Order of initialization: early load() =over 4 =item The most hairy case =back =item DIAGNOSTICS C<Can't find '%s' symbol in %s>, C<Can't load '%s' for module %s: %s>, C<Undefined symbols present after loading %s: %s> =item LIMITATIONS =item KNOWN BUGS =item BUGS =item SEE ALSO =item AUTHORS =item COPYRIGHT & LICENSE =back =head1 AUXILIARY DOCUMENTATION Here should be listed all the extra programs' documentation, but they don't all have manual pages yet: =over 4 =item a2p =item c2ph =item h2ph =item h2xs =item perlbug =item pl2pm =item pod2html =item pod2man =item s2p =item splain =item xsubpp =back =head1 AUTHOR Larry Wall <F<larry@wall.org>>, with the help of oodles of other folks. PK PU�\�j�kf kf perlootut.podnu �[��� =encoding utf8 =for comment Consistent formatting of this file is achieved with: perl ./Porting/podtidy pod/perlootut.pod =head1 NAME perlootut - Object-Oriented Programming in Perl Tutorial =head1 DATE This document was created in February, 2011. =head1 DESCRIPTION This document provides an introduction to object-oriented programming in Perl. It begins with a brief overview of the concepts behind object oriented design. Then it introduces several different OO systems from L<CPAN|http://search.cpan.org> which build on top of what Perl provides. By default, Perl's built-in OO system is very minimal, leaving you to do most of the work. This minimalism made a lot of sense in 1994, but in the years since Perl 5.0 we've seen a number of common patterns emerge in Perl OO. Fortunately, Perl's flexibility has allowed a rich ecosystem of Perl OO systems to flourish. If you want to know how Perl OO works under the hood, the L<perlobj> document explains the nitty gritty details. This document assumes that you already understand the basics of Perl syntax, variable types, operators, and subroutine calls. If you don't understand these concepts yet, please read L<perlintro> first. You should also read the L<perlsyn>, L<perlop>, and L<perlsub> documents. =head1 OBJECT-ORIENTED FUNDAMENTALS Most object systems share a number of common concepts. You've probably heard terms like "class", "object, "method", and "attribute" before. Understanding the concepts will make it much easier to read and write object-oriented code. If you're already familiar with these terms, you should still skim this section, since it explains each concept in terms of Perl's OO implementation. Perl's OO system is class-based. Class-based OO is fairly common. It's used by Java, C++, C#, Python, Ruby, and many other languages. There are other object orientation paradigms as well. JavaScript is the most popular language to use another paradigm. JavaScript's OO system is prototype-based. =head2 Object An B<object> is a data structure that bundles together data and subroutines which operate on that data. An object's data is called B<attributes>, and its subroutines are called B<methods>. An object can be thought of as a noun (a person, a web service, a computer). An object represents a single discrete thing. For example, an object might represent a file. The attributes for a file object might include its path, content, and last modification time. If we created an object to represent F</etc/hostname> on a machine named "foo.example.com", that object's path would be "/etc/hostname", its content would be "foo\n", and it's last modification time would be 1304974868 seconds since the beginning of the epoch. The methods associated with a file might include C<rename()> and C<write()>. In Perl most objects are hashes, but the OO systems we recommend keep you from having to worry about this. In practice, it's best to consider an object's internal data structure opaque. =head2 Class A B<class> defines the behavior of a category of objects. A class is a name for a category (like "File"), and a class also defines the behavior of objects in that category. All objects belong to a specific class. For example, our F</etc/hostname> object belongs to the C<File> class. When we want to create a specific object, we start with its class, and B<construct> or B<instantiate> an object. A specific object is often referred to as an B<instance> of a class. In Perl, any package can be a class. The difference between a package which is a class and one which isn't is based on how the package is used. Here's our "class declaration" for the C<File> class: package File; In Perl, there is no special keyword for constructing an object. However, most OO modules on CPAN use a method named C<new()> to construct a new object: my $hostname = File->new( path => '/etc/hostname', content => "foo\n", last_mod_time => 1304974868, ); (Don't worry about that C<< -> >> operator, it will be explained later.) =head3 Blessing As we said earlier, most Perl objects are hashes, but an object can be an instance of any Perl data type (scalar, array, etc.). Turning a plain data structure into an object is done by B<blessing> that data structure using Perl's C<bless> function. While we strongly suggest you don't build your objects from scratch, you should know the term B<bless>. A B<blessed> data structure (aka "a referent") is an object. We sometimes say that an object has been "blessed into a class". Once a referent has been blessed, the C<blessed> function from the L<Scalar::Util> core module can tell us its class name. This subroutine returns an object's class when passed an object, and false otherwise. use Scalar::Util 'blessed'; print blessed($hash); # undef print blessed($hostname); # File =head3 Constructor A B<constructor> creates a new object. In Perl, a class's constructor is just another method, unlike some other languages, which provide syntax for constructors. Most Perl classes use C<new> as the name for their constructor: my $file = File->new(...); =head2 Methods You already learned that a B<method> is a subroutine that operates on an object. You can think of a method as the things that an object can I<do>. If an object is a noun, then methods are its verbs (save, print, open). In Perl, methods are simply subroutines that live in a class's package. Methods are always written to receive the object as their first argument: sub print_info { my $self = shift; print "This file is at ", $self->path, "\n"; } $file->print_info; # The file is at /etc/hostname What makes a method special is I<how it's called>. The arrow operator (C<< -> >>) tells Perl that we are calling a method. When we make a method call, Perl arranges for the method's B<invocant> to be passed as the first argument. B<Invocant> is a fancy name for the thing on the left side of the arrow. The invocant can either be a class name or an object. We can also pass additional arguments to the method: sub print_info { my $self = shift; my $prefix = shift // "This file is at "; print $prefix, ", ", $self->path, "\n"; } $file->print_info("The file is located at "); # The file is located at /etc/hostname =head2 Attributes Each class can define its B<attributes>. When we instantiate an object, we assign values to those attributes. For example, every C<File> object has a path. Attributes are sometimes called B<properties>. Perl has no special syntax for attributes. Under the hood, attributes are often stored as keys in the object's underlying hash, but don't worry about this. We recommend that you only access attributes via B<accessor> methods. These are methods that can get or set the value of each attribute. We saw this earlier in the C<print_info()> example, which calls C<< $self->path >>. You might also see the terms B<getter> and B<setter>. These are two types of accessors. A getter gets the attribute's value, while a setter sets it. Another term for a setter is B<mutator> Attributes are typically defined as read-only or read-write. Read-only attributes can only be set when the object is first created, while read-write attributes can be altered at any time. The value of an attribute may itself be another object. For example, instead of returning its last mod time as a number, the C<File> class could return a L<DateTime> object representing that value. It's possible to have a class that does not expose any publicly settable attributes. Not every class has attributes and methods. =head2 Polymorphism B<Polymorphism> is a fancy way of saying that objects from two different classes share an API. For example, we could have C<File> and C<WebPage> classes which both have a C<print_content()> method. This method might produce different output for each class, but they share a common interface. While the two classes may differ in many ways, when it comes to the C<print_content()> method, they are the same. This means that we can try to call the C<print_content()> method on an object of either class, and B<we don't have to know what class the object belongs to!> Polymorphism is one of the key concepts of object-oriented design. =head2 Inheritance B<Inheritance> lets you create a specialized version of an existing class. Inheritance lets the new class to reuse the methods and attributes of another class. For example, we could create an C<File::MP3> class which B<inherits> from C<File>. An C<File::MP3> B<is-a> I<more specific> type of C<File>. All mp3 files are files, but not all files are mp3 files. We often refer to inheritance relationships as B<parent-child> or C<superclass/subclass> relationships. Sometimes we say that the child has an B<is-a> relationship with its parent class. C<File> is a B<superclass> of C<File::MP3>, and C<File::MP3> is a B<subclass> of C<File>. package File::MP3; use parent 'File'; The L<parent> module is one of several ways that Perl lets you define inheritance relationships. Perl allows multiple inheritance, which means that a class can inherit from multiple parents. While this is possible, we strongly recommend against it. Generally, you can use B<roles> to do everything you can do with multiple inheritance, but in a cleaner way. Note that there's nothing wrong with defining multiple subclasses of a given class. This is both common and safe. For example, we might define C<File::MP3::FixedBitrate> and C<File::MP3::VariableBitrate> classes to distinguish between different types of mp3 file. =head3 Overriding methods and method resolution Inheritance allows two classes to share code. By default, every method in the parent class is also available in the child. The child can explicitly B<override> a parent's method to provide its own implementation. For example, if we have an C<File::MP3> object, it has the C<print_info()> method from C<File>: my $cage = File::MP3->new( path => 'mp3s/My-Body-Is-a-Cage.mp3', content => $mp3_data, last_mod_time => 1304974868, title => 'My Body Is a Cage', ); $cage->print_info; # The file is at mp3s/My-Body-Is-a-Cage.mp3 If we wanted to include the mp3's title in the greeting, we could override the method: package File::MP3; use parent 'File'; sub print_info { my $self = shift; print "This file is at ", $self->path, "\n"; print "Its title is ", $self->title, "\n"; } $cage->print_info; # The file is at mp3s/My-Body-Is-a-Cage.mp3 # Its title is My Body Is a Cage The process of determining what method should be used is called B<method resolution>. What Perl does is look at the object's class first (C<File::MP3> in this case). If that class defines the method, then that class's version of the method is called. If not, Perl looks at each parent class in turn. For C<File::MP3>, its only parent is C<File>. If C<File::MP3> does not define the method, but C<File> does, then Perl calls the method in C<File>. If C<File> inherited from C<DataSource>, which inherited from C<Thing>, then Perl would keep looking "up the chain" if necessary. It is possible to explicitly call a parent method from a child: package File::MP3; use parent 'File'; sub print_info { my $self = shift; $self->SUPER::print_info(); print "Its title is ", $self->title, "\n"; } The C<SUPER::> bit tells Perl to look for the C<print_info()> in the C<File::MP3> class's inheritance chain. When it finds the parent class that implements this method, the method is called. We mentioned multiple inheritance earlier. The main problem with multiple inheritance is that it greatly complicates method resolution. See L<perlobj> for more details. =head2 Encapsulation B<Encapsulation> is the idea that an object is opaque. When another developer uses your class, they don't need to know I<how> it is implemented, they just need to know I<what> it does. Encapsulation is important for several reasons. First, it allows you to separate the public API from the private implementation. This means you can change that implementation without breaking the API. Second, when classes are well encapsulated, they become easier to subclass. Ideally, a subclass uses the same APIs to access object data that its parent class uses. In reality, subclassing sometimes involves violating encapsulation, but a good API can minimize the need to do this. We mentioned earlier that most Perl objects are implemented as hashes under the hood. The principle of encapsulation tells us that we should not rely on this. Instead, we should use accessor methods to access the data in that hash. The object systems that we recommend below all automate the generation of accessor methods. If you use one of them, you should never have to access the object as a hash directly. =head2 Composition In object-oriented code, we often find that one object references another object. This is called B<composition>, or a B<has-a> relationship. Earlier, we mentioned that the C<File> class's C<last_mod_time> accessor could return a L<DateTime> object. This is a perfect example of composition. We could go even further, and make the C<path> and C<content> accessors return objects as well. The C<File> class would then be B<composed> of several other objects. =head2 Roles B<Roles> are something that a class I<does>, rather than something that it I<is>. Roles are relatively new to Perl, but have become rather popular. Roles are B<applied> to classes. Sometimes we say that classes B<consume> roles. Roles are an alternative to inheritance for providing polymorphism. Let's assume we have two classes, C<Radio> and C<Computer>. Both of these things have on/off switches. We want to model that in our class definitions. We could have both classes inherit from a common parent, like C<Machine>, but not all machines have on/off switches. We could create a parent class called C<HasOnOffSwitch>, but that is very artificial. Radios and computers are not specializations of this parent. This parent is really a rather ridiculous creation. This is where roles come in. It makes a lot of sense to create a C<HasOnOffSwitch> role and apply it to both classes. This role would define a known API like providing C<turn_on()> and C<turn_off()> methods. Perl does not have any built-in way to express roles. In the past, people just bit the bullet and used multiple inheritance. Nowadays, there are several good choices on CPAN for using roles. =head2 When to Use OO Object Orientation is not the best solution to every problem. In I<Perl Best Practices> (copyright 2004, Published by O'Reilly Media, Inc.), Damian Conway provides a list of criteria to use when deciding if OO is the right fit for your problem: =over 4 =item * The system being designed is large, or is likely to become large. =item * The data can be aggregated into obvious structures, especially if there's a large amount of data in each aggregate. =item * The various types of data aggregate form a natural hierarchy that facilitates the use of inheritance and polymorphism. =item * You have a piece of data on which many different operations are applied. =item * You need to perform the same general operations on related types of data, but with slight variations depending on the specific type of data the operations are applied to. =item * It's likely you'll have to add new data types later. =item * The typical interactions between pieces of data are best represented by operators. =item * The implementation of individual components of the system is likely to change over time. =item * The system design is already object-oriented. =item * Large numbers of other programmers will be using your code modules. =back =head1 PERL OO SYSTEMS As we mentioned before, Perl's built-in OO system is very minimal, but also quite flexible. Over the years, many people have developed systems which build on top of Perl's built-in system to provide more features and convenience. We strongly recommend that you use one of these systems. Even the most minimal of them eliminates a lot of repetitive boilerplate. There's really no good reason to write your classes from scratch in Perl. If you are interested in the guts underlying these systems, check out L<perlobj>. =head2 Moose L<Moose> bills itself as a "postmodern object system for Perl 5". Don't be scared, the "postmodern" label is a callback to Larry's description of Perl as "the first postmodern computer language". C<Moose> provides a complete, modern OO system. Its biggest influence is the Common Lisp Object System, but it also borrows ideas from Smalltalk and several other languages. C<Moose> was created by Stevan Little, and draws heavily from his work on the Perl 6 OO design. Here is our C<File> class using C<Moose>: package File; use Moose; has path => ( is => 'ro' ); has content => ( is => 'ro' ); has last_mod_time => ( is => 'ro' ); sub print_info { my $self = shift; print "This file is at ", $self->path, "\n"; } C<Moose> provides a number of features: =over 4 =item * Declarative sugar C<Moose> provides a layer of declarative "sugar" for defining classes. That sugar is just a set of exported functions that make declaring how your class works simpler and more palatable. This lets you describe I<what> your class is, rather than having to tell Perl I<how> to implement your class. The C<has()> subroutine declares an attribute, and C<Moose> automatically creates accessors for these attributes. It also takes care of creating a C<new()> method for you. This constructor knows about the attributes you declared, so you can set them when creating a new C<File>. =item * Roles built-in C<Moose> lets you define roles the same way you define classes: package HasOnOfSwitch; use Moose::Role; has is_on => ( is => 'rw', isa => 'Bool', ); sub turn_on { my $self = shift; $self->is_on(1); } sub turn_off { my $self = shift; $self->is_on(0); } =item * A miniature type system In the example above, you can see that we passed C<< isa => 'Bool' >> to C<has()> when creating our C<is_on> attribute. This tells C<Moose> that this attribute must be a boolean value. If we try to set it to an invalid value, our code will throw an error. =item * Full introspection and manipulation Perl's built-in introspection features are fairly minimal. C<Moose> builds on top of them and creates a full introspection layer for your classes. This lets you ask questions like "what methods does the File class implement?" It also lets you modify your classes programmatically. =item * Self-hosted and extensible C<Moose> describes itself using its own introspection API. Besides being a cool trick, this means that you can extend C<Moose> using C<Moose> itself. =item * Rich ecosystem There is a rich ecosystem of C<Moose> extensions on CPAN under the L<MooseX|http://search.cpan.org/search?query=MooseX&mode=dist> namespace. In addition, many modules on CPAN already use C<Moose>, providing you with lots of examples to learn from. =item * Many more features C<Moose> is a very powerful tool, and we can't cover all of its features here. We encourage you to learn more by reading the C<Moose> documentation, starting with L<Moose::Manual|http://search.cpan.org/perldoc?Moose::Manual>. =back Of course, C<Moose> isn't perfect. C<Moose> can make your code slower to load. C<Moose> itself is not small, and it does a I<lot> of code generation when you define your class. This code generation means that your runtime code is as fast as it can be, but you pay for this when your modules are first loaded. This load time hit can be a problem when startup speed is important, such as with a command-line script or a "plain vanilla" CGI script that must be loaded each time it is executed. Before you panic, know that many people do use C<Moose> for command-line tools and other startup-sensitive code. We encourage you to try C<Moose> out first before worrying about startup speed. C<Moose> also has several dependencies on other modules. Most of these are small stand-alone modules, a number of which have been spun off from C<Moose>. C<Moose> itself, and some of its dependencies, require a compiler. If you need to install your software on a system without a compiler, or if having I<any> dependencies is a problem, then C<Moose> may not be right for you. =head3 Mouse If you try C<Moose> and find that one of these issues is preventing you from using C<Moose>, we encourage you to consider L<Mouse> next. C<Mouse> implements a subset of C<Moose>'s functionality in a simpler package. For all features that it does implement, the end-user API is I<identical> to C<Moose>, meaning you can switch from C<Mouse> to C<Moose> quite easily. C<Mouse> does not implement most of C<Moose>'s introspection API, so it's often faster when loading your modules. Additionally, all of its I<required> dependencies ship with the Perl core, and it can run without a compiler. If you do have a compiler, C<Mouse> will use it to compile some of its code for a speed boost. Finally, it ships with a C<Mouse::Tiny> module that takes most of C<Mouse>'s features and bundles them up in a single module file. You can copy this module file into your application's library directory for easy bundling. The C<Moose> authors hope that one day C<Mouse> can be made obsolete by improving C<Moose> enough, but for now it provides a worthwhile alternative to C<Moose>. =head2 Class::Accessor L<Class::Accessor> is the polar opposite of C<Moose>. It provides very few features, nor is it self-hosting. It is, however, very simple, pure Perl, and it has no non-core dependencies. It also provides a "Moose-like" API on demand for the features it supports. Even though it doesn't do much, it is still preferable to writing your own classes from scratch. Here's our C<File> class with C<Class::Accessor>: package File; use Class::Accessor 'antlers'; has path => ( is => 'ro' ); has content => ( is => 'ro' ); has last_mod_time => ( is => 'ro' ); sub print_info { my $self = shift; print "This file is at ", $self->path, "\n"; } The C<antlers> import flag tells C<Class::Accessor> that you want to define your attributes using C<Moose>-like syntax. The only parameter that you can pass to C<has> is C<is>. We recommend that you use this Moose-like syntax if you choose C<Class::Accessor> since it means you will have a smoother upgrade path if you later decide to move to C<Moose>. Like C<Moose>, C<Class::Accessor> generates accessor methods and a constructor for your class. =head2 Object::Tiny Finally, we have L<Object::Tiny>. This module truly lives up to its name. It has an incredibly minimal API and absolutely no dependencies (core or not). Still, we think it's a lot easier to use than writing your own OO code from scratch. Here's our C<File> class once more: package File; use Object::Tiny qw( path content last_mod_time ); sub print_info { my $self = shift; print "This file is at ", $self->path, "\n"; } That's it! With C<Object::Tiny>, all accessors are read-only. It generates a constructor for you, as well as the accessors you define. =head2 Role::Tiny As we mentioned before, roles provide an alternative to inheritance, but Perl does not have any built-in role support. If you choose to use Moose, it comes with a full-fledged role implementation. However, if you use one of our other recommended OO modules, you can still use roles with L<Role::Tiny> C<Role::Tiny> provides some of the same features as Moose's role system, but in a much smaller package. Most notably, it doesn't support any sort of attribute declaration, so you have to do that by hand. Still, it's useful, and works well with C<Class::Accessor> and C<Object::Tiny> =head2 OO System Summary Here's a brief recap of the options we covered: =over 4 =item * L<Moose> C<Moose> is the maximal option. It has a lot of features, a big ecosystem, and a thriving user base. We also covered L<Mouse> briefly. C<Mouse> is C<Moose> lite, and a reasonable alternative when Moose doesn't work for your application. =item * L<Class::Accessor> C<Class::Accessor> does a lot less than C<Moose>, and is a nice alternative if you find C<Moose> overwhelming. It's been around a long time and is well battle-tested. It also has a minimal C<Moose> compatibility mode which makes moving from C<Class::Accessor> to C<Moose> easy. =item * L<Object::Tiny> C<Object::Tiny> is the absolute minimal option. It has no dependencies, and almost no syntax to learn. It's a good option for a super minimal environment and for throwing something together quickly without having to worry about details. =item * L<Role::Tiny> Use C<Role::Tiny> with C<Class::Accessor> or C<Object::Tiny> if you find yourself considering multiple inheritance. If you go with C<Moose>, it comes with its own role implementation. =back =head2 Other OO Systems There are literally dozens of other OO-related modules on CPAN besides those covered here, and you're likely to run across one or more of them if you work with other people's code. In addition, plenty of code in the wild does all of its OO "by hand", using just the Perl built-in OO features. If you need to maintain such code, you should read L<perlobj> to understand exactly how Perl's built-in OO works. =head1 CONCLUSION As we said before, Perl's minimal OO system has led to a profusion of OO systems on CPAN. While you can still drop down to the bare metal and write your classes by hand, there's really no reason to do that with modern Perl. For small systems, L<Object::Tiny> and L<Class::Accessor> both provide minimal object systems that take care of basic boilerplate for you. For bigger projects, L<Moose> provides a rich set of features that will let you focus on implementing your business logic. We encourage you to play with and evaluate L<Moose>, L<Class::Accessor>, and L<Object::Tiny> to see which OO system is right for you. =cut PK PU�\@�kKCp Cp perlhpux.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see pod/perlpod.pod) which is specially designed to be readable as is. =head1 NAME perlhpux - Perl version 5 on Hewlett-Packard Unix (HP-UX) systems =head1 DESCRIPTION This document describes various features of HP's Unix operating system (HP-UX) that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs. =head2 Using perl as shipped with HP-UX Application release September 2001, HP-UX 11.00 is the first to ship with Perl. By the time it was perl-5.6.1 in /opt/perl. The first occurrence is on CD 5012-7954 and can be installed using swinstall -s /cdrom perl assuming you have mounted that CD on /cdrom. In this version the following modules were installed: ActivePerl::DocTools-0.04 HTML::Parser-3.19 XML::DOM-1.25 Archive::Tar-0.072 HTML::Tagset-3.03 XML::Parser-2.27 Compress::Zlib-1.08 MIME::Base64-2.11 XML::Simple-1.05 Convert::ASN1-0.10 Net-1.07 XML::XPath-1.09 Digest::MD5-2.11 PPM-2.1.5 XML::XSLT-0.32 File::CounterFile-0.12 SOAP::Lite-0.46 libwww-perl-5.51 Font::AFM-1.18 Storable-1.011 libxml-perl-0.07 HTML-Tree-3.11 URI-1.11 perl-ldap-0.23 That build was a portable hppa-1.1 multithread build that supports large files compiled with gcc-2.9-hppa-991112. If you perform a new installation, then (a newer) Perl will be installed automatically. Preinstalled HP-UX systems now slao have more recent versions of Perl and the updated modules. The official (threaded) builds from HP, as they are shipped on the Application DVD/CD's are available on L<http://www.software.hp.com/portal/swdepot/displayProductInfo.do?productNumber=PERL> for both PA-RISC and IPF (Itanium Processor Family). They are built with the HP ANSI-C compiler. Up till 5.8.8 that was done by ActiveState. To see what version is included on the DVD (assumed here to be mounted on /cdrom), issue this command: # swlist -s /cdrom perl # perl D.5.8.8.B 5.8.8 Perl Programming Language perl.Perl5-32 D.5.8.8.B 32-bit 5.8.8 Perl Programming Language with Extensions perl.Perl5-64 D.5.8.8.B 64-bit 5.8.8 Perl Programming Language with Extensions =head2 Using perl from HP's porting centre HP porting centre tries very hard to keep up with customer demand and release updates from the Open Source community. Having precompiled Perl binaries available is obvious. The HP porting centres are limited in what systems they are allowed to port to and they usually choose the two most recent OS versions available. This means that at the moment of writing, there are only HP-UX 11.11 (pa-risc 2.0) and HP-UX 11.23 (Itanium 2) ports available on the porting centres. HP has asked the porting centre to move Open Source binaries from /opt to /usr/local, so binaries produced since the start of July 2002 are located in /usr/local. One of HP porting centres URL's is L<http://hpux.connect.org.uk/> The port currently available is built with GNU gcc. =head2 Compiling Perl 5 on HP-UX When compiling Perl, you must use an ANSI C compiler. The C compiler that ships with all HP-UX systems is a K&R compiler that should only be used to build new kernels. Perl can be compiled with either HP's ANSI C compiler or with gcc. The former is recommended, as not only can it compile Perl with no difficulty, but also can take advantage of features listed later that require the use of HP compiler-specific command-line flags. If you decide to use gcc, make sure your installation is recent and complete, and be sure to read the Perl INSTALL file for more gcc-specific details. =head2 PA-RISC HP's HP9000 Unix systems run on HP's own Precision Architecture (PA-RISC) chip. HP-UX used to run on the Motorola MC68000 family of chips, but any machine with this chip in it is quite obsolete and this document will not attempt to address issues for compiling Perl on the Motorola chipset. The version of PA-RISC at the time of this document's last update is 2.0, which is also the last there will be. HP PA-RISC systems are usually refered to with model description "HP 9000". The last CPU in this series is the PA-8900. Support for PA-RISC architectured machines officially ends as shown in the following table: PA-RISC End-of-Life Roadmap +--------+----------------+----------------+-----------------+ | HP9000 | Superdome | PA-8700 | Spring 2011 | | 4-128 | | PA-8800/sx1000 | Summer 2012 | | cores | | PA-8900/sx1000 | 2014 | | | | PA-8900/sx2000 | 2015 | +--------+----------------+----------------+-----------------+ | HP9000 | rp7410, rp8400 | PA-8700 | Spring 2011 | | 2-32 | rp7420, rp8420 | PA-8800/sx1000 | 2012 | | cores | rp7440, rp8440 | PA-8900/sx1000 | Autumn 2013 | | | | PA-8900/sx2000 | 2015 | +--------+----------------+----------------+-----------------+ | HP9000 | rp44x0 | PA-8700 | Spring 2011 | | 1-8 | | PA-8800/rp44x0 | 2012 | | cores | | PA-8900/rp44x0 | 2014 | +--------+----------------+----------------+-----------------+ | HP9000 | rp34x0 | PA-8700 | Spring 2011 | | 1-4 | | PA-8800/rp34x0 | 2012 | | cores | | PA-8900/rp34x0 | 2014 | +--------+----------------+----------------+-----------------+ From L<http://www.hp.com/products1/evolution/9000/faqs.html> The last order date for HP 9000 systems was December 31, 2008. A complete list of models at the time the OS was built is in the file /usr/sam/lib/mo/sched.models. The first column corresponds to the last part of the output of the "model" command. The second column is the PA-RISC version and the third column is the exact chip type used. (Start browsing at the bottom to prevent confusion ;-) # model 9000/800/L1000-44 # grep L1000-44 /usr/sam/lib/mo/sched.models L1000-44 2.0 PA8500 =head2 Portability Between PA-RISC Versions An executable compiled on a PA-RISC 2.0 platform will not execute on a PA-RISC 1.1 platform, even if they are running the same version of HP-UX. If you are building Perl on a PA-RISC 2.0 platform and want that Perl to also run on a PA-RISC 1.1, the compiler flags +DAportable and +DS32 should be used. It is no longer possible to compile PA-RISC 1.0 executables on either the PA-RISC 1.1 or 2.0 platforms. The command-line flags are accepted, but the resulting executable will not run when transferred to a PA-RISC 1.0 system. =head2 PA-RISC 1.0 The original version of PA-RISC, HP no longer sells any system with this chip. The following systems contained PA-RISC 1.0 chips: 600, 635, 645, 808, 815, 822, 825, 832, 834, 835, 840, 842, 845, 850, 852, 855, 860, 865, 870, 890 =head2 PA-RISC 1.1 An upgrade to the PA-RISC design, it shipped for many years in many different system. The following systems contain with PA-RISC 1.1 chips: 705, 710, 712, 715, 720, 722, 725, 728, 730, 735, 742, 743, 744, 745, 747, 750, 755, 770, 777, 778, 779, 800, 801, 803, 806, 807, 809, 811, 813, 816, 817, 819, 821, 826, 827, 829, 831, 837, 839, 841, 847, 849, 851, 856, 857, 859, 867, 869, 877, 887, 891, 892, 897, A180, A180C, B115, B120, B132L, B132L+, B160L, B180L, C100, C110, C115, C120, C160L, D200, D210, D220, D230, D250, D260, D310, D320, D330, D350, D360, D410, DX0, DX5, DXO, E25, E35, E45, E55, F10, F20, F30, G30, G40, G50, G60, G70, H20, H30, H40, H50, H60, H70, I30, I40, I50, I60, I70, J200, J210, J210XC, K100, K200, K210, K220, K230, K400, K410, K420, S700i, S715, S744, S760, T500, T520 =head2 PA-RISC 2.0 The most recent upgrade to the PA-RISC design, it added support for 64-bit integer data. As of the date of this document's last update, the following systems contain PA-RISC 2.0 chips: 700, 780, 781, 782, 783, 785, 802, 804, 810, 820, 861, 871, 879, 889, 893, 895, 896, 898, 899, A400, A500, B1000, B2000, C130, C140, C160, C180, C180+, C180-XP, C200+, C400+, C3000, C360, C3600, CB260, D270, D280, D370, D380, D390, D650, J220, J2240, J280, J282, J400, J410, J5000, J5500XM, J5600, J7000, J7600, K250, K260, K260-EG, K270, K360, K370, K380, K450, K460, K460-EG, K460-XP, K470, K570, K580, L1000, L2000, L3000, N4000, R380, R390, SD16000, SD32000, SD64000, T540, T600, V2000, V2200, V2250, V2500, V2600 Just before HP took over Compaq, some systems were renamed. the link that contained the explanation is dead, so here's a short summary: HP 9000 A-Class servers, now renamed HP Server rp2400 series. HP 9000 L-Class servers, now renamed HP Server rp5400 series. HP 9000 N-Class servers, now renamed HP Server rp7400. rp2400, rp2405, rp2430, rp2450, rp2470, rp3410, rp3440, rp4410, rp4440, rp5400, rp5405, rp5430, rp5450, rp5470, rp7400, rp7405, rp7410, rp7420, rp7440, rp8400, rp8420, rp8440, Superdome The current naming convention is: aadddd ||||`+- 00 - 99 relative capacity & newness (upgrades, etc.) |||`--- unique number for each architecture to ensure different ||| systems do not have the same numbering across ||| architectures ||`---- 1 - 9 identifies family and/or relative positioning || |`----- c = ia32 (cisc) | p = pa-risc | x = ia-64 (Itanium & Itanium 2) | h = housing `------ t = tower r = rack optimized s = super scalable b = blade sa = appliance =head2 Itanium Processor Family (IPF) and HP-UX HP-UX also runs on the new Itanium processor. This requires the use of a different version of HP-UX (currently 11.23 or 11i v2), and with the exception of a few differences detailed below and in later sections, Perl should compile with no problems. Although PA-RISC binaries can run on Itanium systems, you should not attempt to use a PA-RISC version of Perl on an Itanium system. This is because shared libraries created on an Itanium system cannot be loaded while running a PA-RISC executable. HP Itanium 2 systems are usually refered to with model description "HP Integrity". =head2 Itanium, Itanium 2 & Madison 6 HP also ships servers with the 128-bit Itanium processor(s). The cx26x0 is told to have Madison 6. As of the date of this document's last update, the following systems contain Itanium or Itanium 2 chips (this is likely to be out of date): BL60p, BL860c, BL870c, cx2600, cx2620, rx1600, rx1620, rx2600, rx2600hptc, rx2620, rx2660, rx3600, rx4610, rx4640, rx5670, rx6600, rx7420, rx7620, rx7640, rx8420, rx8620, rx8640, rx9610, sx1000, sx2000 To see all about your machine, type # model ia64 hp server rx2600 # /usr/contrib/bin/machinfo =head2 HP-UX versions Not all architectures (PA = PA-RISC, IPF = Itanium Processor Family) support all versions of HP-UX, here is a short list HP-UX version Kernel Architecture ------------- ------ ------------ 10.20 32 bit PA 11.00 32/64 PA 11.11 11i v1 32/64 PA 11.22 11i v2 64 IPF 11.23 11i v2 64 PA & IPF 11.31 11i v3 64 PA & IPF See for the full list of hardware/OS support and expected end-of-life L<http://www.hp.com/go/hpuxservermatrix> =head2 Building Dynamic Extensions on HP-UX HP-UX supports dynamically loadable libraries (shared libraries). Shared libraries end with the suffix .sl. On Itanium systems, they end with the suffix .so. Shared libraries created on a platform using a particular PA-RISC version are not usable on platforms using an earlier PA-RISC version by default. However, this backwards compatibility may be enabled using the same +DAportable compiler flag (with the same PA-RISC 1.0 caveat mentioned above). Shared libraries created on an Itanium platform cannot be loaded on a PA-RISC platform. Shared libraries created on a PA-RISC platform can only be loaded on an Itanium platform if it is a PA-RISC executable that is attempting to load the PA-RISC library. A PA-RISC shared library cannot be loaded into an Itanium executable nor vice-versa. To create a shared library, the following steps must be performed: 1. Compile source modules with +z or +Z flag to create a .o module which contains Position-Independent Code (PIC). The linker will tell you in the next step if +Z was needed. (For gcc, the appropriate flag is -fpic or -fPIC.) 2. Link the shared library using the -b flag. If the code calls any functions in other system libraries (e.g., libm), it must be included on this line. (Note that these steps are usually handled automatically by the extension's Makefile). If these dependent libraries are not listed at shared library creation time, you will get fatal "Unresolved symbol" errors at run time when the library is loaded. You may create a shared library that refers to another library, which may be either an archive library or a shared library. If this second library is a shared library, this is called a "dependent library". The dependent library's name is recorded in the main shared library, but it is not linked into the shared library. Instead, it is loaded when the main shared library is loaded. This can cause problems if you build an extension on one system and move it to another system where the libraries may not be located in the same place as on the first system. If the referred library is an archive library, then it is treated as a simple collection of .o modules (all of which must contain PIC). These modules are then linked into the shared library. Note that it is okay to create a library which contains a dependent library that is already linked into perl. Some extensions, like DB_File and Compress::Zlib use/require prebuilt libraries for the perl extensions/modules to work. If these libraries are built using the default configuration, it might happen that you run into an error like "invalid loader fixup" during load phase. HP is aware of this problem. Search the HP-UX cxx-dev forums for discussions about the subject. The short answer is that B<everything> (all libraries, everything) must be compiled with C<+z> or C<+Z> to be PIC (position independent code). (For gcc, that would be C<-fpic> or C<-fPIC>). In HP-UX 11.00 or newer the linker error message should tell the name of the offending object file. A more general approach is to intervene manually, as with an example for the DB_File module, which requires SleepyCat's libdb.sl: # cd .../db-3.2.9/build_unix # vi Makefile ... add +Z to all cflags to create shared objects CFLAGS= -c $(CPPFLAGS) +Z -Ae +O2 +Onolimit \ -I/usr/local/include -I/usr/include/X11R6 CXXFLAGS= -c $(CPPFLAGS) +Z -Ae +O2 +Onolimit \ -I/usr/local/include -I/usr/include/X11R6 # make clean # make # mkdir tmp # cd tmp # ar x ../libdb.a # ld -b -o libdb-3.2.sl *.o # mv libdb-3.2.sl /usr/local/lib # rm *.o # cd /usr/local/lib # rm -f libdb.sl # ln -s libdb-3.2.sl libdb.sl # cd .../DB_File-1.76 # make distclean # perl Makefile.PL # make # make test # make install As of db-4.2.x it is no longer needed to do this by hand. Sleepycat has changed the configuration process to add +z on HP-UX automatically. # cd .../db-4.2.25/build_unix # env CFLAGS=+DD64 LDFLAGS=+DD64 ../dist/configure should work to generate 64bit shared libraries for HP-UX 11.00 and 11i. It is no longer possible to link PA-RISC 1.0 shared libraries (even though the command-line flags are still present). PA-RISC and Itanium object files are not interchangeable. Although you may be able to use ar to create an archive library of PA-RISC object files on an Itanium system, you cannot link against it using an Itanium link editor. =head2 The HP ANSI C Compiler When using this compiler to build Perl, you should make sure that the flag -Aa is added to the cpprun and cppstdin variables in the config.sh file (though see the section on 64-bit perl below). If you are using a recent version of the Perl distribution, these flags are set automatically. Even though HP-UX 10.20 and 11.00 are not actively maintained by HP anymore, updates for the HP ANSI C compiler are still available from time to time, and it might be advisable to see if updates are applicable. At the moment of writing, the latests available patches for 11.00 that should be applied are PHSS_35098, PHSS_35175, PHSS_35100, PHSS_33036, and PHSS_33902). If you have a SUM account, you can use it to search for updates/patches. Enter "ANSI" as keyword. =head2 The GNU C Compiler When you are going to use the GNU C compiler (gcc), and you don't have gcc yet, you can either build it yourself from the sources (available from e.g. L<http://gcc.gnu.org/mirrors.html>) or fetch a prebuilt binary from the HP porting center. gcc prebuilds can be fetched from L<http://h21007.www2.hp.com/dspp/tech/tech_TechSoftwareDetailPage_IDX/1,1703,547,00.html> (Browse through the list, because there are often multiple versions of the same package available). Above mentioned distributions are depots. H.Merijn Brand has made prebuilt gcc binaries available on L<http://mirrors.develooper.com/hpux/> and/or L<http://www.cmve.net/~merijn/> for HP-UX 10.20, HP-UX 11.00, HP-UX 11.11 (HP-UX 11i v1), and HP-UX 11.23 (HP-UX 11i v2) in both 32- and 64-bit versions. These are bzipped tar archives that also include recent GNU binutils and GNU gdb. Read the instructions on that page to rebuild gcc using itself. On PA-RISC you need a different compiler for 32-bit applications and for 64-bit applications. On PA-RISC, 32-bit objects and 64-bit objects do not mix. Period. There is no different behaviour for HP C-ANSI-C or GNU gcc. So if you require your perl binary to use 64-bit libraries, like Oracle-64bit, you MUST build a 64-bit perl. Building a 64-bit capable gcc on PA-RISC from source is possible only when you have the HP C-ANSI C compiler or an already working 64-bit binary of gcc available. Best performance for perl is achieved with HP's native compiler. =head2 Using Large Files with Perl on HP-UX Beginning with HP-UX version 10.20, files larger than 2GB (2^31 bytes) may be created and manipulated. Three separate methods of doing this are available. Of these methods, the best method for Perl is to compile using the -Duselargefiles flag to Configure. This causes Perl to be compiled using structures and functions in which these are 64 bits wide, rather than 32 bits wide. (Note that this will only work with HP's ANSI C compiler. If you want to compile Perl using gcc, you will have to get a version of the compiler that supports 64-bit operations. See above for where to find it.) There are some drawbacks to this approach. One is that any extension which calls any file-manipulating C function will need to be recompiled (just follow the usual "perl Makefile.PL; make; make test; make install" procedure). The list of functions that will need to recompiled is: creat, fgetpos, fopen, freopen, fsetpos, fstat, fstatvfs, fstatvfsdev, ftruncate, ftw, lockf, lseek, lstat, mmap, nftw, open, prealloc, stat, statvfs, statvfsdev, tmpfile, truncate, getrlimit, setrlimit Another drawback is only valid for Perl versions before 5.6.0. This drawback is that the seek and tell functions (both the builtin version and POSIX module version) will not perform correctly. It is strongly recommended that you use this flag when you run Configure. If you do not do this, but later answer the question about large files when Configure asks you, you may get a configuration that cannot be compiled, or that does not function as expected. =head2 Threaded Perl on HP-UX It is possible to compile a version of threaded Perl on any version of HP-UX before 10.30, but it is strongly suggested that you be running on HP-UX 11.00 at least. To compile Perl with threads, add -Dusethreads to the arguments of Configure. Verify that the -D_POSIX_C_SOURCE=199506L compiler flag is automatically added to the list of flags. Also make sure that -lpthread is listed before -lc in the list of libraries to link Perl with. The hints provided for HP-UX during Configure will try very hard to get this right for you. HP-UX versions before 10.30 require a separate installation of a POSIX threads library package. Two examples are the HP DCE package, available on "HP-UX Hardware Extensions 3.0, Install and Core OS, Release 10.20, April 1999 (B3920-13941)" or the Freely available PTH package, available on H.Merijn's site (L<http://mirrors.develooper.com/hpux/>). The use of PTH will be unsupported in perl-5.12 and up and is rather buggy in 5.11.x. If you are going to use the HP DCE package, the library used for threading is /usr/lib/libcma.sl, but there have been multiple updates of that library over time. Perl will build with the first version, but it will not pass the test suite. Older Oracle versions might be a compelling reason not to update that library, otherwise please find a newer version in one of the following patches: PHSS_19739, PHSS_20608, or PHSS_23672 reformatted output: d3:/usr/lib 106 > what libcma-*.1 libcma-00000.1: HP DCE/9000 1.5 Module: libcma.sl (Export) Date: Apr 29 1996 22:11:24 libcma-19739.1: HP DCE/9000 1.5 PHSS_19739-40 Module: libcma.sl (Export) Date: Sep 4 1999 01:59:07 libcma-20608.1: HP DCE/9000 1.5 PHSS_20608 Module: libcma.1 (Export) Date: Dec 8 1999 18:41:23 libcma-23672.1: HP DCE/9000 1.5 PHSS_23672 Module: libcma.1 (Export) Date: Apr 9 2001 10:01:06 d3:/usr/lib 107 > If you choose for the PTH package, use swinstall to install pth in the default location (/opt/pth), and then make symbolic links to the libraries from /usr/lib # cd /usr/lib # ln -s /opt/pth/lib/libpth* . For building perl to support Oracle, it needs to be linked with libcl and libpthread. So even if your perl is an unthreaded build, these libraries might be required. See "Oracle on HP-UX" below. =head2 64-bit Perl on HP-UX Beginning with HP-UX 11.00, programs compiled under HP-UX can take advantage of the LP64 programming environment (LP64 means Longs and Pointers are 64 bits wide), in which scalar variables will be able to hold numbers larger than 2^32 with complete precision. Perl has proven to be consistent and reliable in 64bit mode since 5.8.1 on all HP-UX 11.xx. As of the date of this document, Perl is fully 64-bit compliant on HP-UX 11.00 and up for both cc- and gcc builds. If you are about to build a 64-bit perl with GNU gcc, please read the gcc section carefully. Should a user have the need for compiling Perl in the LP64 environment, use the -Duse64bitall flag to Configure. This will force Perl to be compiled in a pure LP64 environment (with the +DD64 flag for HP C-ANSI-C, with no additional options for GNU gcc 64-bit on PA-RISC, and with -mlp64 for GNU gcc on Itanium). If you want to compile Perl using gcc, you will have to get a version of the compiler that supports 64-bit operations.) You can also use the -Duse64bitint flag to Configure. Although there are some minor differences between compiling Perl with this flag versus the -Duse64bitall flag, they should not be noticeable from a Perl user's perspective. When configuring -Duse64bitint using a 64bit gcc on a pa-risc architecture, -Duse64bitint is silently promoted to -Duse64bitall. In both cases, it is strongly recommended that you use these flags when you run Configure. If you do not use do this, but later answer the questions about 64-bit numbers when Configure asks you, you may get a configuration that cannot be compiled, or that does not function as expected. =head2 Oracle on HP-UX Using perl to connect to Oracle databases through DBI and DBD::Oracle has caused a lot of people many headaches. Read README.hpux in the DBD::Oracle for much more information. The reason to mention it here is that Oracle requires a perl built with libcl and libpthread, the latter even when perl is build without threads. Building perl using all defaults, but still enabling to build DBD::Oracle later on can be achieved using Configure -A prepend:libswanted='cl pthread ' ... Do not forget the space before the trailing quote. Also note that this does not (yet) work with all configurations, it is known to fail with 64-bit versions of GCC. =head2 GDBM and Threads on HP-UX If you attempt to compile Perl with (POSIX) threads on an 11.X system and also link in the GDBM library, then Perl will immediately core dump when it starts up. The only workaround at this point is to relink the GDBM library under 11.X, then relink it into Perl. the error might show something like: Pthread internal error: message: __libc_reinit() failed, file: ../pthreads/pthread.c, line: 1096 Return Pointer is 0xc082bf33 sh: 5345 Quit(coredump) and Configure will give up. =head2 NFS filesystems and utime(2) on HP-UX If you are compiling Perl on a remotely-mounted NFS filesystem, the test io/fs.t may fail on test #18. This appears to be a bug in HP-UX and no fix is currently available. =head2 HP-UX Kernel Parameters (maxdsiz) for Compiling Perl By default, HP-UX comes configured with a maximum data segment size of 64MB. This is too small to correctly compile Perl with the maximum optimization levels. You can increase the size of the maxdsiz kernel parameter through the use of SAM. When using the GUI version of SAM, click on the Kernel Configuration icon, then the Configurable Parameters icon. Scroll down and select the maxdsiz line. From the Actions menu, select the Modify Configurable Parameter item. Insert the new formula into the Formula/Value box. Then follow the instructions to rebuild your kernel and reboot your system. In general, a value of 256MB (or "256*1024*1024") is sufficient for Perl to compile at maximum optimization. =head1 nss_delete core dump from op/pwent or op/grent You may get a bus error core dump from the op/pwent or op/grent tests. If compiled with -g you will see a stack trace much like the following: #0 0xc004216c in () from /usr/lib/libc.2 #1 0xc00d7550 in __nss_src_state_destr () from /usr/lib/libc.2 #2 0xc00d7768 in __nss_src_state_destr () from /usr/lib/libc.2 #3 0xc00d78a8 in nss_delete () from /usr/lib/libc.2 #4 0xc01126d8 in endpwent () from /usr/lib/libc.2 #5 0xd1950 in Perl_pp_epwent () from ./perl #6 0x94d3c in Perl_runops_standard () from ./perl #7 0x23728 in S_run_body () from ./perl #8 0x23428 in perl_run () from ./perl #9 0x2005c in main () from ./perl The key here is the C<nss_delete> call. One workaround for this bug seems to be to create add to the file F</etc/nsswitch.conf> (at least) the following lines group: files passwd: files Whether you are using NIS does not matter. Amazingly enough, the same bug also affects Solaris. =head1 error: pasting ")" and "l" does not give a valid preprocessing token There seems to be a broken system header file in HP-UX 11.00 that breaks perl building in 32bit mode with GNU gcc-4.x causing this error. The same file for HP-UX 11.11 (even though the file is older) does not show this failure, and has the correct definition, so the best fix is to patch the header to match: --- /usr/include/inttypes.h 2001-04-20 18:42:14 +0200 +++ /usr/include/inttypes.h 2000-11-14 09:00:00 +0200 @@ -72,7 +72,7 @@ #define UINT32_C(__c) __CONCAT_U__(__c) #else /* __LP64 */ #define INT32_C(__c) __CONCAT__(__c,l) -#define UINT32_C(__c) __CONCAT__(__CONCAT_U__(__c),l) +#define UINT32_C(__c) __CONCAT__(__c,ul) #endif /* __LP64 */ #define INT64_C(__c) __CONCAT_L__(__c,l) =head1 Miscellaneous HP-UX 11 Y2K patch "Y2K-1100 B.11.00.B0125 HP-UX Core OS Year 2000 Patch Bundle" has been reported to break the io/fs test #18 which tests whether utime() can change timestamps. The Y2K patch seems to break utime() so that over NFS the timestamps do not get changed (on local filesystems utime() still works). This has probably been fixed on your system by now. =head1 AUTHOR H.Merijn Brand <h.m.brand@xs4all.nl> Jeff Okamoto <okamoto@corp.hp.com> With much assistance regarding shared libraries from Marc Sabatella. =cut PK PU�\�њN�b �b perl588delta.podnu �[��� =encoding utf8 =head1 NAME perl588delta - what is new for perl v5.8.8 =head1 DESCRIPTION This document describes differences between the 5.8.7 release and the 5.8.8 release. =head1 Incompatible Changes There are no changes intentionally incompatible with 5.8.7. If any exist, they are bugs and reports are welcome. =head1 Core Enhancements =over =item * C<chdir>, C<chmod> and C<chown> can now work on filehandles as well as filenames, if the system supports respectively C<fchdir>, C<fchmod> and C<fchown>, thanks to a patch provided by Gisle Aas. =back =head1 Modules and Pragmata =over =item * C<Attribute::Handlers> upgraded to version 0.78_02 =over =item * Documentation typo fix =back =item * C<attrs> upgraded to version 1.02 =over =item * Internal cleanup only =back =item * C<autouse> upgraded to version 1.05 =over =item * Simplified implementation =back =item * C<B> upgraded to version 1.09_01 =over =item * The inheritance hierarchy of the C<B::> modules has been corrected; C<B::NV> now inherits from C<B::SV> (instead of C<B::IV>). =back =item * C<blib> upgraded to version 1.03 =over =item * Documentation typo fix =back =item * C<ByteLoader> upgraded to version 0.06 =over =item * Internal cleanup =back =item * C<CGI> upgraded to version 3.15 =over =item * Extraneous "?" from C<self_url()> removed =item * C<scrolling_list()> select attribute fixed =item * C<virtual_port> now works properly with the https protocol =item * C<upload_hook()> and C<append()> now works in function-oriented mode =item * C<POST_MAX> doesn't cause the client to hang any more =item * Automatic tab indexes are now disabled and new C<-tabindex> pragma has been added to turn automatic indexes back on =item * C<end_form()> doesn't emit empty (and non-validating) C<< <div> >> =item * C<CGI::Carp> works better in certain mod_perl configurations =item * Setting C<$CGI::TMPDIRECTORY> is now effective =item * Enhanced documentation =back =item * C<charnames> upgraded to version 1.05 =over =item * C<viacode()> now accept hex strings and has been optimized. =back =item * C<CPAN> upgraded to version 1.76_02 =over =item * 1 minor bug fix for Win32 =back =item * C<Cwd> upgraded to version 3.12 =over =item * C<canonpath()> on Win32 now collapses F<foo\..> sections correctly. =item * Improved behaviour on Symbian OS. =item * Enhanced documentation and typo fixes =item * Internal cleanup =back =item * C<Data::Dumper> upgraded to version 2.121_08 =over =item * A problem where C<Data::Dumper> would sometimes update the iterator state of hashes has been fixed =item * Numeric labels now work =item * Internal cleanup =back =item * C<DB> upgraded to version 1.01 =over =item * A problem where the state of the regexp engine would sometimes get clobbered when running under the debugger has been fixed. =back =item * C<DB_File> upgraded to version 1.814 =over =item * Adds support for Berkeley DB 4.4. =back =item * C<Devel::DProf> upgraded to version 20050603.00 =over =item * Internal cleanup =back =item * C<Devel::Peek> upgraded to version 1.03 =over =item * Internal cleanup =back =item * C<Devel::PPPort> upgraded to version 3.06_01 =over =item * C<--compat-version> argument checking has been improved =item * Files passed on the command line are filtered by default =item * C<--nofilter> option to override the filtering has been added =item * Enhanced documentation =back =item * C<diagnostics> upgraded to version 1.15 =over =item * Documentation typo fix =back =item * C<Digest> upgraded to version 1.14 =over =item * The constructor now knows which module implements SHA-224 =item * Documentation tweaks and typo fixes =back =item * C<Digest::MD5> upgraded to version 2.36 =over =item * C<XSLoader> is now used for faster loading =item * Enhanced documentation including MD5 weaknesses discovered lately =back =item * C<Dumpvalue> upgraded to version 1.12 =over =item * Documentation fix =back =item * C<DynaLoader> upgraded but unfortunately we're not able to increment its version number :-( =over =item * Implements C<dl_unload_file> on Win32 =item * Internal cleanup =item * C<XSLoader> 0.06 incorporated; small optimisation for calling C<bootstrap_inherit()> and documentation enhancements. =back =item * C<Encode> upgraded to version 2.12 =over =item * A coderef is now acceptable for C<CHECK>! =item * 3 new characters added to the ISO-8859-7 encoding =item * New encoding C<MIME-Header-ISO_2022_JP> added =item * Problem with partial characters and C<< encoding(utf-8-strict) >> fixed. =item * Documentation enhancements and typo fixes =back =item * C<English> upgraded to version 1.02 =over =item * the C<< $COMPILING >> variable has been added =back =item * C<ExtUtils::Constant> upgraded to version 0.17 =over =item * Improved compatibility with older versions of perl =back =item * C<ExtUtils::MakeMaker> upgraded to version 6.30 (was 6.17) =over =item * Too much to list here; see L<http://search.cpan.org/dist/ExtUtils-MakeMaker/Changes> =back =item * C<File::Basename> upgraded to version 2.74, with changes contributed by Michael Schwern. =over =item * Documentation clarified and errors corrected. =item * C<basename> now strips trailing path separators before processing the name. =item * C<basename> now returns C</> for parameter C</>, to make C<basename> consistent with the shell utility of the same name. =item * The suffix is no longer stripped if it is identical to the remaining characters in the name, again for consistency with the shell utility. =item * Some internal code cleanup. =back =item * C<File::Copy> upgraded to version 2.09 =over =item * Copying a file onto itself used to fail. =item * Moving a file between file systems now preserves the access and modification time stamps =back =item * C<File::Find> upgraded to version 1.10 =over =item * Win32 portability fixes =item * Enhanced documentation =back =item * C<File::Glob> upgraded to version 1.05 =over =item * Internal cleanup =back =item * C<File::Path> upgraded to version 1.08 =over =item * C<mkpath> now preserves C<errno> when C<mkdir> fails =back =item * C<File::Spec> upgraded to version 3.12 =over =item * C<File::Spec->rootdir()> now returns C<\> on Win32, instead of C</> =item * C<$^O> could sometimes become tainted. This has been fixed. =item * C<canonpath> on Win32 now collapses C<foo/..> (or C<foo\..>) sections correctly, rather than doing the "misguided" work it was previously doing. Note that C<canonpath> on Unix still does B<not> collapse these sections, as doing so would be incorrect. =item * Some documentation improvements =item * Some internal code cleanup =back =item * C<FileCache> upgraded to version 1.06 =over =item * POD formatting errors in the documentation fixed =back =item * C<Filter::Simple> upgraded to version 0.82 =item * C<FindBin> upgraded to version 1.47 =over =item * Now works better with directories where access rights are more restrictive than usual. =back =item * C<GDBM_File> upgraded to version 1.08 =over =item * Internal cleanup =back =item * C<Getopt::Long> upgraded to version 2.35 =over =item * C<prefix_pattern> has now been complemented by a new configuration option C<long_prefix_pattern> that allows the user to specify what prefix patterns should have long option style semantics applied. =item * Options can now take multiple values at once (experimental) =item * Various bug fixes =back =item * C<if> upgraded to version 0.05 =over =item * Give more meaningful error messages from C<if> when invoked with a condition in list context. =item * Restore backwards compatibility with earlier versions of perl =back =item * C<IO> upgraded to version 1.22 =over =item * Enhanced documentation =item * Internal cleanup =back =item * C<IPC::Open2> upgraded to version 1.02 =over =item * Enhanced documentation =back =item * C<IPC::Open3> upgraded to version 1.02 =over =item * Enhanced documentation =back =item * C<List::Util> upgraded to version 1.18 (was 1.14) =over =item * Fix pure-perl version of C<refaddr> to avoid blessing an un-blessed reference =item * Use C<XSLoader> for faster loading =item * Fixed various memory leaks =item * Internal cleanup and portability fixes =back =item * C<Math::Complex> upgraded to version 1.35 =over =item * C<atan2(0, i)> now works, as do all the (computable) complex argument cases =item * Fixes for certain bugs in C<make> and C<emake> =item * Support returning the I<k>th root directly =item * Support C<[2,-3pi/8]> in C<emake> =item * Support C<inf> for C<make>/C<emake> =item * Document C<make>/C<emake> more visibly =back =item * C<Math::Trig> upgraded to version 1.03 =over =item * Add more great circle routines: C<great_circle_waypoint> and C<great_circle_destination> =back =item * C<MIME::Base64> upgraded to version 3.07 =over =item * Use C<XSLoader> for faster loading =item * Enhanced documentation =item * Internal cleanup =back =item * C<NDBM_File> upgraded to version 1.06 =over =item * Enhanced documentation =back =item * C<ODBM_File> upgraded to version 1.06 =over =item * Documentation typo fixed =item * Internal cleanup =back =item * C<Opcode> upgraded to version 1.06 =over =item * Enhanced documentation =item * Internal cleanup =back =item * C<open> upgraded to version 1.05 =over =item * Enhanced documentation =back =item * C<overload> upgraded to version 1.04 =over =item * Enhanced documentation =back =item * C<PerlIO> upgraded to version 1.04 =over =item * C<PerlIO::via> iterate over layers properly now =item * C<PerlIO::scalar> understands C<< $/ = "" >> now =item * C<encoding(utf-8-strict)> with partial characters now works =item * Enhanced documentation =item * Internal cleanup =back =item * C<Pod::Functions> upgraded to version 1.03 =over =item * Documentation typos fixed =back =item * C<Pod::Html> upgraded to version 1.0504 =over =item * HTML output will now correctly link to C<=item>s on the same page, and should be valid XHTML. =item * Variable names are recognized as intended =item * Documentation typos fixed =back =item * C<Pod::Parser> upgraded to version 1.32 =over =item * Allow files that start with C<=head> on the first line =item * Win32 portability fix =item * Exit status of C<pod2usage> fixed =item * New C<-noperldoc> switch for C<pod2usage> =item * Arbitrary URL schemes now allowed =item * Documentation typos fixed =back =item * C<POSIX> upgraded to version 1.09 =over =item * Documentation typos fixed =item * Internal cleanup =back =item * C<re> upgraded to version 0.05 =over =item * Documentation typo fixed =back =item * C<Safe> upgraded to version 2.12 =over =item * Minor documentation enhancement =back =item * C<SDBM_File> upgraded to version 1.05 =over =item * Documentation typo fixed =item * Internal cleanup =back =item * C<Socket> upgraded to version 1.78 =over =item * Internal cleanup =back =item * C<Storable> upgraded to version 2.15 =over =item * This includes the C<STORABLE_attach> hook functionality added by Adam Kennedy, and more frugal memory requirements when storing under C<ithreads>, by using the C<ithreads> cloning tracking code. =back =item * C<Switch> upgraded to version 2.10_01 =over =item * Documentation typos fixed =back =item * C<Sys::Syslog> upgraded to version 0.13 =over =item * Now provides numeric macros and meaningful C<Exporter> tags. =item * No longer uses C<Sys::Hostname> as it may provide useless values in unconfigured network environments, so instead uses C<INADDR_LOOPBACK> directly. =item * C<syslog()> now uses local timestamp. =item * C<setlogmask()> now behaves like its C counterpart. =item * C<setlogsock()> will now C<croak()> as documented. =item * Improved error and warnings messages. =item * Improved documentation. =back =item * C<Term::ANSIColor> upgraded to version 1.10 =over =item * Fixes a bug in C<colored> when C<$EACHLINE> is set that caused it to not color lines consisting solely of 0 (literal zero). =item * Improved tests. =back =item * C<Term::ReadLine> upgraded to version 1.02 =over =item * Documentation tweaks =back =item * C<Test::Harness> upgraded to version 2.56 (was 2.48) =over =item * The C<Test::Harness> timer is now off by default. =item * Now shows elapsed time in milliseconds. =item * Various bug fixes =back =item * C<Test::Simple> upgraded to version 0.62 (was 0.54) =over =item * C<is_deeply()> no longer fails to work for many cases =item * Various minor bug fixes =item * Documentation enhancements =back =item * C<Text::Tabs> upgraded to version 2005.0824 =over =item * Provides a faster implementation of C<expand> =back =item * C<Text::Wrap> upgraded to version 2005.082401 =over =item * Adds C<$Text::Wrap::separator2>, which allows you to preserve existing newlines but add line-breaks with some other string. =back =item * C<threads> upgraded to version 1.07 =over =item * C<threads> will now honour C<no warnings 'threads'> =item * A thread's interpreter is now freed after C<< $t->join() >> rather than after C<undef $t>, which should fix some C<ithreads> memory leaks. (Fixed by Dave Mitchell) =item * Some documentation typo fixes. =back =item * C<threads::shared> upgraded to version 0.94 =over =item * Documentation changes only =item * Note: An improved implementation of C<threads::shared> is available on CPAN - this will be merged into 5.8.9 if it proves stable. =back =item * C<Tie::Hash> upgraded to version 1.02 =over =item * Documentation typo fixed =back =item * C<Time::HiRes> upgraded to version 1.86 (was 1.66) =over =item * C<clock_nanosleep()> and C<clock()> functions added =item * Support for the POSIX C<clock_gettime()> and C<clock_getres()> has been added =item * Return C<undef> or an empty list if the C C<gettimeofday()> function fails =item * Improved C<nanosleep> detection =item * Internal cleanup =item * Enhanced documentation =back =item * C<Unicode::Collate> upgraded to version 0.52 =over =item * Now implements UCA Revision 14 (based on Unicode 4.1.0). =item * C<Unicode::Collate->new> method no longer overwrites user's C<$_> =item * Enhanced documentation =back =item * C<Unicode::UCD> upgraded to version 0.24 =over =item * Documentation typos fixed =back =item * C<User::grent> upgraded to version 1.01 =over =item * Documentation typo fixed =back =item * C<utf8> upgraded to version 1.06 =over =item * Documentation typos fixed =back =item * C<vmsish> upgraded to version 1.02 =over =item * Documentation typos fixed =back =item * C<warnings> upgraded to version 1.05 =over =item * Gentler messing with C<Carp::> internals =item * Internal cleanup =item * Documentation update =back =item * C<Win32> upgraded to version 0.2601 =for cynics And how many perl 5.8.x versions can I release ahead of Vista? =over =item * Provides Windows Vista support to C<Win32::GetOSName> =item * Documentation enhancements =back =item * C<XS::Typemap> upgraded to version 0.02 =over =item * Internal cleanup =back =back =head1 Utility Changes =head2 C<h2xs> enhancements C<h2xs> implements new option C<--use-xsloader> to force use of C<XSLoader> even in backwards compatible modules. The handling of authors' names that had apostrophes has been fixed. Any enums with negative values are now skipped. =head2 C<perlivp> enhancements C<perlivp> implements new option C<-a> and will not check for F<*.ph> files by default any more. Use the C<-a> option to run I<all> tests. =head1 New Documentation The L<perlglossary> manpage is a glossary of terms used in the Perl documentation, technical and otherwise, kindly provided by O'Reilly Media, inc. =head1 Performance Enhancements =over 4 =item * Weak reference creation is now I<O(1)> rather than I<O(n)>, courtesy of Nicholas Clark. Weak reference deletion remains I<O(n)>, but if deletion only happens at program exit, it may be skipped completely. =item * Salvador Fandiño provided improvements to reduce the memory usage of C<sort> and to speed up some cases. =item * Jarkko Hietaniemi and Andy Lester worked to mark as much data as possible in the C source files as C<static>, to increase the proportion of the executable file that the operating system can share between process, and thus reduce real memory usage on multi-user systems. =back =head1 Installation and Configuration Improvements Parallel makes should work properly now, although there may still be problems if C<make test> is instructed to run in parallel. Building with Borland's compilers on Win32 should work more smoothly. In particular Steve Hay has worked to side step many warnings emitted by their compilers and at least one C compiler internal error. C<Configure> will now detect C<clearenv> and C<unsetenv>, thanks to a patch from Alan Burlison. It will also probe for C<futimes> and whether C<sprintf> correctly returns the length of the formatted string, which will both be used in perl 5.8.9. There are improved hints for next-3.0, vmesa, IX, Darwin, Solaris, Linux, DEC/OSF, HP-UX and MPE/iX Perl extensions on Windows now can be statically built into the Perl DLL, thanks to a work by Vadim Konovalov. (This improvement was actually in 5.8.7, but was accidentally omitted from L<perl587delta>). =head1 Selected Bug Fixes =head2 no warnings 'category' works correctly with -w Previously when running with warnings enabled globally via C<-w>, selective disabling of specific warning categories would actually turn off all warnings. This is now fixed; now C<no warnings 'io';> will only turn off warnings in the C<io> class. Previously it would erroneously turn off all warnings. This bug fix may cause some programs to start correctly issuing warnings. =head2 Remove over-optimisation Perl 5.8.4 introduced a change so that assignments of C<undef> to a scalar, or of an empty list to an array or a hash, were optimised away. As this could cause problems when C<goto> jumps were involved, this change has been backed out. =head2 sprintf() fixes Using the sprintf() function with some formats could lead to a buffer overflow in some specific cases. This has been fixed, along with several other bugs, notably in bounds checking. In related fixes, it was possible for badly written code that did not follow the documentation of C<Sys::Syslog> to have formatting vulnerabilities. C<Sys::Syslog> has been changed to protect people from poor quality third party code. =head2 Debugger and Unicode slowdown It had been reported that running under perl's debugger when processing Unicode data could cause unexpectedly large slowdowns. The most likely cause of this was identified and fixed by Nicholas Clark. =head2 Smaller fixes =over 4 =item * C<FindBin> now works better with directories where access rights are more restrictive than usual. =item * Several memory leaks in ithreads were closed. An improved implementation of C<threads::shared> is available on CPAN - this will be merged into 5.8.9 if it proves stable. =item * Trailing spaces are now trimmed from C<$!> and C<$^E>. =item * Operations that require perl to read a process's list of groups, such as reads of C<$(> and C<$)>, now dynamically allocate memory rather than using a fixed sized array. The fixed size array could cause C stack exhaustion on systems configured to use large numbers of groups. =item * C<PerlIO::scalar> now works better with non-default C<$/> settings. =item * You can now use the C<x> operator to repeat a C<qw//> list. This used to raise a syntax error. =item * The debugger now traces correctly execution in eval("")uated code that contains #line directives. =item * The value of the C<open> pragma is no longer ignored for three-argument opens. =item * The optimisation of C<for (reverse @a)> introduced in perl 5.8.6 could misbehave when the array had undefined elements and was used in LVALUE context. Dave Mitchell provided a fix. =item * Some case insensitive matches between UTF-8 encoded data and 8 bit regexps, and vice versa, could give malformed character warnings. These have been fixed by Dave Mitchell and Yves Orton. =item * C<lcfirst> and C<ucfirst> could corrupt the string for certain cases where the length UTF-8 encoding of the string in lower case, upper case or title case differed. This was fixed by Nicholas Clark. =item * Perl will now use the C library calls C<unsetenv> and C<clearenv> if present to delete keys from C<%ENV> and delete C<%ENV> entirely, thanks to a patch from Alan Burlison. =back =head1 New or Changed Diagnostics =head2 Attempt to set length of freed array This is a new warning, produced in situations such as this: $r = do {my @a; \$#a}; $$r = 503; =head2 Non-string passed as bitmask This is a new warning, produced when number has been passed as a argument to select(), instead of a bitmask. # Wrong, will now warn $rin = fileno(STDIN); ($nfound,$timeleft) = select($rout=$rin, undef, undef, $timeout); # Should be $rin = ''; vec($rin,fileno(STDIN),1) = 1; ($nfound,$timeleft) = select($rout=$rin, undef, undef, $timeout); =head2 Search pattern not terminated or ternary operator parsed as search pattern This syntax error indicates that the lexer couldn't find the final delimiter of a C<?PATTERN?> construct. Mentioning the ternary operator in this error message makes it easier to diagnose syntax errors. =head1 Changed Internals There has been a fair amount of refactoring of the C<C> source code, partly to make it tidier and more maintainable. The resulting object code and the C<perl> binary may well be smaller than 5.8.7, in particular due to a change contributed by Dave Mitchell which reworked the warnings code to be significantly smaller. Apart from being smaller and possibly faster, there should be no user-detectable changes. Andy Lester supplied many improvements to determine which function parameters and local variables could actually be declared C<const> to the C compiler. Steve Peters provided new C<*_set> macros and reworked the core to use these rather than assigning to macros in LVALUE context. Dave Mitchell improved the lexer debugging output under C<-DT> Nicholas Clark changed the string buffer allocation so that it is now rounded up to the next multiple of 4 (or 8 on platforms with 64 bit pointers). This should reduce the number of calls to C<realloc> without actually using any extra memory. The C<HV>'s array of C<HE*>s is now allocated at the correct (minimal) size, thanks to another change by Nicholas Clark. Compile with C<-DPERL_USE_LARGE_HV_ALLOC> to use the old, sloppier, default. For XS or embedding debugging purposes, if perl is compiled with C<-DDEBUG_LEAKING_SCALARS_FORK_DUMP> in addition to C<-DDEBUG_LEAKING_SCALARS> then a child process is C<fork>ed just before global destruction, which is used to display the values of any scalars found to have leaked at the end of global destruction. Without this, the scalars have already been freed sufficiently at the point of detection that it is impossible to produce any meaningful dump of their contents. This feature was implemented by the indefatigable Nicholas Clark, based on an idea by Mike Giroux. =head1 Platform Specific Problems The optimiser on HP-UX 11.23 (Itanium 2) is currently partly disabled (scaled down to +O1) when using HP C-ANSI-C; the cause of problems at higher optimisation levels is still unclear. There are a handful of remaining test failures on VMS, mostly due to test fixes and minor module tweaks with too many dependencies to integrate into this release from the development stream, where they have all been corrected. The following is a list of expected failures with the patch number of the fix where that is known: ext/Devel/PPPort/t/ppphtest.t #26913 ext/List/Util/t/p_tainted.t #26912 lib/ExtUtils/t/PL_FILES.t #26813 lib/ExtUtils/t/basic.t #26813 t/io/fs.t t/op/cmp.t =head1 Reporting Bugs If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup and the perl bug database at http://bugs.perl.org. There may also be information at http://www.perl.org, the Perl Home Page. If you believe you have an unreported bug, please run the B<perlbug> program included with your release. Be sure to trim your bug down to a tiny but sufficient test case. Your bug report, along with the output of C<perl -V>, will be sent off to perlbug@perl.org to be analysed by the Perl porting team. You can browse and search the Perl 5 bugs at http://bugs.perl.org/ =head1 SEE ALSO The F<Changes> file for exhaustive details on what changed. The F<INSTALL> file for how to build Perl. The F<README> file for general stuff. The F<Artistic> and F<Copying> files for copyright information. =cut PK PU�\�W� � perlmacos.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see pod/perlpod.pod) which is specially designed to be readable as is. =head1 NAME perlmacos - Perl under Mac OS (Classic) =head1 SYNOPSIS For Mac OS X see README.macosx Perl under Mac OS Classic has not been supported since before Perl 5.10 (April 2004). When we say "Mac OS" below, we mean Mac OS 7, 8, and 9, and I<not> Mac OS X. =head1 DESCRIPTION The port of Perl to to Mac OS was officially removed as of Perl 5.12, though the last official production release of MacPerl corresponded to Perl 5.6. While Perl 5.10 included the port to Mac OS, ExtUtils::MakeMaker, a core part of Perl's module installation infrastructure officially dropped support for Mac OS in April 2004. =head1 AUTHOR Perl was ported to Mac OS by Matthias Neeracher E<lt>neeracher@mac.comE<gt>. Chris Nandor E<lt>pudge@pobox.comE<gt> continued development and maintenance for the duration of the port's life. PK PU�\.�m Yc Yc perldsc.podnu �[��� =head1 NAME X<data structure> X<complex data structure> X<struct> perldsc - Perl Data Structures Cookbook =head1 DESCRIPTION The single feature most sorely lacking in the Perl programming language prior to its 5.0 release was complex data structures. Even without direct language support, some valiant programmers did manage to emulate them, but it was hard work and not for the faint of heart. You could occasionally get away with the C<$m{$AoA,$b}> notation borrowed from B<awk> in which the keys are actually more like a single concatenated string C<"$AoA$b">, but traversal and sorting were difficult. More desperate programmers even hacked Perl's internal symbol table directly, a strategy that proved hard to develop and maintain--to put it mildly. The 5.0 release of Perl let us have complex data structures. You may now write something like this and all of a sudden, you'd have an array with three dimensions! for $x (1 .. 10) { for $y (1 .. 10) { for $z (1 .. 10) { $AoA[$x][$y][$z] = $x ** $y + $z; } } } Alas, however simple this may appear, underneath it's a much more elaborate construct than meets the eye! How do you print it out? Why can't you say just C<print @AoA>? How do you sort it? How can you pass it to a function or get one of these back from a function? Is it an object? Can you save it to disk to read back later? How do you access whole rows or columns of that matrix? Do all the values have to be numeric? As you see, it's quite easy to become confused. While some small portion of the blame for this can be attributed to the reference-based implementation, it's really more due to a lack of existing documentation with examples designed for the beginner. This document is meant to be a detailed but understandable treatment of the many different sorts of data structures you might want to develop. It should also serve as a cookbook of examples. That way, when you need to create one of these complex data structures, you can just pinch, pilfer, or purloin a drop-in example from here. Let's look at each of these possible constructs in detail. There are separate sections on each of the following: =over 5 =item * arrays of arrays =item * hashes of arrays =item * arrays of hashes =item * hashes of hashes =item * more elaborate constructs =back But for now, let's look at general issues common to all these types of data structures. =head1 REFERENCES X<reference> X<dereference> X<dereferencing> X<pointer> The most important thing to understand about all data structures in Perl--including multidimensional arrays--is that even though they might appear otherwise, Perl C<@ARRAY>s and C<%HASH>es are all internally one-dimensional. They can hold only scalar values (meaning a string, number, or a reference). They cannot directly contain other arrays or hashes, but instead contain I<references> to other arrays or hashes. X<multidimensional array> X<array, multidimensional> You can't use a reference to an array or hash in quite the same way that you would a real array or hash. For C or C++ programmers unused to distinguishing between arrays and pointers to the same, this can be confusing. If so, just think of it as the difference between a structure and a pointer to a structure. You can (and should) read more about references in L<perlref>. Briefly, references are rather like pointers that know what they point to. (Objects are also a kind of reference, but we won't be needing them right away--if ever.) This means that when you have something which looks to you like an access to a two-or-more-dimensional array and/or hash, what's really going on is that the base type is merely a one-dimensional entity that contains references to the next level. It's just that you can I<use> it as though it were a two-dimensional one. This is actually the way almost all C multidimensional arrays work as well. $array[7][12] # array of arrays $array[7]{string} # array of hashes $hash{string}[7] # hash of arrays $hash{string}{'another string'} # hash of hashes Now, because the top level contains only references, if you try to print out your array in with a simple print() function, you'll get something that doesn't look very nice, like this: @AoA = ( [2, 3], [4, 5, 7], [0] ); print $AoA[1][2]; 7 print @AoA; ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0) That's because Perl doesn't (ever) implicitly dereference your variables. If you want to get at the thing a reference is referring to, then you have to do this yourself using either prefix typing indicators, like C<${$blah}>, C<@{$blah}>, C<@{$blah[$i]}>, or else postfix pointer arrows, like C<$a-E<gt>[3]>, C<$h-E<gt>{fred}>, or even C<$ob-E<gt>method()-E<gt>[3]>. =head1 COMMON MISTAKES The two most common mistakes made in constructing something like an array of arrays is either accidentally counting the number of elements or else taking a reference to the same memory location repeatedly. Here's the case where you just get the count instead of a nested array: for $i (1..10) { @array = somefunc($i); $AoA[$i] = @array; # WRONG! } That's just the simple case of assigning an array to a scalar and getting its element count. If that's what you really and truly want, then you might do well to consider being a tad more explicit about it, like this: for $i (1..10) { @array = somefunc($i); $counts[$i] = scalar @array; } Here's the case of taking a reference to the same memory location again and again: for $i (1..10) { @array = somefunc($i); $AoA[$i] = \@array; # WRONG! } So, what's the big problem with that? It looks right, doesn't it? After all, I just told you that you need an array of references, so by golly, you've made me one! Unfortunately, while this is true, it's still broken. All the references in @AoA refer to the I<very same place>, and they will therefore all hold whatever was last in @array! It's similar to the problem demonstrated in the following C program: #include <pwd.h> main() { struct passwd *getpwnam(), *rp, *dp; rp = getpwnam("root"); dp = getpwnam("daemon"); printf("daemon name is %s\nroot name is %s\n", dp->pw_name, rp->pw_name); } Which will print daemon name is daemon root name is daemon The problem is that both C<rp> and C<dp> are pointers to the same location in memory! In C, you'd have to remember to malloc() yourself some new memory. In Perl, you'll want to use the array constructor C<[]> or the hash constructor C<{}> instead. Here's the right way to do the preceding broken code fragments: X<[]> X<{}> for $i (1..10) { @array = somefunc($i); $AoA[$i] = [ @array ]; } The square brackets make a reference to a new array with a I<copy> of what's in @array at the time of the assignment. This is what you want. Note that this will produce something similar, but it's much harder to read: for $i (1..10) { @array = 0 .. $i; @{$AoA[$i]} = @array; } Is it the same? Well, maybe so--and maybe not. The subtle difference is that when you assign something in square brackets, you know for sure it's always a brand new reference with a new I<copy> of the data. Something else could be going on in this new case with the C<@{$AoA[$i]}> dereference on the left-hand-side of the assignment. It all depends on whether C<$AoA[$i]> had been undefined to start with, or whether it already contained a reference. If you had already populated @AoA with references, as in $AoA[3] = \@another_array; Then the assignment with the indirection on the left-hand-side would use the existing reference that was already there: @{$AoA[3]} = @array; Of course, this I<would> have the "interesting" effect of clobbering @another_array. (Have you ever noticed how when a programmer says something is "interesting", that rather than meaning "intriguing", they're disturbingly more apt to mean that it's "annoying", "difficult", or both? :-) So just remember always to use the array or hash constructors with C<[]> or C<{}>, and you'll be fine, although it's not always optimally efficient. Surprisingly, the following dangerous-looking construct will actually work out fine: for $i (1..10) { my @array = somefunc($i); $AoA[$i] = \@array; } That's because my() is more of a run-time statement than it is a compile-time declaration I<per se>. This means that the my() variable is remade afresh each time through the loop. So even though it I<looks> as though you stored the same variable reference each time, you actually did not! This is a subtle distinction that can produce more efficient code at the risk of misleading all but the most experienced of programmers. So I usually advise against teaching it to beginners. In fact, except for passing arguments to functions, I seldom like to see the gimme-a-reference operator (backslash) used much at all in code. Instead, I advise beginners that they (and most of the rest of us) should try to use the much more easily understood constructors C<[]> and C<{}> instead of relying upon lexical (or dynamic) scoping and hidden reference-counting to do the right thing behind the scenes. In summary: $AoA[$i] = [ @array ]; # usually best $AoA[$i] = \@array; # perilous; just how my() was that array? @{ $AoA[$i] } = @array; # way too tricky for most programmers =head1 CAVEAT ON PRECEDENCE X<dereference, precedence> X<dereferencing, precedence> Speaking of things like C<@{$AoA[$i]}>, the following are actually the same thing: X<< -> >> $aref->[2][2] # clear $$aref[2][2] # confusing That's because Perl's precedence rules on its five prefix dereferencers (which look like someone swearing: C<$ @ * % &>) make them bind more tightly than the postfix subscripting brackets or braces! This will no doubt come as a great shock to the C or C++ programmer, who is quite accustomed to using C<*a[i]> to mean what's pointed to by the I<i'th> element of C<a>. That is, they first take the subscript, and only then dereference the thing at that subscript. That's fine in C, but this isn't C. The seemingly equivalent construct in Perl, C<$$aref[$i]> first does the deref of $aref, making it take $aref as a reference to an array, and then dereference that, and finally tell you the I<i'th> value of the array pointed to by $AoA. If you wanted the C notion, you'd have to write C<${$AoA[$i]}> to force the C<$AoA[$i]> to get evaluated first before the leading C<$> dereferencer. =head1 WHY YOU SHOULD ALWAYS C<use strict> If this is starting to sound scarier than it's worth, relax. Perl has some features to help you avoid its most common pitfalls. The best way to avoid getting confused is to start every program like this: #!/usr/bin/perl -w use strict; This way, you'll be forced to declare all your variables with my() and also disallow accidental "symbolic dereferencing". Therefore if you'd done this: my $aref = [ [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "homer", "bart", "marge", "maggie", ], [ "george", "jane", "elroy", "judy", ], ]; print $aref[2][2]; The compiler would immediately flag that as an error I<at compile time>, because you were accidentally accessing C<@aref>, an undeclared variable, and it would thereby remind you to write instead: print $aref->[2][2] =head1 DEBUGGING X<data structure, debugging> X<complex data structure, debugging> X<AoA, debugging> X<HoA, debugging> X<AoH, debugging> X<HoH, debugging> X<array of arrays, debugging> X<hash of arrays, debugging> X<array of hashes, debugging> X<hash of hashes, debugging> Before version 5.002, the standard Perl debugger didn't do a very nice job of printing out complex data structures. With 5.002 or above, the debugger includes several new features, including command line editing as well as the C<x> command to dump out complex data structures. For example, given the assignment to $AoA above, here's the debugger output: DB<1> x $AoA $AoA = ARRAY(0x13b5a0) 0 ARRAY(0x1f0a24) 0 'fred' 1 'barney' 2 'pebbles' 3 'bambam' 4 'dino' 1 ARRAY(0x13b558) 0 'homer' 1 'bart' 2 'marge' 3 'maggie' 2 ARRAY(0x13b540) 0 'george' 1 'jane' 2 'elroy' 3 'judy' =head1 CODE EXAMPLES Presented with little comment (these will get their own manpages someday) here are short code examples illustrating access of various types of data structures. =head1 ARRAYS OF ARRAYS X<array of arrays> X<AoA> =head2 Declaration of an ARRAY OF ARRAYS @AoA = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], ); =head2 Generation of an ARRAY OF ARRAYS # reading from file while ( <> ) { push @AoA, [ split ]; } # calling a function for $i ( 1 .. 10 ) { $AoA[$i] = [ somefunc($i) ]; } # using temp vars for $i ( 1 .. 10 ) { @tmp = somefunc($i); $AoA[$i] = [ @tmp ]; } # add to an existing row push @{ $AoA[0] }, "wilma", "betty"; =head2 Access and Printing of an ARRAY OF ARRAYS # one element $AoA[0][0] = "Fred"; # another element $AoA[1][1] =~ s/(\w)/\u$1/; # print the whole thing with refs for $aref ( @AoA ) { print "\t [ @$aref ],\n"; } # print the whole thing with indices for $i ( 0 .. $#AoA ) { print "\t [ @{$AoA[$i]} ],\n"; } # print the whole thing one at a time for $i ( 0 .. $#AoA ) { for $j ( 0 .. $#{ $AoA[$i] } ) { print "elt $i $j is $AoA[$i][$j]\n"; } } =head1 HASHES OF ARRAYS X<hash of arrays> X<HoA> =head2 Declaration of a HASH OF ARRAYS %HoA = ( flintstones => [ "fred", "barney" ], jetsons => [ "george", "jane", "elroy" ], simpsons => [ "homer", "marge", "bart" ], ); =head2 Generation of a HASH OF ARRAYS # reading from file # flintstones: fred barney wilma dino while ( <> ) { next unless s/^(.*?):\s*//; $HoA{$1} = [ split ]; } # reading from file; more temps # flintstones: fred barney wilma dino while ( $line = <> ) { ($who, $rest) = split /:\s*/, $line, 2; @fields = split ' ', $rest; $HoA{$who} = [ @fields ]; } # calling a function that returns a list for $group ( "simpsons", "jetsons", "flintstones" ) { $HoA{$group} = [ get_family($group) ]; } # likewise, but using temps for $group ( "simpsons", "jetsons", "flintstones" ) { @members = get_family($group); $HoA{$group} = [ @members ]; } # append new members to an existing family push @{ $HoA{"flintstones"} }, "wilma", "betty"; =head2 Access and Printing of a HASH OF ARRAYS # one element $HoA{flintstones}[0] = "Fred"; # another element $HoA{simpsons}[1] =~ s/(\w)/\u$1/; # print the whole thing foreach $family ( keys %HoA ) { print "$family: @{ $HoA{$family} }\n" } # print the whole thing with indices foreach $family ( keys %HoA ) { print "family: "; foreach $i ( 0 .. $#{ $HoA{$family} } ) { print " $i = $HoA{$family}[$i]"; } print "\n"; } # print the whole thing sorted by number of members foreach $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) { print "$family: @{ $HoA{$family} }\n" } # print the whole thing sorted by number of members and name foreach $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} || $a cmp $b } keys %HoA ) { print "$family: ", join(", ", sort @{ $HoA{$family} }), "\n"; } =head1 ARRAYS OF HASHES X<array of hashes> X<AoH> =head2 Declaration of an ARRAY OF HASHES @AoH = ( { Lead => "fred", Friend => "barney", }, { Lead => "george", Wife => "jane", Son => "elroy", }, { Lead => "homer", Wife => "marge", Son => "bart", } ); =head2 Generation of an ARRAY OF HASHES # reading from file # format: LEAD=fred FRIEND=barney while ( <> ) { $rec = {}; for $field ( split ) { ($key, $value) = split /=/, $field; $rec->{$key} = $value; } push @AoH, $rec; } # reading from file # format: LEAD=fred FRIEND=barney # no temp while ( <> ) { push @AoH, { split /[\s+=]/ }; } # calling a function that returns a key/value pair list, like # "lead","fred","daughter","pebbles" while ( %fields = getnextpairset() ) { push @AoH, { %fields }; } # likewise, but using no temp vars while (<>) { push @AoH, { parsepairs($_) }; } # add key/value to an element $AoH[0]{pet} = "dino"; $AoH[2]{pet} = "santa's little helper"; =head2 Access and Printing of an ARRAY OF HASHES # one element $AoH[0]{lead} = "fred"; # another element $AoH[1]{lead} =~ s/(\w)/\u$1/; # print the whole thing with refs for $href ( @AoH ) { print "{ "; for $role ( keys %$href ) { print "$role=$href->{$role} "; } print "}\n"; } # print the whole thing with indices for $i ( 0 .. $#AoH ) { print "$i is { "; for $role ( keys %{ $AoH[$i] } ) { print "$role=$AoH[$i]{$role} "; } print "}\n"; } # print the whole thing one at a time for $i ( 0 .. $#AoH ) { for $role ( keys %{ $AoH[$i] } ) { print "elt $i $role is $AoH[$i]{$role}\n"; } } =head1 HASHES OF HASHES X<hash of hashes> X<HoH> =head2 Declaration of a HASH OF HASHES %HoH = ( flintstones => { lead => "fred", pal => "barney", }, jetsons => { lead => "george", wife => "jane", "his boy" => "elroy", }, simpsons => { lead => "homer", wife => "marge", kid => "bart", }, ); =head2 Generation of a HASH OF HASHES # reading from file # flintstones: lead=fred pal=barney wife=wilma pet=dino while ( <> ) { next unless s/^(.*?):\s*//; $who = $1; for $field ( split ) { ($key, $value) = split /=/, $field; $HoH{$who}{$key} = $value; } # reading from file; more temps while ( <> ) { next unless s/^(.*?):\s*//; $who = $1; $rec = {}; $HoH{$who} = $rec; for $field ( split ) { ($key, $value) = split /=/, $field; $rec->{$key} = $value; } } # calling a function that returns a key,value hash for $group ( "simpsons", "jetsons", "flintstones" ) { $HoH{$group} = { get_family($group) }; } # likewise, but using temps for $group ( "simpsons", "jetsons", "flintstones" ) { %members = get_family($group); $HoH{$group} = { %members }; } # append new members to an existing family %new_folks = ( wife => "wilma", pet => "dino", ); for $what (keys %new_folks) { $HoH{flintstones}{$what} = $new_folks{$what}; } =head2 Access and Printing of a HASH OF HASHES # one element $HoH{flintstones}{wife} = "wilma"; # another element $HoH{simpsons}{lead} =~ s/(\w)/\u$1/; # print the whole thing foreach $family ( keys %HoH ) { print "$family: { "; for $role ( keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; } # print the whole thing somewhat sorted foreach $family ( sort keys %HoH ) { print "$family: { "; for $role ( sort keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; } # print the whole thing sorted by number of members foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$a}} } keys %HoH ) { print "$family: { "; for $role ( sort keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; } # establish a sort order (rank) for each role $i = 0; for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i } # now print the whole thing sorted by number of members foreach $family ( sort { keys %{ $HoH{$b} } <=> keys %{ $HoH{$a} } } keys %HoH ) { print "$family: { "; # and print these according to rank order for $role ( sort { $rank{$a} <=> $rank{$b} } keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; } =head1 MORE ELABORATE RECORDS X<record> X<structure> X<struct> =head2 Declaration of MORE ELABORATE RECORDS Here's a sample showing how to create and use a record whose fields are of many different sorts: $rec = { TEXT => $string, SEQUENCE => [ @old_values ], LOOKUP => { %some_table }, THATCODE => \&some_function, THISCODE => sub { $_[0] ** $_[1] }, HANDLE => \*STDOUT, }; print $rec->{TEXT}; print $rec->{SEQUENCE}[0]; $last = pop @ { $rec->{SEQUENCE} }; print $rec->{LOOKUP}{"key"}; ($first_k, $first_v) = each %{ $rec->{LOOKUP} }; $answer = $rec->{THATCODE}->($arg); $answer = $rec->{THISCODE}->($arg1, $arg2); # careful of extra block braces on fh ref print { $rec->{HANDLE} } "a string\n"; use FileHandle; $rec->{HANDLE}->autoflush(1); $rec->{HANDLE}->print(" a string\n"); =head2 Declaration of a HASH OF COMPLEX RECORDS %TV = ( flintstones => { series => "flintstones", nights => [ qw(monday thursday friday) ], members => [ { name => "fred", role => "lead", age => 36, }, { name => "wilma", role => "wife", age => 31, }, { name => "pebbles", role => "kid", age => 4, }, ], }, jetsons => { series => "jetsons", nights => [ qw(wednesday saturday) ], members => [ { name => "george", role => "lead", age => 41, }, { name => "jane", role => "wife", age => 39, }, { name => "elroy", role => "kid", age => 9, }, ], }, simpsons => { series => "simpsons", nights => [ qw(monday) ], members => [ { name => "homer", role => "lead", age => 34, }, { name => "marge", role => "wife", age => 37, }, { name => "bart", role => "kid", age => 11, }, ], }, ); =head2 Generation of a HASH OF COMPLEX RECORDS # reading from file # this is most easily done by having the file itself be # in the raw data format as shown above. perl is happy # to parse complex data structures if declared as data, so # sometimes it's easiest to do that # here's a piece by piece build up $rec = {}; $rec->{series} = "flintstones"; $rec->{nights} = [ find_days() ]; @members = (); # assume this file in field=value syntax while (<>) { %fields = split /[\s=]+/; push @members, { %fields }; } $rec->{members} = [ @members ]; # now remember the whole thing $TV{ $rec->{series} } = $rec; ########################################################### # now, you might want to make interesting extra fields that # include pointers back into the same data structure so if # change one piece, it changes everywhere, like for example # if you wanted a {kids} field that was a reference # to an array of the kids' records without having duplicate # records and thus update problems. ########################################################### foreach $family (keys %TV) { $rec = $TV{$family}; # temp pointer @kids = (); for $person ( @{ $rec->{members} } ) { if ($person->{role} =~ /kid|son|daughter/) { push @kids, $person; } } # REMEMBER: $rec and $TV{$family} point to same data!! $rec->{kids} = [ @kids ]; } # you copied the array, but the array itself contains pointers # to uncopied objects. this means that if you make bart get # older via $TV{simpsons}{kids}[0]{age}++; # then this would also change in print $TV{simpsons}{members}[2]{age}; # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2] # both point to the same underlying anonymous hash table # print the whole thing foreach $family ( keys %TV ) { print "the $family"; print " is on during @{ $TV{$family}{nights} }\n"; print "its members are:\n"; for $who ( @{ $TV{$family}{members} } ) { print " $who->{name} ($who->{role}), age $who->{age}\n"; } print "it turns out that $TV{$family}{lead} has "; print scalar ( @{ $TV{$family}{kids} } ), " kids named "; print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } ); print "\n"; } =head1 Database Ties You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file. The first problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you also have problems with how references are to be represented on disk. One experimental module that does partially attempt to address this need is the MLDBM module. Check your nearest CPAN site as described in L<perlmodlib> for source code to MLDBM. =head1 SEE ALSO L<perlref>, L<perllol>, L<perldata>, L<perlobj> =head1 AUTHOR Tom Christiansen <F<tchrist@perl.com>> Last update: Wed Oct 23 04:57:50 MET DST 1996 PK PU�\W>�.o� o� perl5101delta.podnu �[��� =head1 NAME perl5101delta - what is new for perl v5.10.1 =head1 DESCRIPTION This document describes differences between the 5.10.0 release and the 5.10.1 release. If you are upgrading from an earlier release such as 5.8.8, first read the L<perl5100delta>, which describes differences between 5.8.8 and 5.10.0 =head1 Incompatible Changes =head2 Switch statement changes The handling of complex expressions by the C<given>/C<when> switch statement has been enhanced. There are two new cases where C<when> now interprets its argument as a boolean, instead of an expression to be used in a smart match: =over 4 =item flip-flop operators The C<..> and C<...> flip-flop operators are now evaluated in boolean context, following their usual semantics; see L<perlop/"Range Operators">. Note that, as in perl 5.10.0, C<when (1..10)> will not work to test whether a given value is an integer between 1 and 10; you should use C<when ([1..10])> instead (note the array reference). However, contrary to 5.10.0, evaluating the flip-flop operators in boolean context ensures it can now be useful in a C<when()>, notably for implementing bistable conditions, like in: when (/^=begin/ .. /^=end/) { # do something } =item defined-or operator A compound expression involving the defined-or operator, as in C<when (expr1 // expr2)>, will be treated as boolean if the first expression is boolean. (This just extends the existing rule that applies to the regular or operator, as in C<when (expr1 || expr2)>.) =back The next section details more changes brought to the semantics to the smart match operator, that naturally also modify the behaviour of the switch statements where smart matching is implicitly used. =head2 Smart match changes =head3 Changes to type-based dispatch The smart match operator C<~~> is no longer commutative. The behaviour of a smart match now depends primarily on the type of its right hand argument. Moreover, its semantics have been adjusted for greater consistency or usefulness in several cases. While the general backwards compatibility is maintained, several changes must be noted: =over 4 =item * Code references with an empty prototype are no longer treated specially. They are passed an argument like the other code references (even if they choose to ignore it). =item * C<%hash ~~ sub {}> and C<@array ~~ sub {}> now test that the subroutine returns a true value for each key of the hash (or element of the array), instead of passing the whole hash or array as a reference to the subroutine. =item * Due to the commutativity breakage, code references are no longer treated specially when appearing on the left of the C<~~> operator, but like any vulgar scalar. =item * C<undef ~~ %hash> is always false (since C<undef> can't be a key in a hash). No implicit conversion to C<""> is done (as was the case in perl 5.10.0). =item * C<$scalar ~~ @array> now always distributes the smart match across the elements of the array. It's true if one element in @array verifies C<$scalar ~~ $element>. This is a generalization of the old behaviour that tested whether the array contained the scalar. =back The full dispatch table for the smart match operator is given in L<perlsyn/"Smart matching in detail">. =head3 Smart match and overloading According to the rule of dispatch based on the rightmost argument type, when an object overloading C<~~> appears on the right side of the operator, the overload routine will always be called (with a 3rd argument set to a true value, see L<overload>.) However, when the object will appear on the left, the overload routine will be called only when the rightmost argument is a simple scalar. This way distributivity of smart match across arrays is not broken, as well as the other behaviours with complex types (coderefs, hashes, regexes). Thus, writers of overloading routines for smart match mostly need to worry only with comparing against a scalar, and possibly with stringification overloading; the other common cases will be automatically handled consistently. C<~~> will now refuse to work on objects that do not overload it (in order to avoid relying on the object's underlying structure). (However, if the object overloads the stringification or the numification operators, and if overload fallback is active, it will be used instead, as usual.) =head2 Other incompatible changes =over 4 =item * The semantics of C<use feature :5.10*> have changed slightly. See L<"Modules and Pragmata"> for more information. =item * It is now a run-time error to use the smart match operator C<~~> with an object that has no overload defined for it. (This way C<~~> will not break encapsulation by matching against the object's internal representation as a reference.) =item * The version control system used for the development of the perl interpreter has been switched from Perforce to git. This is mainly an internal issue that only affects people actively working on the perl core; but it may have minor external visibility, for example in some of details of the output of C<perl -V>. See L<perlrepository> for more information. =item * The internal structure of the C<ext/> directory in the perl source has been reorganised. In general, a module C<Foo::Bar> whose source was stored under F<ext/Foo/Bar/> is now located under F<ext/Foo-Bar/>. Also, some modules have been moved from F<lib/> to F<ext/>. This is purely a source tarball change, and should make no difference to the compilation or installation of perl, unless you have a very customised build process that explicitly relies on this structure, or which hard-codes the C<nonxs_ext> F<Configure> parameter. Specifically, this change does not by default alter the location of any files in the final installation. =item * As part of the C<Test::Harness> 2.x to 3.x upgrade, the experimental C<Test::Harness::Straps> module has been removed. See L</"Updated Modules"> for more details. =item * As part of the C<ExtUtils::MakeMaker> upgrade, the C<ExtUtils::MakeMaker::bytes> and C<ExtUtils::MakeMaker::vmsish> modules have been removed from this distribution. =item * C<Module::CoreList> no longer contains the C<%:patchlevel> hash. =item * This one is actually a change introduced in 5.10.0, but it was missed from that release's perldelta, so it is mentioned here instead. A bugfix related to the handling of the C</m> modifier and C<qr> resulted in a change of behaviour between 5.8.x and 5.10.0: # matches in 5.8.x, doesn't match in 5.10.0 $re = qr/^bar/; "foo\nbar" =~ /$re/m; =back =head1 Core Enhancements =head2 Unicode Character Database 5.1.0 The copy of the Unicode Character Database included in Perl 5.10.1 has been updated to 5.1.0 from 5.0.0. See L<http://www.unicode.org/versions/Unicode5.1.0/#Notable_Changes> for the notable changes. =head2 A proper interface for pluggable Method Resolution Orders As of Perl 5.10.1 there is a new interface for plugging and using method resolution orders other than the default (linear depth first search). The C3 method resolution order added in 5.10.0 has been re-implemented as a plugin, without changing its Perl-space interface. See L<perlmroapi> for more information. =head2 The C<overloading> pragma This pragma allows you to lexically disable or enable overloading for some or all operations. (Yuval Kogman) =head2 Parallel tests The core distribution can now run its regression tests in parallel on Unix-like platforms. Instead of running C<make test>, set C<TEST_JOBS> in your environment to the number of tests to run in parallel, and run C<make test_harness>. On a Bourne-like shell, this can be done as TEST_JOBS=3 make test_harness # Run 3 tests in parallel An environment variable is used, rather than parallel make itself, because L<TAP::Harness> needs to be able to schedule individual non-conflicting test scripts itself, and there is no standard interface to C<make> utilities to interact with their job schedulers. Note that currently some test scripts may fail when run in parallel (most notably C<ext/IO/t/io_dir.t>). If necessary run just the failing scripts again sequentially and see if the failures go away. =head2 DTrace support Some support for DTrace has been added. See "DTrace support" in F<INSTALL>. =head2 Support for C<configure_requires> in CPAN module metadata Both C<CPAN> and C<CPANPLUS> now support the C<configure_requires> keyword in the C<META.yml> metadata file included in most recent CPAN distributions. This allows distribution authors to specify configuration prerequisites that must be installed before running F<Makefile.PL> or F<Build.PL>. See the documentation for C<ExtUtils::MakeMaker> or C<Module::Build> for more on how to specify C<configure_requires> when creating a distribution for CPAN. =head1 Modules and Pragmata =head2 New Modules and Pragmata =over 4 =item C<autodie> This is a new lexically-scoped alternative for the C<Fatal> module. The bundled version is 2.06_01. Note that in this release, using a string eval when C<autodie> is in effect can cause the autodie behaviour to leak into the surrounding scope. See L<autodie/"BUGS"> for more details. =item C<Compress::Raw::Bzip2> This has been added to the core (version 2.020). =item C<parent> This pragma establishes an ISA relationship with base classes at compile time. It provides the key feature of C<base> without the feature creep. =item C<Parse::CPAN::Meta> This has been added to the core (version 1.39). =back =head2 Pragmata Changes =over 4 =item C<attributes> Upgraded from version 0.08 to 0.09. =item C<attrs> Upgraded from version 1.02 to 1.03. =item C<base> Upgraded from version 2.13 to 2.14. See L<parent> for a replacement. =item C<bigint> Upgraded from version 0.22 to 0.23. =item C<bignum> Upgraded from version 0.22 to 0.23. =item C<bigrat> Upgraded from version 0.22 to 0.23. =item C<charnames> Upgraded from version 1.06 to 1.07. The Unicode F<NameAliases.txt> database file has been added. This has the effect of adding some extra C<\N> character names that formerly wouldn't have been recognised; for example, C<"\N{LATIN CAPITAL LETTER GHA}">. =item C<constant> Upgraded from version 1.13 to 1.17. =item C<feature> The meaning of the C<:5.10> and C<:5.10.X> feature bundles has changed slightly. The last component, if any (i.e. C<X>) is simply ignored. This is predicated on the assumption that new features will not, in general, be added to maintenance releases. So C<:5.10> and C<:5.10.X> have identical effect. This is a change to the behaviour documented for 5.10.0. =item C<fields> Upgraded from version 2.13 to 2.14 (this was just a version bump; there were no functional changes). =item C<lib> Upgraded from version 0.5565 to 0.62. =item C<open> Upgraded from version 1.06 to 1.07. =item C<overload> Upgraded from version 1.06 to 1.07. =item C<overloading> See L</"The C<overloading> pragma"> above. =item C<version> Upgraded from version 0.74 to 0.77. =back =head2 Updated Modules =over 4 =item C<Archive::Extract> Upgraded from version 0.24 to 0.34. =item C<Archive::Tar> Upgraded from version 1.38 to 1.52. =item C<Attribute::Handlers> Upgraded from version 0.79 to 0.85. =item C<AutoLoader> Upgraded from version 5.63 to 5.68. =item C<AutoSplit> Upgraded from version 1.05 to 1.06. =item C<B> Upgraded from version 1.17 to 1.22. =item C<B::Debug> Upgraded from version 1.05 to 1.11. =item C<B::Deparse> Upgraded from version 0.83 to 0.89. =item C<B::Lint> Upgraded from version 1.09 to 1.11. =item C<B::Xref> Upgraded from version 1.01 to 1.02. =item C<Benchmark> Upgraded from version 1.10 to 1.11. =item C<Carp> Upgraded from version 1.08 to 1.11. =item C<CGI> Upgraded from version 3.29 to 3.43. (also includes the "default_value for popup_menu()" fix from 3.45). =item C<Compress::Zlib> Upgraded from version 2.008 to 2.020. =item C<CPAN> Upgraded from version 1.9205 to 1.9402. C<CPAN::FTP> has a local fix to stop it being too verbose on download failure. =item C<CPANPLUS> Upgraded from version 0.84 to 0.88. =item C<CPANPLUS::Dist::Build> Upgraded from version 0.06_02 to 0.36. =item C<Cwd> Upgraded from version 3.25_01 to 3.30. =item C<Data::Dumper> Upgraded from version 2.121_14 to 2.124. =item C<DB> Upgraded from version 1.01 to 1.02. =item C<DB_File> Upgraded from version 1.816_1 to 1.820. =item C<Devel::PPPort> Upgraded from version 3.13 to 3.19. =item C<Digest::MD5> Upgraded from version 2.36_01 to 2.39. =item C<Digest::SHA> Upgraded from version 5.45 to 5.47. =item C<DirHandle> Upgraded from version 1.01 to 1.03. =item C<Dumpvalue> Upgraded from version 1.12 to 1.13. =item C<DynaLoader> Upgraded from version 1.08 to 1.10. =item C<Encode> Upgraded from version 2.23 to 2.35. =item C<Errno> Upgraded from version 1.10 to 1.11. =item C<Exporter> Upgraded from version 5.62 to 5.63. =item C<ExtUtils::CBuilder> Upgraded from version 0.21 to 0.2602. =item C<ExtUtils::Command> Upgraded from version 1.13 to 1.16. =item C<ExtUtils::Constant> Upgraded from 0.20 to 0.22. (Note that neither of these versions are available on CPAN.) =item C<ExtUtils::Embed> Upgraded from version 1.27 to 1.28. =item C<ExtUtils::Install> Upgraded from version 1.44 to 1.54. =item C<ExtUtils::MakeMaker> Upgraded from version 6.42 to 6.55_02. Note that C<ExtUtils::MakeMaker::bytes> and C<ExtUtils::MakeMaker::vmsish> have been removed from this distribution. =item C<ExtUtils::Manifest> Upgraded from version 1.51_01 to 1.56. =item C<ExtUtils::ParseXS> Upgraded from version 2.18_02 to 2.2002. =item C<Fatal> Upgraded from version 1.05 to 2.06_01. See also the new pragma C<autodie>. =item C<File::Basename> Upgraded from version 2.76 to 2.77. =item C<File::Compare> Upgraded from version 1.1005 to 1.1006. =item C<File::Copy> Upgraded from version 2.11 to 2.14. =item C<File::Fetch> Upgraded from version 0.14 to 0.20. =item C<File::Find> Upgraded from version 1.12 to 1.14. =item C<File::Path> Upgraded from version 2.04 to 2.07_03. =item C<File::Spec> Upgraded from version 3.2501 to 3.30. =item C<File::stat> Upgraded from version 1.00 to 1.01. =item C<File::Temp> Upgraded from version 0.18 to 0.22. =item C<FileCache> Upgraded from version 1.07 to 1.08. =item C<FileHandle> Upgraded from version 2.01 to 2.02. =item C<Filter::Simple> Upgraded from version 0.82 to 0.84. =item C<Filter::Util::Call> Upgraded from version 1.07 to 1.08. =item C<FindBin> Upgraded from version 1.49 to 1.50. =item C<GDBM_File> Upgraded from version 1.08 to 1.09. =item C<Getopt::Long> Upgraded from version 2.37 to 2.38. =item C<Hash::Util::FieldHash> Upgraded from version 1.03 to 1.04. This fixes a memory leak. =item C<I18N::Collate> Upgraded from version 1.00 to 1.01. =item C<IO> Upgraded from version 1.23_01 to 1.25. This makes non-blocking mode work on Windows in C<IO::Socket::INET> [CPAN #43573]. =item C<IO::Compress::*> Upgraded from version 2.008 to 2.020. =item C<IO::Dir> Upgraded from version 1.06 to 1.07. =item C<IO::Handle> Upgraded from version 1.27 to 1.28. =item C<IO::Socket> Upgraded from version 1.30_01 to 1.31. =item C<IO::Zlib> Upgraded from version 1.07 to 1.09. =item C<IPC::Cmd> Upgraded from version 0.40_1 to 0.46. =item C<IPC::Open3> Upgraded from version 1.02 to 1.04. =item C<IPC::SysV> Upgraded from version 1.05 to 2.01. =item C<lib> Upgraded from version 0.5565 to 0.62. =item C<List::Util> Upgraded from version 1.19 to 1.21. =item C<Locale::MakeText> Upgraded from version 1.12 to 1.13. =item C<Log::Message> Upgraded from version 0.01 to 0.02. =item C<Math::BigFloat> Upgraded from version 1.59 to 1.60. =item C<Math::BigInt> Upgraded from version 1.88 to 1.89. =item C<Math::BigInt::FastCalc> Upgraded from version 0.16 to 0.19. =item C<Math::BigRat> Upgraded from version 0.21 to 0.22. =item C<Math::Complex> Upgraded from version 1.37 to 1.56. =item C<Math::Trig> Upgraded from version 1.04 to 1.20. =item C<Memoize> Upgraded from version 1.01_02 to 1.01_03 (just a minor documentation change). =item C<Module::Build> Upgraded from version 0.2808_01 to 0.34_02. =item C<Module::CoreList> Upgraded from version 2.13 to 2.18. This release no longer contains the C<%Module::CoreList::patchlevel> hash. =item C<Module::Load> Upgraded from version 0.12 to 0.16. =item C<Module::Load::Conditional> Upgraded from version 0.22 to 0.30. =item C<Module::Loaded> Upgraded from version 0.01 to 0.02. =item C<Module::Pluggable> Upgraded from version 3.6 to 3.9. =item C<NDBM_File> Upgraded from version 1.07 to 1.08. =item C<Net::Ping> Upgraded from version 2.33 to 2.36. =item C<NEXT> Upgraded from version 0.60_01 to 0.64. =item C<Object::Accessor> Upgraded from version 0.32 to 0.34. =item C<OS2::REXX> Upgraded from version 1.03 to 1.04. =item C<Package::Constants> Upgraded from version 0.01 to 0.02. =item C<PerlIO> Upgraded from version 1.04 to 1.06. =item C<PerlIO::via> Upgraded from version 0.04 to 0.07. =item C<Pod::Man> Upgraded from version 2.16 to 2.22. =item C<Pod::Parser> Upgraded from version 1.35 to 1.37. =item C<Pod::Simple> Upgraded from version 3.05 to 3.07. =item C<Pod::Text> Upgraded from version 3.08 to 3.13. =item C<POSIX> Upgraded from version 1.13 to 1.17. =item C<Safe> Upgraded from 2.12 to 2.18. =item C<Scalar::Util> Upgraded from version 1.19 to 1.21. =item C<SelectSaver> Upgraded from 1.01 to 1.02. =item C<SelfLoader> Upgraded from 1.11 to 1.17. =item C<Socket> Upgraded from 1.80 to 1.82. =item C<Storable> Upgraded from 2.18 to 2.20. =item C<Switch> Upgraded from version 2.13 to 2.14. Please see L</Deprecations>. =item C<Symbol> Upgraded from version 1.06 to 1.07. =item C<Sys::Syslog> Upgraded from version 0.22 to 0.27. =item C<Term::ANSIColor> Upgraded from version 1.12 to 2.00. =item C<Term::ReadLine> Upgraded from version 1.03 to 1.04. =item C<Term::UI> Upgraded from version 0.18 to 0.20. =item C<Test::Harness> Upgraded from version 2.64 to 3.17. Note that one side-effect of the 2.x to 3.x upgrade is that the experimental C<Test::Harness::Straps> module (and its supporting C<Assert>, C<Iterator>, C<Point> and C<Results> modules) have been removed. If you still need this, then they are available in the (unmaintained) C<Test-Harness-Straps> distribution on CPAN. =item C<Test::Simple> Upgraded from version 0.72 to 0.92. =item C<Text::ParseWords> Upgraded from version 3.26 to 3.27. =item C<Text::Tabs> Upgraded from version 2007.1117 to 2009.0305. =item C<Text::Wrap> Upgraded from version 2006.1117 to 2009.0305. =item C<Thread::Queue> Upgraded from version 2.00 to 2.11. =item C<Thread::Semaphore> Upgraded from version 2.01 to 2.09. =item C<threads> Upgraded from version 1.67 to 1.72. =item C<threads::shared> Upgraded from version 1.14 to 1.29. =item C<Tie::RefHash> Upgraded from version 1.37 to 1.38. =item C<Tie::StdHandle> This has documentation changes, and has been assigned a version for the first time: version 4.2. =item C<Time::HiRes> Upgraded from version 1.9711 to 1.9719. =item C<Time::Local> Upgraded from version 1.18 to 1.1901. =item C<Time::Piece> Upgraded from version 1.12 to 1.15. =item C<Unicode::Normalize> Upgraded from version 1.02 to 1.03. =item C<Unicode::UCD> Upgraded from version 0.25 to 0.27. C<charinfo()> now works on Unified CJK code points added to later versions of Unicode. C<casefold()> has new fields returned to provide both a simpler interface and previously missing information. The old fields are retained for backwards compatibility. Information about Turkic-specific code points is now returned. The documentation has been corrected and expanded. =item C<UNIVERSAL> Upgraded from version 1.04 to 1.05. =item C<Win32> Upgraded from version 0.34 to 0.39. =item C<Win32API::File> Upgraded from version 0.1001_01 to 0.1101. =item C<XSLoader> Upgraded from version 0.08 to 0.10. =back =head1 Utility Changes =over 4 =item F<h2ph> Now looks in C<include-fixed> too, which is a recent addition to gcc's search path. =item F<h2xs> No longer incorrectly treats enum values like macros (Daniel Burr). Now handles C++ style constants (C<//>) properly in enums. (A patch from Rainer Weikusat was used; Daniel Burr also proposed a similar fix). =item F<perl5db.pl> C<LVALUE> subroutines now work under the debugger. The debugger now correctly handles proxy constant subroutines, and subroutine stubs. =item F<perlthanks> Perl 5.10.1 adds a new utility F<perlthanks>, which is a variant of F<perlbug>, but for sending non-bug-reports to the authors and maintainers of Perl. Getting nothing but bug reports can become a bit demoralising: we'll see if this changes things. =back =head1 New Documentation =over 4 =item L<perlhaiku> This contains instructions on how to build perl for the Haiku platform. =item L<perlmroapi> This describes the new interface for pluggable Method Resolution Orders. =item L<perlperf> This document, by Richard Foley, provides an introduction to the use of performance and optimization techniques which can be used with particular reference to perl programs. =item L<perlrepository> This describes how to access the perl source using the I<git> version control system. =item L<perlthanks> This describes the new F<perlthanks> utility. =back =head1 Changes to Existing Documentation The various large C<Changes*> files (which listed every change made to perl over the last 18 years) have been removed, and replaced by a small file, also called C<Changes>, which just explains how that same information may be extracted from the git version control system. The file F<Porting/patching.pod> has been deleted, as it mainly described interacting with the old Perforce-based repository, which is now obsolete. Information still relevant has been moved to L<perlrepository>. L<perlapi>, L<perlintern>, L<perlmodlib> and L<perltoc> are now all generated at build time, rather than being shipped as part of the release. =head1 Performance Enhancements =over 4 =item * A new internal cache means that C<isa()> will often be faster. =item * Under C<use locale>, the locale-relevant information is now cached on read-only values, such as the list returned by C<keys %hash>. This makes operations such as C<sort keys %hash> in the scope of C<use locale> much faster. =item * Empty C<DESTROY> methods are no longer called. =back =head1 Installation and Configuration Improvements =head2 F<ext/> reorganisation The layout of directories in F<ext> has been revised. Specifically, all extensions are now flat, and at the top level, with C</> in pathnames replaced by C<->, so that F<ext/Data/Dumper/> is now F<ext/Data-Dumper/>, etc. The names of the extensions as specified to F<Configure>, and as reported by C<%Config::Config> under the keys C<dynamic_ext>, C<known_extensions>, C<nonxs_ext> and C<static_ext> have not changed, and still use C</>. Hence this change will not have any affect once perl is installed. However, C<Attribute::Handlers>, C<Safe> and C<mro> have now become extensions in their own right, so if you run F<Configure> with options to specify an exact list of extensions to build, you will need to change it to account for this. For 5.10.2, it is planned that many dual-life modules will have been moved from F<lib> to F<ext>; again this will have no effect on an installed perl, but will matter if you invoke F<Configure> with a pre-canned list of extensions to build. =head2 Configuration improvements If C<vendorlib> and C<vendorarch> are the same, then they are only added to C<@INC> once. C<$Config{usedevel}> and the C-level C<PERL_USE_DEVEL> are now defined if perl is built with C<-Dusedevel>. F<Configure> will enable use of C<-fstack-protector>, to provide protection against stack-smashing attacks, if the compiler supports it. F<Configure> will now determine the correct prototypes for re-entrant functions, and for C<gconvert>, if you are using a C++ compiler rather than a C compiler. On Unix, if you build from a tree containing a git repository, the configuration process will note the commit hash you have checked out, for display in the output of C<perl -v> and C<perl -V>. Unpushed local commits are automatically added to the list of local patches displayed by C<perl -V>. =head2 Compilation improvements As part of the flattening of F<ext>, all extensions on all platforms are built by F<make_ext.pl>. This replaces the Unix-specific F<ext/util/make_ext>, VMS-specific F<make_ext.com> and Win32-specific F<win32/buildext.pl>. =head2 Platform Specific Changes =over 4 =item AIX Removed F<libbsd> for AIX 5L and 6.1. Only flock() was used from F<libbsd>. Removed F<libgdbm> for AIX 5L and 6.1. The F<libgdbm> is delivered as an optional package with the AIX Toolbox. Unfortunately the 64 bit version is broken. Hints changes mean that AIX 4.2 should work again. =item Cygwin On Cygwin we now strip the last number from the DLL. This has been the behaviour in the cygwin.com build for years. The hints files have been updated. =item FreeBSD The hints files now identify the correct threading libraries on FreeBSD 7 and later. =item Irix We now work around a bizarre preprocessor bug in the Irix 6.5 compiler: C<cc -E -> unfortunately goes into K&R mode, but C<cc -E file.c> doesn't. =item Haiku Patches from the Haiku maintainers have been merged in. Perl should now build on Haiku. =item MirOS BSD Perl should now build on MirOS BSD. =item NetBSD Hints now supports versions 5.*. =item Stratus VOS Various changes from Stratus have been merged in. =item Symbian There is now support for Symbian S60 3.2 SDK and S60 5.0 SDK. =item Win32 Improved message window handling means that C<alarm> and C<kill> messages will no longer be dropped under race conditions. =item VMS Reads from the in-memory temporary files of C<PerlIO::scalar> used to fail if C<$/> was set to a numeric reference (to indicate record-style reads). This is now fixed. VMS now supports C<getgrgid>. Many improvements and cleanups have been made to the VMS file name handling and conversion code. Enabling the C<PERL_VMS_POSIX_EXIT> logical name now encodes a POSIX exit status in a VMS condition value for better interaction with GNV's bash shell and other utilities that depend on POSIX exit values. See L<perlvms/"$?"> for details. =back =head1 Selected Bug Fixes =over 4 =item * 5.10.0 inadvertently disabled an optimisation, which caused a measurable performance drop in list assignment, such as is often used to assign function parameters from C<@_>. The optimisation has been re-instated, and the performance regression fixed. =item * Fixed memory leak on C<while (1) { map 1, 1 }> [RT #53038]. =item * Some potential coredumps in PerlIO fixed [RT #57322,54828]. =item * The debugger now works with lvalue subroutines. =item * The debugger's C<m> command was broken on modules that defined constants [RT #61222]. =item * C<crypt()> and string complement could return tainted values for untainted arguments [RT #59998]. =item * The C<-i.suffix> command-line switch now recreates the file using restricted permissions, before changing its mode to match the original file. This eliminates a potential race condition [RT #60904]. =item * On some Unix systems, the value in C<$?> would not have the top bit set (C<$? & 128>) even if the child core dumped. =item * Under some circumstances, $^R could incorrectly become undefined [RT #57042]. =item * (XS) In various hash functions, passing a pre-computed hash to when the key is UTF-8 might result in an incorrect lookup. =item * (XS) Including F<XSUB.h> before F<perl.h> gave a compile-time error [RT #57176]. =item * C<< $object->isa('Foo') >> would report false if the package C<Foo> didn't exist, even if the object's C<@ISA> contained C<Foo>. =item * Various bugs in the new-to 5.10.0 mro code, triggered by manipulating C<@ISA>, have been found and fixed. =item * Bitwise operations on references could crash the interpreter, e.g. C<$x=\$y; $x |= "foo"> [RT #54956]. =item * Patterns including alternation might be sensitive to the internal UTF-8 representation, e.g. my $byte = chr(192); my $utf8 = chr(192); utf8::upgrade($utf8); $utf8 =~ /$byte|X}/i; # failed in 5.10.0 =item * Within UTF8-encoded Perl source files (i.e. where C<use utf8> is in effect), double-quoted literal strings could be corrupted where a C<\xNN>, C<\0NNN> or C<\N{}> is followed by a literal character with ordinal value greater than 255 [RT #59908]. =item * C<B::Deparse> failed to correctly deparse various constructs: C<readpipe STRING> [RT #62428], C<CORE::require(STRING)> [RT #62488], C<sub foo(_)> [RT #62484]. =item * Using C<setpgrp()> with no arguments could corrupt the perl stack. =item * The block form of C<eval> is now specifically trappable by C<Safe> and C<ops>. Previously it was erroneously treated like string C<eval>. =item * In 5.10.0, the two characters C<[~> were sometimes parsed as the smart match operator (C<~~>) [RT #63854]. =item * In 5.10.0, the C<*> quantifier in patterns was sometimes treated as C<{0,32767}> [RT #60034, #60464]. For example, this match would fail: ("ab" x 32768) =~ /^(ab)*$/ =item * C<shmget> was limited to a 32 bit segment size on a 64 bit OS [RT #63924]. =item * Using C<next> or C<last> to exit a C<given> block no longer produces a spurious warning like the following: Exiting given via last at foo.pl line 123 =item * On Windows, C<'.\foo'> and C<'..\foo'> were treated differently than C<'./foo'> and C<'../foo'> by C<do> and C<require> [RT #63492]. =item * Assigning a format to a glob could corrupt the format; e.g.: *bar=*foo{FORMAT}; # foo format now bad =item * Attempting to coerce a typeglob to a string or number could cause an assertion failure. The correct error message is now generated, C<Can't coerce GLOB to I<$type>>. =item * Under C<use filetest 'access'>, C<-x> was using the wrong access mode. This has been fixed [RT #49003]. =item * C<length> on a tied scalar that returned a Unicode value would not be correct the first time. This has been fixed. =item * Using an array C<tie> inside in array C<tie> could SEGV. This has been fixed. [RT #51636] =item * A race condition inside C<PerlIOStdio_close()> has been identified and fixed. This used to cause various threading issues, including SEGVs. =item * In C<unpack>, the use of C<()> groups in scalar context was internally placing a list on the interpreter's stack, which manifested in various ways, including SEGVs. This is now fixed [RT #50256]. =item * Magic was called twice in C<substr>, C<\&$x>, C<tie $x, $m> and C<chop>. These have all been fixed. =item * A 5.10.0 optimisation to clear the temporary stack within the implicit loop of C<s///ge> has been reverted, as it turned out to be the cause of obscure bugs in seemingly unrelated parts of the interpreter [commit ef0d4e17921ee3de]. =item * The line numbers for warnings inside C<elsif> are now correct. =item * The C<..> operator now works correctly with ranges whose ends are at or close to the values of the smallest and largest integers. =item * C<binmode STDIN, ':raw'> could lead to segmentation faults on some platforms. This has been fixed [RT #54828]. =item * An off-by-one error meant that C<index $str, ...> was effectively being executed as C<index "$str\0", ...>. This has been fixed [RT #53746]. =item * Various leaks associated with named captures in regexes have been fixed [RT #57024]. =item * A weak reference to a hash would leak. This was affecting C<DBI> [RT #56908]. =item * Using (?|) in a regex could cause a segfault [RT #59734]. =item * Use of a UTF-8 C<tr//> within a closure could cause a segfault [RT #61520]. =item * Calling C<sv_chop()> or otherwise upgrading an SV could result in an unaligned 64-bit access on the SPARC architecture [RT #60574]. =item * In the 5.10.0 release, C<inc_version_list> would incorrectly list C<5.10.*> after C<5.8.*>; this affected the C<@INC> search order [RT #67628]. =item * In 5.10.0, C<pack "a*", $tainted_value> returned a non-tainted value [RT #52552]. =item * In 5.10.0, C<printf> and C<sprintf> could produce the fatal error C<panic: utf8_mg_pos_cache_update> when printing UTF-8 strings [RT #62666]. =item * In the 5.10.0 release, a dynamically created C<AUTOLOAD> method might be missed (method cache issue) [RT #60220,60232]. =item * In the 5.10.0 release, a combination of C<use feature> and C<//ee> could cause a memory leak [RT #63110]. =item * C<-C> on the shebang (C<#!>) line is once more permitted if it is also specified on the command line. C<-C> on the shebang line used to be a silent no-op I<if> it was not also on the command line, so perl 5.10.0 disallowed it, which broke some scripts. Now perl checks whether it is also on the command line and only dies if it is not [RT #67880]. =item * In 5.10.0, certain types of re-entrant regular expression could crash, or cause the following assertion failure [RT #60508]: Assertion rx->sublen >= (s - rx->subbeg) + i failed =back =head1 New or Changed Diagnostics =over 4 =item C<panic: sv_chop %s> This new fatal error occurs when the C routine C<Perl_sv_chop()> was passed a position that is not within the scalar's string buffer. This could be caused by buggy XS code, and at this point recovery is not possible. =item C<Can't locate package %s for the parents of %s> This warning has been removed. In general, it only got produced in conjunction with other warnings, and removing it allowed an ISA lookup optimisation to be added. =item C<v-string in use/require is non-portable> This warning has been removed. =item C<Deep recursion on subroutine "%s"> It is now possible to change the depth threshold for this warning from the default of 100, by recompiling the F<perl> binary, setting the C pre-processor macro C<PERL_SUB_DEPTH_WARN> to the desired value. =back =head1 Changed Internals =over 4 =item * The J.R.R. Tolkien quotes at the head of C source file have been checked and proper citations added, thanks to a patch from Tom Christiansen. =item * C<vcroak()> now accepts a null first argument. In addition, a full audit was made of the "not NULL" compiler annotations, and those for several other internal functions were corrected. =item * New macros C<dSAVEDERRNO>, C<dSAVE_ERRNO>, C<SAVE_ERRNO>, C<RESTORE_ERRNO> have been added to formalise the temporary saving of the C<errno> variable. =item * The function C<Perl_sv_insert_flags> has been added to augment C<Perl_sv_insert>. =item * The function C<Perl_newSV_type(type)> has been added, equivalent to C<Perl_newSV()> followed by C<Perl_sv_upgrade(type)>. =item * The function C<Perl_newSVpvn_flags()> has been added, equivalent to C<Perl_newSVpvn()> and then performing the action relevant to the flag. Two flag bits are currently supported. =over 4 =item C<SVf_UTF8> This will call C<SvUTF8_on()> for you. (Note that this does not convert an sequence of ISO 8859-1 characters to UTF-8). A wrapper, C<newSVpvn_utf8()> is available for this. =item C<SVs_TEMP> Call C<sv_2mortal()> on the new SV. =back There is also a wrapper that takes constant strings, C<newSVpvs_flags()>. =item * The function C<Perl_croak_xs_usage> has been added as a wrapper to C<Perl_croak>. =item * The functions C<PerlIO_find_layer> and C<PerlIO_list_alloc> are now exported. =item * C<PL_na> has been exterminated from the core code, replaced by local STRLEN temporaries, or C<*_nolen()> calls. Either approach is faster than C<PL_na>, which is a pointer deference into the interpreter structure under ithreads, and a global variable otherwise. =item * C<Perl_mg_free()> used to leave freed memory accessible via SvMAGIC() on the scalar. It now updates the linked list to remove each piece of magic as it is freed. =item * Under ithreads, the regex in C<PL_reg_curpm> is now reference counted. This eliminates a lot of hackish workarounds to cope with it not being reference counted. =item * C<Perl_mg_magical()> would sometimes incorrectly turn on C<SvRMAGICAL()>. This has been fixed. =item * The I<public> IV and NV flags are now not set if the string value has trailing "garbage". This behaviour is consistent with not setting the public IV or NV flags if the value is out of range for the type. =item * SV allocation tracing has been added to the diagnostics enabled by C<-Dm>. The tracing can alternatively output via the C<PERL_MEM_LOG> mechanism, if that was enabled when the F<perl> binary was compiled. =item * Uses of C<Nullav>, C<Nullcv>, C<Nullhv>, C<Nullop>, C<Nullsv> etc have been replaced by C<NULL> in the core code, and non-dual-life modules, as C<NULL> is clearer to those unfamiliar with the core code. =item * A macro C<MUTABLE_PTR(p)> has been added, which on (non-pedantic) gcc will not cast away C<const>, returning a C<void *>. Macros C<MUTABLE_SV(av)>, C<MUTABLE_SV(cv)> etc build on this, casting to C<AV *> etc without casting away C<const>. This allows proper compile-time auditing of C<const> correctness in the core, and helped picked up some errors (now fixed). =item * Macros C<mPUSHs()> and C<mXPUSHs()> have been added, for pushing SVs on the stack and mortalizing them. =item * Use of the private structure C<mro_meta> has changed slightly. Nothing outside the core should be accessing this directly anyway. =item * A new tool, C<Porting/expand-macro.pl> has been added, that allows you to view how a C preprocessor macro would be expanded when compiled. This is handy when trying to decode the macro hell that is the perl guts. =back =head1 New Tests Many modules updated from CPAN incorporate new tests. Several tests that have the potential to hang forever if they fail now incorporate a "watchdog" functionality that will kill them after a timeout, which helps ensure that C<make test> and C<make test_harness> run to completion automatically. (Jerry Hedden). Some core-specific tests have been added: =over 4 =item t/comp/retainedlines.t Check that the debugger can retain source lines from C<eval>. =item t/io/perlio_fail.t Check that bad layers fail. =item t/io/perlio_leaks.t Check that PerlIO layers are not leaking. =item t/io/perlio_open.t Check that certain special forms of open work. =item t/io/perlio.t General PerlIO tests. =item t/io/pvbm.t Check that there is no unexpected interaction between the internal types C<PVBM> and C<PVGV>. =item t/mro/package_aliases.t Check that mro works properly in the presence of aliased packages. =item t/op/dbm.t Tests for C<dbmopen> and C<dbmclose>. =item t/op/index_thr.t Tests for the interaction of C<index> and threads. =item t/op/pat_thr.t Tests for the interaction of esoteric patterns and threads. =item t/op/qr_gc.t Test that C<qr> doesn't leak. =item t/op/reg_email_thr.t Tests for the interaction of regex recursion and threads. =item t/op/regexp_qr_embed_thr.t Tests for the interaction of patterns with embedded C<qr//> and threads. =item t/op/regexp_unicode_prop.t Tests for Unicode properties in regular expressions. =item t/op/regexp_unicode_prop_thr.t Tests for the interaction of Unicode properties and threads. =item t/op/reg_nc_tie.t Test the tied methods of C<Tie::Hash::NamedCapture>. =item t/op/reg_posixcc.t Check that POSIX character classes behave consistently. =item t/op/re.t Check that exportable C<re> functions in F<universal.c> work. =item t/op/setpgrpstack.t Check that C<setpgrp> works. =item t/op/substr_thr.t Tests for the interaction of C<substr> and threads. =item t/op/upgrade.t Check that upgrading and assigning scalars works. =item t/uni/lex_utf8.t Check that Unicode in the lexer works. =item t/uni/tie.t Check that Unicode and C<tie> work. =back =head1 Known Problems This is a list of some significant unfixed bugs, which are regressions from either 5.10.0 or 5.8.x. =over 4 =item * C<List::Util::first> misbehaves in the presence of a lexical C<$_> (typically introduced by C<my $_> or implicitly by C<given>). The variable which gets set for each iteration is the package variable C<$_>, not the lexical C<$_> [RT #67694]. A similar issue may occur in other modules that provide functions which take a block as their first argument, like foo { ... $_ ...} list =item * The C<charnames> pragma may generate a run-time error when a regex is interpolated [RT #56444]: use charnames ':full'; my $r1 = qr/\N{THAI CHARACTER SARA I}/; "foo" =~ $r1; # okay "foo" =~ /$r1+/; # runtime error A workaround is to generate the character outside of the regex: my $a = "\N{THAI CHARACTER SARA I}"; my $r1 = qr/$a/; =item * Some regexes may run much more slowly when run in a child thread compared with the thread the pattern was compiled into [RT #55600]. =back =head1 Deprecations The following items are now deprecated. =over 4 =item * C<Switch> is buggy and should be avoided. From perl 5.11.0 onwards, it is intended that any use of the core version of this module will emit a warning, and that the module will eventually be removed from the core (probably in perl 5.14.0). See L<perlsyn/"Switch statements"> for its replacement. =item * C<suidperl> will be removed in 5.12.0. This provides a mechanism to emulate setuid permission bits on systems that don't support it properly. =back =head1 Acknowledgements Some of the work in this release was funded by a TPF grant. Nicholas Clark officially retired from maintenance pumpking duty at the end of 2008; however in reality he has put much effort in since then to help get 5.10.1 into a fit state to be released, including writing a considerable chunk of this perldelta. Steffen Mueller and David Golden in particular helped getting CPAN modules polished and synchronised with their in-core equivalents. Craig Berry was tireless in getting maint to run under VMS, no matter how many times we broke it for him. The other core committers contributed most of the changes, and applied most of the patches sent in by the hundreds of contributors listed in F<AUTHORS>. (Sorry to all the people I haven't mentioned by name). Finally, thanks to Larry Wall, without whom none of this would be necessary. =head1 Reporting Bugs If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup and the perl bug database at http://rt.perl.org/perlbug/ . There may also be information at http://www.perl.org/ , the Perl Home Page. If you believe you have an unreported bug, please run the B<perlbug> program included with your release. Be sure to trim your bug down to a tiny but sufficient test case. Your bug report, along with the output of C<perl -V>, will be sent off to perlbug@perl.org to be analysed by the Perl porting team. If the bug you are reporting has security implications, which make it inappropriate to send to a publicly archived mailing list, then please send it to perl5-security-report@perl.org. This points to a closed subscription unarchived mailing list, which includes all the core committers, who will be able to help assess the impact of issues, figure out a resolution, and help co-ordinate the release of patches to mitigate or fix the problem across all platforms on which Perl is supported. Please only use this address for security issues in the Perl core, not for modules independently distributed on CPAN. =head1 SEE ALSO The F<Changes> file for an explanation of how to view exhaustive details on what changed. The F<INSTALL> file for how to build Perl. The F<README> file for general stuff. The F<Artistic> and F<Copying> files for copyright information. =cut PK PU�\ �z럺 �� perlglossary.podnu �[��� =head1 NAME perlglossary - Perl Glossary =head1 DESCRIPTION A glossary of terms (technical and otherwise) used in the Perl documentation. Other useful sources include the Free On-Line Dictionary of Computing L<http://foldoc.org/>, the Jargon File L<http://catb.org/~esr/jargon/>, and Wikipedia L<http://www.wikipedia.org/>. =head2 A =over 4 =item accessor methods A L</method> used to indirectly inspect or update an L</object>'s state (its L<instance variables|/instance variable>). =item actual arguments The L<scalar values|/scalar value> that you supply to a L</function> or L</subroutine> when you call it. For instance, when you call C<power("puff")>, the string C<"puff"> is the actual argument. See also L</argument> and L</formal arguments>. =item address operator Some languages work directly with the memory addresses of values, but this can be like playing with fire. Perl provides a set of asbestos gloves for handling all memory management. The closest to an address operator in Perl is the backslash operator, but it gives you a L</hard reference>, which is much safer than a memory address. =item algorithm A well-defined sequence of steps, clearly enough explained that even a computer could do them. =item alias A nickname for something, which behaves in all ways as though you'd used the original name instead of the nickname. Temporary aliases are implicitly created in the loop variable for C<foreach> loops, in the C<$_> variable for L<map|perlfunc/map> or L<grep|perlfunc/grep> operators, in C<$a> and C<$b> during L<sort|perlfunc/sort>'s comparison function, and in each element of C<@_> for the L</actual arguments> of a subroutine call. Permanent aliases are explicitly created in L<packages|/package> by L<importing|/import> symbols or by assignment to L<typeglobs|/typeglob>. Lexically scoped aliases for package variables are explicitly created by the L<our|perlfunc/our> declaration. =item alternatives A list of possible choices from which you may select only one, as in "Would you like door A, B, or C?" Alternatives in regular expressions are separated with a single vertical bar: C<|>. Alternatives in normal Perl expressions are separated with a double vertical bar: C<||>. Logical alternatives in L</Boolean> expressions are separated with either C<||> or C<or>. =item anonymous Used to describe a L</referent> that is not directly accessible through a named L</variable>. Such a referent must be indirectly accessible through at least one L</hard reference>. When the last hard reference goes away, the anonymous referent is destroyed without pity. =item architecture The kind of computer you're working on, where one "kind" of computer means all those computers sharing a compatible machine language. Since Perl programs are (typically) simple text files, not executable images, a Perl program is much less sensitive to the architecture it's running on than programs in other languages, such as C, that are compiled into machine code. See also L</platform> and L</operating system>. =item argument A piece of data supplied to a L<program|/executable file>, L</subroutine>, L</function>, or L</method> to tell it what it's supposed to do. Also called a "parameter". =item ARGV The name of the array containing the L</argument> L</vector> from the command line. If you use the empty C<< E<lt>E<gt> >> operator, L</ARGV> is the name of both the L</filehandle> used to traverse the arguments and the L</scalar> containing the name of the current input file. =item arithmetical operator A L</symbol> such as C<+> or C</> that tells Perl to do the arithmetic you were supposed to learn in grade school. =item array An ordered sequence of L<values|/value>, stored such that you can easily access any of the values using an integer L</subscript> that specifies the value's L</offset> in the sequence. =item array context An archaic expression for what is more correctly referred to as L</list context>. =item ASCII The American Standard Code for Information Interchange (a 7-bit character set adequate only for poorly representing English text). Often used loosely to describe the lowest 128 values of the various ISO-8859-X character sets, a bunch of mutually incompatible 8-bit codes sometimes described as half ASCII. See also L</Unicode>. =item assertion A component of a L</regular expression> that must be true for the pattern to match but does not necessarily match any characters itself. Often used specifically to mean a L</zero width> assertion. =item assignment An L</operator> whose assigned mission in life is to change the value of a L</variable>. =item assignment operator Either a regular L</assignment>, or a compound L</operator> composed of an ordinary assignment and some other operator, that changes the value of a variable in place, that is, relative to its old value. For example, C<$a += 2> adds C<2> to C<$a>. =item associative array See L</hash>. Please. =item associativity Determines whether you do the left L</operator> first or the right L</operator> first when you have "A L</operator> B L</operator> C" and the two operators are of the same precedence. Operators like C<+> are left associative, while operators like C<**> are right associative. See L<perlop> for a list of operators and their associativity. =item asynchronous Said of events or activities whose relative temporal ordering is indeterminate because too many things are going on at once. Hence, an asynchronous event is one you didn't know when to expect. =item atom A L</regular expression> component potentially matching a L</substring> containing one or more characters and treated as an indivisible syntactic unit by any following L</quantifier>. (Contrast with an L</assertion> that matches something of L</zero width> and may not be quantified.) =item atomic operation When Democritus gave the word "atom" to the indivisible bits of matter, he meant literally something that could not be cut: I<a-> (not) + I<tomos> (cuttable). An atomic operation is an action that can't be interrupted, not one forbidden in a nuclear-free zone. =item attribute A new feature that allows the declaration of L<variables|/variable> and L<subroutines|/subroutine> with modifiers as in C<sub foo : locked method>. Also, another name for an L</instance variable> of an L</object>. =item autogeneration A feature of L</operator overloading> of L<objects|/object>, whereby the behavior of certain L<operators|/operator> can be reasonably deduced using more fundamental operators. This assumes that the overloaded operators will often have the same relationships as the regular operators. See L<perlop>. =item autoincrement To add one to something automatically, hence the name of the C<++> operator. To instead subtract one from something automatically is known as an "autodecrement". =item autoload To load on demand. (Also called "lazy" loading.) Specifically, to call an L<AUTOLOAD|perlsub/Autoloading> subroutine on behalf of an undefined subroutine. =item autosplit To split a string automatically, as the B<-a> L</switch> does when running under B<-p> or B<-n> in order to emulate L</awk>. (See also the L<AutoSplit> module, which has nothing to do with the B<-a> switch, but a lot to do with autoloading.) =item autovivification A Greco-Roman word meaning "to bring oneself to life". In Perl, storage locations (L<lvalues|/lvalue>) spontaneously generate themselves as needed, including the creation of any L</hard reference> values to point to the next level of storage. The assignment C<$a[5][5][5][5][5] = "quintet"> potentially creates five scalar storage locations, plus four references (in the first four scalar locations) pointing to four new anonymous arrays (to hold the last four scalar locations). But the point of autovivification is that you don't have to worry about it. =item AV Short for "array value", which refers to one of Perl's internal data types that holds an L</array>. The L</AV> type is a subclass of L</SV>. =item awk Descriptive editing term--short for "awkward". Also coincidentally refers to a venerable text-processing language from which Perl derived some of its high-level ideas. =back =head2 B =over 4 =item backreference A substring L<captured|/capturing> by a subpattern within unadorned parentheses in a L</regex>, also referred to as a capture group. The sequences (C<\g1>, C<\g2>, etc.) later in the same pattern refer back to the corresponding subpattern in the current match. Outside the pattern, the numbered variables (C<$1>, C<$2>, etc.) continue to refer to these same values, as long as the pattern was the last successful match of the current dynamic scope. C<\g{-1}> can be used to refer to a group by relative rather than absolute position; and groups can be also be named, and referred to later by name rather than number. See L<perlre/"Capture groups">. =item backtracking The practice of saying, "If I had to do it all over, I'd do it differently," and then actually going back and doing it all over differently. Mathematically speaking, it's returning from an unsuccessful recursion on a tree of possibilities. Perl backtracks when it attempts to match patterns with a L</regular expression>, and its earlier attempts don't pan out. See L<perlre/Backtracking>. =item backward compatibility Means you can still run your old program because we didn't break any of the features or bugs it was relying on. =item bareword A word sufficiently ambiguous to be deemed illegal under L<use strict 'subs'|strict/strict subs>. In the absence of that stricture, a bareword is treated as if quotes were around it. =item base class A generic L</object> type; that is, a L</class> from which other, more specific classes are derived genetically by L</inheritance>. Also called a "superclass" by people who respect their ancestors. =item big-endian From Swift: someone who eats eggs big end first. Also used of computers that store the most significant L</byte> of a word at a lower byte address than the least significant byte. Often considered superior to little-endian machines. See also L</little-endian>. =item binary Having to do with numbers represented in base 2. That means there's basically two numbers, 0 and 1. Also used to describe a "non-text file", presumably because such a file makes full use of all the binary bits in its bytes. With the advent of L</Unicode>, this distinction, already suspect, loses even more of its meaning. =item binary operator An L</operator> that takes two L<operands|/operand>. =item bind To assign a specific L</network address> to a L</socket>. =item bit An integer in the range from 0 to 1, inclusive. The smallest possible unit of information storage. An eighth of a L</byte> or of a dollar. (The term "Pieces of Eight" comes from being able to split the old Spanish dollar into 8 bits, each of which still counted for money. That's why a 25-cent piece today is still "two bits".) =item bit shift The movement of bits left or right in a computer word, which has the effect of multiplying or dividing by a power of 2. =item bit string A sequence of L<bits|/bit> that is actually being thought of as a sequence of bits, for once. =item bless In corporate life, to grant official approval to a thing, as in, "The VP of Engineering has blessed our WebCruncher project." Similarly in Perl, to grant official approval to a L</referent> so that it can function as an L</object>, such as a WebCruncher object. See L<perlfunc/"bless">. =item block What a L</process> does when it has to wait for something: "My process blocked waiting for the disk." As an unrelated noun, it refers to a large chunk of data, of a size that the L</operating system> likes to deal with (normally a power of two such as 512 or 8192). Typically refers to a chunk of data that's coming from or going to a disk file. =item BLOCK A syntactic construct consisting of a sequence of Perl L<statements|/statement> that is delimited by braces. The C<if> and C<while> statements are defined in terms of L<BLOCKs|/BLOCK>, for instance. Sometimes we also say "block" to mean a lexical scope; that is, a sequence of statements that act like a L</BLOCK>, such as within an L<eval|perlfunc/eval> or a file, even though the statements aren't delimited by braces. =item block buffering A method of making input and output efficient by passing one L</block> at a time. By default, Perl does block buffering to disk files. See L</buffer> and L</command buffering>. =item Boolean A value that is either L</true> or L</false>. =item Boolean context A special kind of L</scalar context> used in conditionals to decide whether the L</scalar value> returned by an expression is L</true> or L</false>. Does not evaluate as either a string or a number. See L</context>. =item breakpoint A spot in your program where you've told the debugger to stop L<execution|/execute> so you can poke around and see whether anything is wrong yet. =item broadcast To send a L</datagram> to multiple destinations simultaneously. =item BSD A psychoactive drug, popular in the 80s, probably developed at U. C. Berkeley or thereabouts. Similar in many ways to the prescription-only medication called "System V", but infinitely more useful. (Or, at least, more fun.) The full chemical name is "Berkeley Standard Distribution". =item bucket A location in a L</hash table> containing (potentially) multiple entries whose keys "hash" to the same hash value according to its hash function. (As internal policy, you don't have to worry about it, unless you're into internals, or policy.) =item buffer A temporary holding location for data. L<Block buffering|/block buffering> means that the data is passed on to its destination whenever the buffer is full. L<Line buffering|/line buffering> means that it's passed on whenever a complete line is received. L<Command buffering|/command buffering> means that it's passed every time you do a L<print|perlfunc/print> command (or equivalent). If your output is unbuffered, the system processes it one byte at a time without the use of a holding area. This can be rather inefficient. =item built-in A L</function> that is predefined in the language. Even when hidden by L</overriding>, you can always get at a built-in function by L<qualifying|/qualified> its name with the C<CORE::> pseudo-package. =item bundle A group of related modules on L</CPAN>. (Also, sometimes refers to a group of command-line switches grouped into one L</switch cluster>.) =item byte A piece of data worth eight L<bits|/bit> in most places. =item bytecode A pidgin-like language spoken among 'droids when they don't wish to reveal their orientation (see L</endian>). Named after some similar languages spoken (for similar reasons) between compilers and interpreters in the late 20th century. These languages are characterized by representing everything as a non-architecture-dependent sequence of bytes. =back =head2 C =over 4 =item C A language beloved by many for its inside-out L</type> definitions, inscrutable L</precedence> rules, and heavy L</overloading> of the function-call mechanism. (Well, actually, people first switched to C because they found lowercase identifiers easier to read than upper.) Perl is written in C, so it's not surprising that Perl borrowed a few ideas from it. =item C preprocessor The typical C compiler's first pass, which processes lines beginning with C<#> for conditional compilation and macro definition and does various manipulations of the program text based on the current definitions. Also known as I<cpp>(1). =item call by reference An L</argument>-passing mechanism in which the L</formal arguments> refer directly to the L</actual arguments>, and the L</subroutine> can change the actual arguments by changing the formal arguments. That is, the formal argument is an L</alias> for the actual argument. See also L</call by value>. =item call by value An L</argument>-passing mechanism in which the L</formal arguments> refer to a copy of the L</actual arguments>, and the L</subroutine> cannot change the actual arguments by changing the formal arguments. See also L</call by reference>. =item callback A L</handler> that you register with some other part of your program in the hope that the other part of your program will L</trigger> your handler when some event of interest transpires. =item canonical Reduced to a standard form to facilitate comparison. =item capture buffer, capture group These two terms are synonymous: a L<captured substring|/capturing> by a regex subpattern. =item capturing The use of parentheses around a L</subpattern> in a L</regular expression> to store the matched L</substring> as a L</backreference> or L<capture group|/capture buffer, capture group>. (Captured strings are also returned as a list in L</list context>.) =item character A small integer representative of a unit of orthography. Historically, characters were usually stored as fixed-width integers (typically in a byte, or maybe two, depending on the character set), but with the advent of UTF-8, characters are often stored in a variable number of bytes depending on the size of the integer that represents the character. Perl manages this transparently for you, for the most part. =item character class A square-bracketed list of characters used in a L</regular expression> to indicate that any character of the set may occur at a given point. Loosely, any predefined set of characters so used. =item character property A predefined L</character class> matchable by the C<\p> L</metasymbol>. Many standard properties are defined for L</Unicode>. =item circumfix operator An L</operator> that surrounds its L</operand>, like the angle operator, or parentheses, or a hug. =item class A user-defined L</type>, implemented in Perl via a L</package> that provides (either directly or by inheritance) L<methods|/method> (that is, L<subroutines|/subroutine>) to handle L<instances|/instance> of the class (its L<objects|/object>). See also L</inheritance>. =item class method A L</method> whose L</invocant> is a L</package> name, not an L</object> reference. A method associated with the class as a whole. =item client In networking, a L</process> that initiates contact with a L</server> process in order to exchange data and perhaps receive a service. =item cloister A L</cluster> used to restrict the scope of a L</regular expression modifier>. =item closure An L</anonymous> subroutine that, when a reference to it is generated at run time, keeps track of the identities of externally visible L<lexical variables|/lexical variable> even after those lexical variables have supposedly gone out of L</scope>. They're called "closures" because this sort of behavior gives mathematicians a sense of closure. =item cluster A parenthesized L</subpattern> used to group parts of a L</regular expression> into a single L</atom>. =item CODE The word returned by the L<ref|perlfunc/ref> function when you apply it to a reference to a subroutine. See also L</CV>. =item code generator A system that writes code for you in a low-level language, such as code to implement the backend of a compiler. See L</program generator>. =item code point The position of a character in a character set encoding. The character C<NULL> is almost certainly at the zeroth position in all character sets, so its code point is 0. The code point for the C<SPACE> character in the ASCII character set is 0x20, or 32 decimal; in EBCDIC it is 0x40, or 64 decimal. The L<ord|perlfunc/ord> function returns the code point of a character. "code position" and "ordinal" mean the same thing as "code point". =item code subpattern A L</regular expression> subpattern whose real purpose is to execute some Perl code, for example, the C<(?{...})> and C<(??{...})> subpatterns. =item collating sequence The order into which L<characters|/character> sort. This is used by L</string> comparison routines to decide, for example, where in this glossary to put "collating sequence". =item command In L</shell> programming, the syntactic combination of a program name and its arguments. More loosely, anything you type to a shell (a command interpreter) that starts it doing something. Even more loosely, a Perl L</statement>, which might start with a L</label> and typically ends with a semicolon. =item command buffering A mechanism in Perl that lets you store up the output of each Perl L</command> and then flush it out as a single request to the L</operating system>. It's enabled by setting the C<$|> (C<$AUTOFLUSH>) variable to a true value. It's used when you don't want data sitting around not going where it's supposed to, which may happen because the default on a L</file> or L</pipe> is to use L</block buffering>. =item command name The name of the program currently executing, as typed on the command line. In C, the L</command> name is passed to the program as the first command-line argument. In Perl, it comes in separately as C<$0>. =item command-line arguments The L<values|/value> you supply along with a program name when you tell a L</shell> to execute a L</command>. These values are passed to a Perl program through C<@ARGV>. =item comment A remark that doesn't affect the meaning of the program. In Perl, a comment is introduced by a C<#> character and continues to the end of the line. =item compilation unit The L</file> (or L</string>, in the case of L<eval|perlfunc/eval>) that is currently being compiled. =item compile phase Any time before Perl starts running your main program. See also L</run phase>. Compile phase is mostly spent in L</compile time>, but may also be spent in L</run time> when C<BEGIN> blocks, L<use|perlfunc/use> declarations, or constant subexpressions are being evaluated. The startup and import code of any L<use|perlfunc/use> declaration is also run during compile phase. =item compile time The time when Perl is trying to make sense of your code, as opposed to when it thinks it knows what your code means and is merely trying to do what it thinks your code says to do, which is L</run time>. =item compiler Strictly speaking, a program that munches up another program and spits out yet another file containing the program in a "more executable" form, typically containing native machine instructions. The I<perl> program is not a compiler by this definition, but it does contain a kind of compiler that takes a program and turns it into a more executable form (L<syntax trees|/syntax tree>) within the I<perl> process itself, which the L</interpreter> then interprets. There are, however, extension L<modules|/module> to get Perl to act more like a "real" compiler. See L<O>. =item composer A "constructor" for a L</referent> that isn't really an L</object>, like an anonymous array or a hash (or a sonata, for that matter). For example, a pair of braces acts as a composer for a hash, and a pair of brackets acts as a composer for an array. See L<perlref/Making References>. =item concatenation The process of gluing one cat's nose to another cat's tail. Also, a similar operation on two L<strings|/string>. =item conditional Something "iffy". See L</Boolean context>. =item connection In telephony, the temporary electrical circuit between the caller's and the callee's phone. In networking, the same kind of temporary circuit between a L</client> and a L</server>. =item construct As a noun, a piece of syntax made up of smaller pieces. As a transitive verb, to create an L</object> using a L</constructor>. =item constructor Any L</class method>, instance L</method>, or L</subroutine> that composes, initializes, blesses, and returns an L</object>. Sometimes we use the term loosely to mean a L</composer>. =item context The surroundings, or environment. The context given by the surrounding code determines what kind of data a particular L</expression> is expected to return. The three primary contexts are L</list context>, L</scalar context>, and L</void context>. Scalar context is sometimes subdivided into L</Boolean context>, L</numeric context>, L</string context>, and L</void context>. There's also a "don't care" scalar context (which is dealt with in Programming Perl, Third Edition, Chapter 2, "Bits and Pieces" if you care). =item continuation The treatment of more than one physical L</line> as a single logical line. L</Makefile> lines are continued by putting a backslash before the L</newline>. Mail headers as defined by RFC 822 are continued by putting a space or tab I<after> the newline. In general, lines in Perl do not need any form of continuation mark, because L</whitespace> (including newlines) is gleefully ignored. Usually. =item core dump The corpse of a L</process>, in the form of a file left in the L</working directory> of the process, usually as a result of certain kinds of fatal error. =item CPAN The Comprehensive Perl Archive Network. (See L<perlfaq2/What modules and extensions are available for Perl? What is CPAN?>). =item cracker Someone who breaks security on computer systems. A cracker may be a true L</hacker> or only a L</script kiddie>. =item current package The L</package> in which the current statement is compiled. Scan backwards in the text of your program through the current L<lexical scope|/lexical scoping> or any enclosing lexical scopes till you find a package declaration. That's your current package name. =item current working directory See L</working directory>. =item currently selected output channel The last L</filehandle> that was designated with L<select|perlfunc/select>(C<FILEHANDLE>); L</STDOUT>, if no filehandle has been selected. =item CV An internal "code value" typedef, holding a L</subroutine>. The L</CV> type is a subclass of L</SV>. =back =head2 D =over 4 =item dangling statement A bare, single L</statement>, without any braces, hanging off an C<if> or C<while> conditional. C allows them. Perl doesn't. =item data structure How your various pieces of data relate to each other and what shape they make when you put them all together, as in a rectangular table or a triangular-shaped tree. =item data type A set of possible values, together with all the operations that know how to deal with those values. For example, a numeric data type has a certain set of numbers that you can work with and various mathematical operations that you can do on the numbers but would make little sense on, say, a string such as C<"Kilroy">. Strings have their own operations, such as L</concatenation>. Compound types made of a number of smaller pieces generally have operations to compose and decompose them, and perhaps to rearrange them. L<Objects|/object> that model things in the real world often have operations that correspond to real activities. For instance, if you model an elevator, your elevator object might have an C<open_door()> L</method>. =item datagram A packet of data, such as a L</UDP> message, that (from the viewpoint of the programs involved) can be sent independently over the network. (In fact, all packets are sent independently at the L</IP> level, but L</stream> protocols such as L</TCP> hide this from your program.) =item DBM Stands for "Data Base Management" routines, a set of routines that emulate an L</associative array> using disk files. The routines use a dynamic hashing scheme to locate any entry with only two disk accesses. DBM files allow a Perl program to keep a persistent L</hash> across multiple invocations. You can L<tie|perlfunc/tie> your hash variables to various DBM implementations--see L<AnyDBM_File> and L<DB_File>. =item declaration An L</assertion> that states something exists and perhaps describes what it's like, without giving any commitment as to how or where you'll use it. A declaration is like the part of your recipe that says, "two cups flour, one large egg, four or five tadpoles..." See L</statement> for its opposite. Note that some declarations also function as statements. Subroutine declarations also act as definitions if a body is supplied. =item decrement To subtract a value from a variable, as in "decrement C<$x>" (meaning to remove 1 from its value) or "decrement C<$x> by 3". =item default A L</value> chosen for you if you don't supply a value of your own. =item defined Having a meaning. Perl thinks that some of the things people try to do are devoid of meaning, in particular, making use of variables that have never been given a L</value> and performing certain operations on data that isn't there. For example, if you try to read data past the end of a file, Perl will hand you back an undefined value. See also L</false> and L<perlfunc/defined>. =item delimiter A L</character> or L</string> that sets bounds to an arbitrarily-sized textual object, not to be confused with a L</separator> or L</terminator>. "To delimit" really just means "to surround" or "to enclose" (like these parentheses are doing). =item deprecated modules and features Deprecated modules and features are those which were part of a stable release, but later found to be subtly flawed, and which should be avoided. They are subject to removal and/or bug-incompatible reimplementation in the next major release (but they will be preserved through maintenance releases). Deprecation warnings are issued under B<-w> or C<use diagnostics>, and notices are found in L<perldelta>s, as well as various other PODs. Coding practices that misuse features, such as C<my $foo if 0>, can also be deprecated. =item dereference A fancy computer science term meaning "to follow a L</reference> to what it points to". The "de" part of it refers to the fact that you're taking away one level of L</indirection>. =item derived class A L</class> that defines some of its L<methods|/method> in terms of a more generic class, called a L</base class>. Note that classes aren't classified exclusively into base classes or derived classes: a class can function as both a derived class and a base class simultaneously, which is kind of classy. =item descriptor See L</file descriptor>. =item destroy To deallocate the memory of a L</referent> (first triggering its C<DESTROY> method, if it has one). =item destructor A special L</method> that is called when an L</object> is thinking about L<destroying|/destroy> itself. A Perl program's C<DESTROY> method doesn't do the actual destruction; Perl just L<triggers|/trigger> the method in case the L</class> wants to do any associated cleanup. =item device A whiz-bang hardware gizmo (like a disk or tape drive or a modem or a joystick or a mouse) attached to your computer, that the L</operating system> tries to make look like a L</file> (or a bunch of files). Under Unix, these fake files tend to live in the I</dev> directory. =item directive A L</pod> directive. See L<perlpod>. =item directory A special file that contains other files. Some L<operating systems|/operating system> call these "folders", "drawers", or "catalogs". =item directory handle A name that represents a particular instance of opening a directory to read it, until you close it. See the L<opendir|perlfunc/opendir> function. =item dispatch To send something to its correct destination. Often used metaphorically to indicate a transfer of programmatic control to a destination selected algorithmically, often by lookup in a table of function L<references|/reference> or, in the case of object L<methods|/method>, by traversing the inheritance tree looking for the most specific definition for the method. =item distribution A standard, bundled release of a system of software. The default usage implies source code is included. If that is not the case, it will be called a "binary-only" distribution. =item (to be) dropped modules When Perl 5 was first released (see L<perlhist>), several modules were included, which have now fallen out of common use. It has been suggested that these modules should be removed, since the distribution became rather large, and the common criterion for new module additions is now limited to modules that help to build, test, and extend perl itself. Furthermore, the CPAN (which didn't exist at the time of Perl 5.0) can become the new home of dropped modules. Dropping modules is currently not an option, but further developments may clear the last barriers. =item dweomer An enchantment, illusion, phantasm, or jugglery. Said when Perl's magical L</dwimmer> effects don't do what you expect, but rather seem to be the product of arcane dweomercraft, sorcery, or wonder working. [From Old English] =item dwimmer DWIM is an acronym for "Do What I Mean", the principle that something should just do what you want it to do without an undue amount of fuss. A bit of code that does "dwimming" is a "dwimmer". Dwimming can require a great deal of behind-the-scenes magic, which (if it doesn't stay properly behind the scenes) is called a L</dweomer> instead. =item dynamic scoping Dynamic scoping works over a dynamic scope, making variables visible throughout the rest of the L</block> in which they are first used and in any L<subroutines|/subroutine> that are called by the rest of the block. Dynamically scoped variables can have their values temporarily changed (and implicitly restored later) by a L<local|perlfunc/local> operator. (Compare L</lexical scoping>.) Used more loosely to mean how a subroutine that is in the middle of calling another subroutine "contains" that subroutine at L</run time>. =back =head2 E =over 4 =item eclectic Derived from many sources. Some would say I<too> many. =item element A basic building block. When you're talking about an L</array>, it's one of the items that make up the array. =item embedding When something is contained in something else, particularly when that might be considered surprising: "I've embedded a complete Perl interpreter in my editor!" =item empty list See </null list>. =item empty subclass test The notion that an empty L</derived class> should behave exactly like its L</base class>. =item en passant When you change a L</value> as it is being copied. [From French, "in passing", as in the exotic pawn-capturing maneuver in chess.] =item encapsulation The veil of abstraction separating the L</interface> from the L</implementation> (whether enforced or not), which mandates that all access to an L</object>'s state be through L<methods|/method> alone. =item endian See L</little-endian> and L</big-endian>. =item environment The collective set of L<environment variables|/environment variable> your L</process> inherits from its parent. Accessed via C<%ENV>. =item environment variable A mechanism by which some high-level agent such as a user can pass its preferences down to its future offspring (child L<processes|/process>, grandchild processes, great-grandchild processes, and so on). Each environment variable is a L</key>/L</value> pair, like one entry in a L</hash>. =item EOF End of File. Sometimes used metaphorically as the terminating string of a L</here document>. =item errno The error number returned by a L</syscall> when it fails. Perl refers to the error by the name C<$!> (or C<$OS_ERROR> if you use the English module). =item error See L</exception> or L</fatal error>. =item escape sequence See L</metasymbol>. =item exception A fancy term for an error. See L</fatal error>. =item exception handling The way a program responds to an error. The exception handling mechanism in Perl is the L<eval|perlfunc/eval> operator. =item exec To throw away the current L</process>'s program and replace it with another without exiting the process or relinquishing any resources held (apart from the old memory image). =item executable file A L</file> that is specially marked to tell the L</operating system> that it's okay to run this file as a program. Usually shortened to "executable". =item execute To run a L<program|/executable file> or L</subroutine>. (Has nothing to do with the L<kill|perlfunc/kill> built-in, unless you're trying to run a L</signal handler>.) =item execute bit The special mark that tells the operating system it can run this program. There are actually three execute bits under Unix, and which bit gets used depends on whether you own the file singularly, collectively, or not at all. =item exit status See L</status>. =item export To make symbols from a L</module> available for L</import> by other modules. =item expression Anything you can legally say in a spot where a L</value> is required. Typically composed of L<literals|/literal>, L<variables|/variable>, L<operators|/operator>, L<functions|/function>, and L</subroutine> calls, not necessarily in that order. =item extension A Perl module that also pulls in compiled C or C++ code. More generally, any experimental option that can be compiled into Perl, such as multithreading. =back =head2 F =over 4 =item false In Perl, any value that would look like C<""> or C<"0"> if evaluated in a string context. Since undefined values evaluate to C<"">, all undefined values are false (including the L</null list>), but not all false values are undefined. =item FAQ Frequently Asked Question (although not necessarily frequently answered, especially if the answer appears in the Perl FAQ shipped standard with Perl). =item fatal error An uncaught L</exception>, which causes termination of the L</process> after printing a message on your L</standard error> stream. Errors that happen inside an L<eval|perlfunc/eval> are not fatal. Instead, the L<eval|perlfunc/eval> terminates after placing the exception message in the C<$@> (C<$EVAL_ERROR>) variable. You can try to provoke a fatal error with the L<die|perlfunc/die> operator (known as throwing or raising an exception), but this may be caught by a dynamically enclosing L<eval|perlfunc/eval>. If not caught, the L<die|perlfunc/die> becomes a fatal error. =item field A single piece of numeric or string data that is part of a longer L</string>, L</record>, or L</line>. Variable-width fields are usually split up by L<separators|/separator> (so use L<split|perlfunc/split> to extract the fields), while fixed-width fields are usually at fixed positions (so use L<unpack|perlfunc/unpack>). L<Instance variables|/instance variable> are also known as fields. =item FIFO First In, First Out. See also L</LIFO>. Also, a nickname for a L</named pipe>. =item file A named collection of data, usually stored on disk in a L</directory> in a L</filesystem>. Roughly like a document, if you're into office metaphors. In modern filesystems, you can actually give a file more than one name. Some files have special properties, like directories and devices. =item file descriptor The little number the L</operating system> uses to keep track of which opened L</file> you're talking about. Perl hides the file descriptor inside a L</standard IE<sol>O> stream and then attaches the stream to a L</filehandle>. =item file test operator A built-in unary operator that you use to determine whether something is L</true> about a file, such as C<-o $filename> to test whether you're the owner of the file. =item fileglob A "wildcard" match on L<filenames|/filename>. See the L<glob|perlfunc/glob> function. =item filehandle An identifier (not necessarily related to the real name of a file) that represents a particular instance of opening a file until you close it. If you're going to open and close several different files in succession, it's fine to open each of them with the same filehandle, so you don't have to write out separate code to process each file. =item filename One name for a file. This name is listed in a L</directory>, and you can use it in an L<open|perlfunc/open> to tell the L</operating system> exactly which file you want to open, and associate the file with a L</filehandle> which will carry the subsequent identity of that file in your program, until you close it. =item filesystem A set of L<directories|/directory> and L<files|/file> residing on a partition of the disk. Sometimes known as a "partition". You can change the file's name or even move a file around from directory to directory within a filesystem without actually moving the file itself, at least under Unix. =item filter A program designed to take a L</stream> of input and transform it into a stream of output. =item flag We tend to avoid this term because it means so many things. It may mean a command-line L</switch> that takes no argument itself (such as Perl's B<-n> and B<-p> flags) or, less frequently, a single-bit indicator (such as the C<O_CREAT> and C<O_EXCL> flags used in L<sysopen|perlfunc/sysopen>). =item floating point A method of storing numbers in "scientific notation", such that the precision of the number is independent of its magnitude (the decimal point "floats"). Perl does its numeric work with floating-point numbers (sometimes called "floats"), when it can't get away with using L<integers|/integer>. Floating-point numbers are mere approximations of real numbers. =item flush The act of emptying a L</buffer>, often before it's full. =item FMTEYEWTK Far More Than Everything You Ever Wanted To Know. An exhaustive treatise on one narrow topic, something of a super-L</FAQ>. See Tom for far more. =item fork To create a child L</process> identical to the parent process at its moment of conception, at least until it gets ideas of its own. A thread with protected memory. =item formal arguments The generic names by which a L</subroutine> knows its L<arguments|/argument>. In many languages, formal arguments are always given individual names, but in Perl, the formal arguments are just the elements of an array. The formal arguments to a Perl program are C<$ARGV[0]>, C<$ARGV[1]>, and so on. Similarly, the formal arguments to a Perl subroutine are C<$_[0]>, C<$_[1]>, and so on. You may give the arguments individual names by assigning the values to a L<my|perlfunc/my> list. See also L</actual arguments>. =item format A specification of how many spaces and digits and things to put somewhere so that whatever you're printing comes out nice and pretty. =item freely available Means you don't have to pay money to get it, but the copyright on it may still belong to someone else (like Larry). =item freely redistributable Means you're not in legal trouble if you give a bootleg copy of it to your friends and we find out about it. In fact, we'd rather you gave a copy to all your friends. =item freeware Historically, any software that you give away, particularly if you make the source code available as well. Now often called C<open source software>. Recently there has been a trend to use the term in contradistinction to L</open source software>, to refer only to free software released under the Free Software Foundation's GPL (General Public License), but this is difficult to justify etymologically. =item function Mathematically, a mapping of each of a set of input values to a particular output value. In computers, refers to a L</subroutine> or L</operator> that returns a L</value>. It may or may not have input values (called L<arguments|/argument>). =item funny character Someone like Larry, or one of his peculiar friends. Also refers to the strange prefixes that Perl requires as noun markers on its variables. =back =head2 G =over 4 =item garbage collection A misnamed feature--it should be called, "expecting your mother to pick up after you". Strictly speaking, Perl doesn't do this, but it relies on a reference-counting mechanism to keep things tidy. However, we rarely speak strictly and will often refer to the reference-counting scheme as a form of garbage collection. (If it's any comfort, when your interpreter exits, a "real" garbage collector runs to make sure everything is cleaned up if you've been messy with circular references and such.) =item GID Group ID--in Unix, the numeric group ID that the L</operating system> uses to identify you and members of your L</group>. =item glob Strictly, the shell's C<*> character, which will match a "glob" of characters when you're trying to generate a list of filenames. Loosely, the act of using globs and similar symbols to do pattern matching. See also L</fileglob> and L</typeglob>. =item global Something you can see from anywhere, usually used of L<variables|/variable> and L<subroutines|/subroutine> that are visible everywhere in your program. In Perl, only certain special variables are truly global--most variables (and all subroutines) exist only in the current L</package>. Global variables can be declared with L<our|perlfunc/our>. See L<perlfunc/our>. =item global destruction The L</garbage collection> of globals (and the running of any associated object destructors) that takes place when a Perl L</interpreter> is being shut down. Global destruction should not be confused with the Apocalypse, except perhaps when it should. =item glue language A language such as Perl that is good at hooking things together that weren't intended to be hooked together. =item granularity The size of the pieces you're dealing with, mentally speaking. =item greedy A L</subpattern> whose L</quantifier> wants to match as many things as possible. =item grep Originally from the old Unix editor command for "Globally search for a Regular Expression and Print it", now used in the general sense of any kind of search, especially text searches. Perl has a built-in L<grep|perlfunc/grep> function that searches a list for elements matching any given criterion, whereas the I<grep>(1) program searches for lines matching a L</regular expression> in one or more files. =item group A set of users of which you are a member. In some operating systems (like Unix), you can give certain file access permissions to other members of your group. =item GV An internal "glob value" typedef, holding a L</typeglob>. The L</GV> type is a subclass of L</SV>. =back =head2 H =over 4 =item hacker Someone who is brilliantly persistent in solving technical problems, whether these involve golfing, fighting orcs, or programming. Hacker is a neutral term, morally speaking. Good hackers are not to be confused with evil L<crackers|/cracker> or clueless L<script kiddies|/script kiddie>. If you confuse them, we will presume that you are either evil or clueless. =item handler A L</subroutine> or L</method> that is called by Perl when your program needs to respond to some internal event, such as a L</signal>, or an encounter with an operator subject to L</operator overloading>. See also L</callback>. =item hard reference A L</scalar> L</value> containing the actual address of a L</referent>, such that the referent's L</reference> count accounts for it. (Some hard references are held internally, such as the implicit reference from one of a L</typeglob>'s variable slots to its corresponding referent.) A hard reference is different from a L</symbolic reference>. =item hash An unordered association of L</key>/L</value> pairs, stored such that you can easily use a string L</key> to look up its associated data L</value>. This glossary is like a hash, where the word to be defined is the key, and the definition is the value. A hash is also sometimes septisyllabically called an "associative array", which is a pretty good reason for simply calling it a "hash" instead. A hash can optionally be L<restricted|/restricted hash> to a fixed set of keys. =item hash table A data structure used internally by Perl for implementing associative arrays (hashes) efficiently. See also L</bucket>. =item header file A file containing certain required definitions that you must include "ahead" of the rest of your program to do certain obscure operations. A C header file has a I<.h> extension. Perl doesn't really have header files, though historically Perl has sometimes used translated I<.h> files with a I<.ph> extension. See L<perlfunc/require>. (Header files have been superseded by the L</module> mechanism.) =item here document So called because of a similar construct in L<shells|/shell> that pretends that the L<lines|/line> following the L</command> are a separate L</file> to be fed to the command, up to some terminating string. In Perl, however, it's just a fancy form of quoting. =item hexadecimal A number in base 16, "hex" for short. The digits for 10 through 16 are customarily represented by the letters C<a> through C<f>. Hexadecimal constants in Perl start with C<0x>. See also L<perlfunc/hex>. =item home directory The directory you are put into when you log in. On a Unix system, the name is often placed into C<$ENV{HOME}> or C<$ENV{LOGDIR}> by I<login>, but you can also find it with C<(getpwuid($E<lt>))[7]>. (Some platforms do not have a concept of a home directory.) =item host The computer on which a program or other data resides. =item hubris Excessive pride, the sort of thing Zeus zaps you for. Also the quality that makes you write (and maintain) programs that other people won't want to say bad things about. Hence, the third great virtue of a programmer. See also L</laziness> and L</impatience>. =item HV Short for a "hash value" typedef, which holds Perl's internal representation of a hash. The L</HV> type is a subclass of L</SV>. =back =head2 I =over 4 =item identifier A legally formed name for most anything in which a computer program might be interested. Many languages (including Perl) allow identifiers that start with a letter and contain letters and digits. Perl also counts the underscore character as a valid letter. (Perl also has more complicated names, such as L</qualified> names.) =item impatience The anger you feel when the computer is being lazy. This makes you write programs that don't just react to your needs, but actually anticipate them. Or at least that pretend to. Hence, the second great virtue of a programmer. See also L</laziness> and L</hubris>. =item implementation How a piece of code actually goes about doing its job. Users of the code should not count on implementation details staying the same unless they are part of the published L</interface>. =item import To gain access to symbols that are exported from another module. See L<perlfunc/use>. =item increment To increase the value of something by 1 (or by some other number, if so specified). =item indexing In olden days, the act of looking up a L</key> in an actual index (such as a phone book), but now merely the act of using any kind of key or position to find the corresponding L</value>, even if no index is involved. Things have degenerated to the point that Perl's L<index|perlfunc/index> function merely locates the position (index) of one string in another. =item indirect filehandle An L</expression> that evaluates to something that can be used as a L</filehandle>: a L</string> (filehandle name), a L</typeglob>, a typeglob L</reference>, or a low-level L</IO> object. =item indirect object In English grammar, a short noun phrase between a verb and its direct object indicating the beneficiary or recipient of the action. In Perl, C<print STDOUT "$foo\n";> can be understood as "verb indirect-object object" where L</STDOUT> is the recipient of the L<print|perlfunc/print> action, and C<"$foo"> is the object being printed. Similarly, when invoking a L</method>, you might place the invocant between the method and its arguments: $gollum = new Pathetic::Creature "Smeagol"; give $gollum "Fisssssh!"; give $gollum "Precious!"; In modern Perl, calling methods this way is often considered bad practice and to be avoided. =item indirect object slot The syntactic position falling between a method call and its arguments when using the indirect object invocation syntax. (The slot is distinguished by the absence of a comma between it and the next argument.) L</STDERR> is in the indirect object slot here: print STDERR "Awake! Awake! Fear, Fire, Foes! Awake!\n"; =item indirection If something in a program isn't the value you're looking for but indicates where the value is, that's indirection. This can be done with either L<symbolic references|/symbolic reference> or L<hard references|/hard reference>. =item infix An L</operator> that comes in between its L<operands|/operand>, such as multiplication in C<24 * 7>. =item inheritance What you get from your ancestors, genetically or otherwise. If you happen to be a L</class>, your ancestors are called L<base classes|/base class> and your descendants are called L<derived classes|/derived class>. See L</single inheritance> and L</multiple inheritance>. =item instance Short for "an instance of a class", meaning an L</object> of that L</class>. =item instance variable An L</attribute> of an L</object>; data stored with the particular object rather than with the class as a whole. =item integer A number with no fractional (decimal) part. A counting number, like 1, 2, 3, and so on, but including 0 and the negatives. =item interface The services a piece of code promises to provide forever, in contrast to its L</implementation>, which it should feel free to change whenever it likes. =item interpolation The insertion of a scalar or list value somewhere in the middle of another value, such that it appears to have been there all along. In Perl, variable interpolation happens in double-quoted strings and patterns, and list interpolation occurs when constructing the list of values to pass to a list operator or other such construct that takes a L</LIST>. =item interpreter Strictly speaking, a program that reads a second program and does what the second program says directly without turning the program into a different form first, which is what L<compilers|/compiler> do. Perl is not an interpreter by this definition, because it contains a kind of compiler that takes a program and turns it into a more executable form (L<syntax trees|/syntax tree>) within the I<perl> process itself, which the Perl L</run time> system then interprets. =item invocant The agent on whose behalf a L</method> is invoked. In a L</class> method, the invocant is a package name. In an L</instance> method, the invocant is an object reference. =item invocation The act of calling up a deity, daemon, program, method, subroutine, or function to get it do what you think it's supposed to do. We usually "call" subroutines but "invoke" methods, since it sounds cooler. =item I/O Input from, or output to, a L</file> or L</device>. =item IO An internal I/O object. Can also mean L</indirect object>. =item IP Internet Protocol, or Intellectual Property. =item IPC Interprocess Communication. =item is-a A relationship between two L<objects|/object> in which one object is considered to be a more specific version of the other, generic object: "A camel is a mammal." Since the generic object really only exists in a Platonic sense, we usually add a little abstraction to the notion of objects and think of the relationship as being between a generic L</base class> and a specific L</derived class>. Oddly enough, Platonic classes don't always have Platonic relationships--see L</inheritance>. =item iteration Doing something repeatedly. =item iterator A special programming gizmo that keeps track of where you are in something that you're trying to iterate over. The C<foreach> loop in Perl contains an iterator; so does a hash, allowing you to L<each|perlfunc/each> through it. =item IV The integer four, not to be confused with six, Tom's favorite editor. IV also means an internal Integer Value of the type a L</scalar> can hold, not to be confused with an L</NV>. =back =head2 J =over 4 =item JAPH "Just Another Perl Hacker," a clever but cryptic bit of Perl code that when executed, evaluates to that string. Often used to illustrate a particular Perl feature, and something of an ongoing Obfuscated Perl Contest seen in Usenix signatures. =back =head2 K =over 4 =item key The string index to a L</hash>, used to look up the L</value> associated with that key. =item keyword See L</reserved words>. =back =head2 L =over 4 =item label A name you give to a L</statement> so that you can talk about that statement elsewhere in the program. =item laziness The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don't have to answer so many questions about it. Hence, the first great virtue of a programmer. Also hence, this book. See also L</impatience> and L</hubris>. =item left shift A L</bit shift> that multiplies the number by some power of 2. =item leftmost longest The preference of the L</regular expression> engine to match the leftmost occurrence of a L</pattern>, then given a position at which a match will occur, the preference for the longest match (presuming the use of a L</greedy> quantifier). See L<perlre> for I<much> more on this subject. =item lexeme Fancy term for a L</token>. =item lexer Fancy term for a L</tokener>. =item lexical analysis Fancy term for L</tokenizing>. =item lexical scoping Looking at your I<Oxford English Dictionary> through a microscope. (Also known as L</static scoping>, because dictionaries don't change very fast.) Similarly, looking at variables stored in a private dictionary (namespace) for each scope, which are visible only from their point of declaration down to the end of the lexical scope in which they are declared. --Syn. L</static scoping>. --Ant. L</dynamic scoping>. =item lexical variable A L</variable> subject to L</lexical scoping>, declared by L<my|perlfunc/my>. Often just called a "lexical". (The L<our|perlfunc/our> declaration declares a lexically scoped name for a global variable, which is not itself a lexical variable.) =item library Generally, a collection of procedures. In ancient days, referred to a collection of subroutines in a I<.pl> file. In modern times, refers more often to the entire collection of Perl L<modules|/module> on your system. =item LIFO Last In, First Out. See also L</FIFO>. A LIFO is usually called a L</stack>. =item line In Unix, a sequence of zero or more non-newline characters terminated with a L</newline> character. On non-Unix machines, this is emulated by the C library even if the underlying L</operating system> has different ideas. =item line buffering Used by a L</standard IE<sol>O> output stream that flushes its L</buffer> after every L</newline>. Many standard I/O libraries automatically set up line buffering on output that is going to the terminal. =item line number The number of lines read previous to this one, plus 1. Perl keeps a separate line number for each source or input file it opens. The current source file's line number is represented by C<__LINE__>. The current input line number (for the file that was most recently read via C<< E<lt>FHE<gt> >>) is represented by the C<$.> (C<$INPUT_LINE_NUMBER>) variable. Many error messages report both values, if available. =item link Used as a noun, a name in a L</directory>, representing a L</file>. A given file can have multiple links to it. It's like having the same phone number listed in the phone directory under different names. As a verb, to resolve a partially compiled file's unresolved symbols into a (nearly) executable image. Linking can generally be static or dynamic, which has nothing to do with static or dynamic scoping. =item LIST A syntactic construct representing a comma-separated list of expressions, evaluated to produce a L</list value>. Each L</expression> in a L</LIST> is evaluated in L</list context> and interpolated into the list value. =item list An ordered set of scalar values. =item list context The situation in which an L</expression> is expected by its surroundings (the code calling it) to return a list of values rather than a single value. Functions that want a L</LIST> of arguments tell those arguments that they should produce a list value. See also L</context>. =item list operator An L</operator> that does something with a list of values, such as L<join|perlfunc/join> or L<grep|perlfunc/grep>. Usually used for named built-in operators (such as L<print|perlfunc/print>, L<unlink|perlfunc/unlink>, and L<system|perlfunc/system>) that do not require parentheses around their L</argument> list. =item list value An unnamed list of temporary scalar values that may be passed around within a program from any list-generating function to any function or construct that provides a L</list context>. =item literal A token in a programming language such as a number or L</string> that gives you an actual L</value> instead of merely representing possible values as a L</variable> does. =item little-endian From Swift: someone who eats eggs little end first. Also used of computers that store the least significant L</byte> of a word at a lower byte address than the most significant byte. Often considered superior to big-endian machines. See also L</big-endian>. =item local Not meaning the same thing everywhere. A global variable in Perl can be localized inside a L<dynamic scope|/dynamic scoping> via the L<local|perlfunc/local> operator. =item logical operator Symbols representing the concepts "and", "or", "xor", and "not". =item lookahead An L</assertion> that peeks at the string to the right of the current match location. =item lookbehind An L</assertion> that peeks at the string to the left of the current match location. =item loop A construct that performs something repeatedly, like a roller coaster. =item loop control statement Any statement within the body of a loop that can make a loop prematurely stop looping or skip an L</iteration>. Generally you shouldn't try this on roller coasters. =item loop label A kind of key or name attached to a loop (or roller coaster) so that loop control statements can talk about which loop they want to control. =item lvaluable Able to serve as an L</lvalue>. =item lvalue Term used by language lawyers for a storage location you can assign a new L</value> to, such as a L</variable> or an element of an L</array>. The "l" is short for "left", as in the left side of an assignment, a typical place for lvalues. An L</lvaluable> function or expression is one to which a value may be assigned, as in C<pos($x) = 10>. =item lvalue modifier An adjectival pseudofunction that warps the meaning of an L</lvalue> in some declarative fashion. Currently there are three lvalue modifiers: L<my|perlfunc/my>, L<our|perlfunc/our>, and L<local|perlfunc/local>. =back =head2 M =over 4 =item magic Technically speaking, any extra semantics attached to a variable such as C<$!>, C<$0>, C<%ENV>, or C<%SIG>, or to any tied variable. Magical things happen when you diddle those variables. =item magical increment An L</increment> operator that knows how to bump up alphabetics as well as numbers. =item magical variables Special variables that have side effects when you access them or assign to them. For example, in Perl, changing elements of the C<%ENV> array also changes the corresponding environment variables that subprocesses will use. Reading the C<$!> variable gives you the current system error number or message. =item Makefile A file that controls the compilation of a program. Perl programs don't usually need a L</Makefile> because the Perl compiler has plenty of self-control. =item man The Unix program that displays online documentation (manual pages) for you. =item manpage A "page" from the manuals, typically accessed via the I<man>(1) command. A manpage contains a SYNOPSIS, a DESCRIPTION, a list of BUGS, and so on, and is typically longer than a page. There are manpages documenting L<commands|/command>, L<syscalls|/syscall>, L</library> L<functions|/function>, L<devices|/device>, L<protocols|/protocol>, L<files|/file>, and such. In this book, we call any piece of standard Perl documentation (like I<perlop> or I<perldelta>) a manpage, no matter what format it's installed in on your system. =item matching See L</pattern matching>. =item member data See L</instance variable>. =item memory This always means your main memory, not your disk. Clouding the issue is the fact that your machine may implement L</virtual> memory; that is, it will pretend that it has more memory than it really does, and it'll use disk space to hold inactive bits. This can make it seem like you have a little more memory than you really do, but it's not a substitute for real memory. The best thing that can be said about virtual memory is that it lets your performance degrade gradually rather than suddenly when you run out of real memory. But your program can die when you run out of virtual memory too, if you haven't thrashed your disk to death first. =item metacharacter A L</character> that is I<not> supposed to be treated normally. Which characters are to be treated specially as metacharacters varies greatly from context to context. Your L</shell> will have certain metacharacters, double-quoted Perl L<strings|/string> have other metacharacters, and L</regular expression> patterns have all the double-quote metacharacters plus some extra ones of their own. =item metasymbol Something we'd call a L</metacharacter> except that it's a sequence of more than one character. Generally, the first character in the sequence must be a true metacharacter to get the other characters in the metasymbol to misbehave along with it. =item method A kind of action that an L</object> can take if you tell it to. See L<perlobj>. =item minimalism The belief that "small is beautiful." Paradoxically, if you say something in a small language, it turns out big, and if you say it in a big language, it turns out small. Go figure. =item mode In the context of the L<stat(2)> syscall, refers to the field holding the L</permission bits> and the type of the L</file>. =item modifier See L</statement modifier>, L</regular expression modifier>, and L</lvalue modifier>, not necessarily in that order. =item module A L</file> that defines a L</package> of (almost) the same name, which can either L</export> symbols or function as an L</object> class. (A module's main I<.pm> file may also load in other files in support of the module.) See the L<use|perlfunc/use> built-in. =item modulus An integer divisor when you're interested in the remainder instead of the quotient. =item monger Short for Perl Monger, a purveyor of Perl. =item mortal A temporary value scheduled to die when the current statement finishes. =item multidimensional array An array with multiple subscripts for finding a single element. Perl implements these using L<references|/reference>--see L<perllol> and L<perldsc>. =item multiple inheritance The features you got from your mother and father, mixed together unpredictably. (See also L</inheritance>, and L</single inheritance>.) In computer languages (including Perl), the notion that a given class may have multiple direct ancestors or L<base classes|/base class>. =back =head2 N =over 4 =item named pipe A L</pipe> with a name embedded in the L</filesystem> so that it can be accessed by two unrelated L<processes|/process>. =item namespace A domain of names. You needn't worry about whether the names in one such domain have been used in another. See L</package>. =item network address The most important attribute of a socket, like your telephone's telephone number. Typically an IP address. See also L</port>. =item newline A single character that represents the end of a line, with the ASCII value of 012 octal under Unix (but 015 on a Mac), and represented by C<\n> in Perl strings. For Windows machines writing text files, and for certain physical devices like terminals, the single newline gets automatically translated by your C library into a line feed and a carriage return, but normally, no translation is done. =item NFS Network File System, which allows you to mount a remote filesystem as if it were local. =item null character A character with the ASCII value of zero. It's used by C to terminate strings, but Perl allows strings to contain a null. =item null list A valueless value represented in Perl by C<()>. It is not really a L</LIST>, but an expression that yields C<undef> in L</scalar context> and a L</list value> with zero elements in L</list context>. =item null string A L</string> containing no characters, not to be confused with a string containing a L</null character>, which has a positive length and is L</true>. =item numeric context The situation in which an expression is expected by its surroundings (the code calling it) to return a number. See also L</context> and L</string context>. =item NV Short for Nevada, no part of which will ever be confused with civilization. NV also means an internal floating-point Numeric Value of the type a L</scalar> can hold, not to be confused with an L</IV>. =item nybble Half a L</byte>, equivalent to one L</hexadecimal> digit, and worth four L<bits|/bit>. =back =head2 O =over 4 =item object An L</instance> of a L</class>. Something that "knows" what user-defined type (class) it is, and what it can do because of what class it is. Your program can request an object to do things, but the object gets to decide whether it wants to do them or not. Some objects are more accommodating than others. =item octal A number in base 8. Only the digits 0 through 7 are allowed. Octal constants in Perl start with 0, as in 013. See also the L<oct|perlfunc/oct> function. =item offset How many things you have to skip over when moving from the beginning of a string or array to a specific position within it. Thus, the minimum offset is zero, not one, because you don't skip anything to get to the first item. =item one-liner An entire computer program crammed into one line of text. =item open source software Programs for which the source code is freely available and freely redistributable, with no commercial strings attached. For a more detailed definition, see L<http://www.opensource.org/osd.html>. =item operand An L</expression> that yields a L</value> that an L</operator> operates on. See also L</precedence>. =item operating system A special program that runs on the bare machine and hides the gory details of managing L<processes|/process> and L<devices|/device>. Usually used in a looser sense to indicate a particular culture of programming. The loose sense can be used at varying levels of specificity. At one extreme, you might say that all versions of Unix and Unix-lookalikes are the same operating system (upsetting many people, especially lawyers and other advocates). At the other extreme, you could say this particular version of this particular vendor's operating system is different from any other version of this or any other vendor's operating system. Perl is much more portable across operating systems than many other languages. See also L</architecture> and L</platform>. =item operator A gizmo that transforms some number of input values to some number of output values, often built into a language with a special syntax or symbol. A given operator may have specific expectations about what L<types|/type> of data you give as its arguments (L<operands|/operand>) and what type of data you want back from it. =item operator overloading A kind of L</overloading> that you can do on built-in L<operators|/operator> to make them work on L<objects|/object> as if the objects were ordinary scalar values, but with the actual semantics supplied by the object class. This is set up with the L<overload> L</pragma>. =item options See either L<switches|/switch> or L</regular expression modifier>. =item ordinal Another name for L</code point> =item overloading Giving additional meanings to a symbol or construct. Actually, all languages do overloading to one extent or another, since people are good at figuring out things from L</context>. =item overriding Hiding or invalidating some other definition of the same name. (Not to be confused with L</overloading>, which adds definitions that must be disambiguated some other way.) To confuse the issue further, we use the word with two overloaded definitions: to describe how you can define your own L</subroutine> to hide a built-in L</function> of the same name (see L<perlsub/Overriding Built-in Functions>) and to describe how you can define a replacement L</method> in a L</derived class> to hide a L</base class>'s method of the same name (see L<perlobj>). =item owner The one user (apart from the superuser) who has absolute control over a L</file>. A file may also have a L</group> of users who may exercise joint ownership if the real owner permits it. See L</permission bits>. =back =head2 P =over 4 =item package A L</namespace> for global L<variables|/variable>, L<subroutines|/subroutine>, and the like, such that they can be kept separate from like-named L<symbols|/symbol> in other namespaces. In a sense, only the package is global, since the symbols in the package's symbol table are only accessible from code compiled outside the package by naming the package. But in another sense, all package symbols are also globals--they're just well-organized globals. =item pad Short for L</scratchpad>. =item parameter See L</argument>. =item parent class See L</base class>. =item parse tree See L</syntax tree>. =item parsing The subtle but sometimes brutal art of attempting to turn your possibly malformed program into a valid L</syntax tree>. =item patch To fix by applying one, as it were. In the realm of hackerdom, a listing of the differences between two versions of a program as might be applied by the I<patch>(1) program when you want to fix a bug or upgrade your old version. =item PATH The list of L<directories|/directory> the system searches to find a program you want to L</execute>. The list is stored as one of your L<environment variables|/environment variable>, accessible in Perl as C<$ENV{PATH}>. =item pathname A fully qualified filename such as I</usr/bin/perl>. Sometimes confused with L</PATH>. =item pattern A template used in L</pattern matching>. =item pattern matching Taking a pattern, usually a L</regular expression>, and trying the pattern various ways on a string to see whether there's any way to make it fit. Often used to pick interesting tidbits out of a file. =item permission bits Bits that the L</owner> of a file sets or unsets to allow or disallow access to other people. These flag bits are part of the L</mode> word returned by the L<stat|perlfunc/stat> built-in when you ask about a file. On Unix systems, you can check the I<ls>(1) manpage for more information. =item Pern What you get when you do C<Perl++> twice. Doing it only once will curl your hair. You have to increment it eight times to shampoo your hair. Lather, rinse, iterate. =item pipe A direct L</connection> that carries the output of one L</process> to the input of another without an intermediate temporary file. Once the pipe is set up, the two processes in question can read and write as if they were talking to a normal file, with some caveats. =item pipeline A series of L<processes|/process> all in a row, linked by L<pipes|/pipe>, where each passes its output stream to the next. =item platform The entire hardware and software context in which a program runs. A program written in a platform-dependent language might break if you change any of: machine, operating system, libraries, compiler, or system configuration. The I<perl> interpreter has to be compiled differently for each platform because it is implemented in C, but programs written in the Perl language are largely platform-independent. =item pod The markup used to embed documentation into your Perl code. See L<perlpod>. =item pointer A L</variable> in a language like C that contains the exact memory location of some other item. Perl handles pointers internally so you don't have to worry about them. Instead, you just use symbolic pointers in the form of L<keys|/key> and L</variable> names, or L<hard references|/hard reference>, which aren't pointers (but act like pointers and do in fact contain pointers). =item polymorphism The notion that you can tell an L</object> to do something generic, and the object will interpret the command in different ways depending on its type. [E<lt>Gk many shapes] =item port The part of the address of a TCP or UDP socket that directs packets to the correct process after finding the right machine, something like the phone extension you give when you reach the company operator. Also, the result of converting code to run on a different platform than originally intended, or the verb denoting this conversion. =item portable Once upon a time, C code compilable under both BSD and SysV. In general, code that can be easily converted to run on another L</platform>, where "easily" can be defined however you like, and usually is. Anything may be considered portable if you try hard enough. See I<mobile home> or I<London Bridge>. =item porter Someone who "carries" software from one L</platform> to another. Porting programs written in platform-dependent languages such as C can be difficult work, but porting programs like Perl is very much worth the agony. =item POSIX The Portable Operating System Interface specification. =item postfix An L</operator> that follows its L</operand>, as in C<$x++>. =item pp An internal shorthand for a "push-pop" code, that is, C code implementing Perl's stack machine. =item pragma A standard module whose practical hints and suggestions are received (and possibly ignored) at compile time. Pragmas are named in all lowercase. =item precedence The rules of conduct that, in the absence of other guidance, determine what should happen first. For example, in the absence of parentheses, you always do multiplication before addition. =item prefix An L</operator> that precedes its L</operand>, as in C<++$x>. =item preprocessing What some helper L</process> did to transform the incoming data into a form more suitable for the current process. Often done with an incoming L</pipe>. See also L</C preprocessor>. =item procedure A L</subroutine>. =item process An instance of a running program. Under multitasking systems like Unix, two or more separate processes could be running the same program independently at the same time--in fact, the L<fork|perlfunc/fork> function is designed to bring about this happy state of affairs. Under other operating systems, processes are sometimes called "threads", "tasks", or "jobs", often with slight nuances in meaning. =item program generator A system that algorithmically writes code for you in a high-level language. See also L</code generator>. =item progressive matching L<Pattern matching|/pattern matching> that picks up where it left off before. =item property See either L</instance variable> or L</character property>. =item protocol In networking, an agreed-upon way of sending messages back and forth so that neither correspondent will get too confused. =item prototype An optional part of a L</subroutine> declaration telling the Perl compiler how many and what flavor of arguments may be passed as L</actual arguments>, so that you can write subroutine calls that parse much like built-in functions. (Or don't parse, as the case may be.) =item pseudofunction A construct that sometimes looks like a function but really isn't. Usually reserved for L</lvalue> modifiers like L<my|perlfunc/my>, for L</context> modifiers like L<scalar|perlfunc/scalar>, and for the pick-your-own-quotes constructs, C<q//>, C<qq//>, C<qx//>, C<qw//>, C<qr//>, C<m//>, C<s///>, C<y///>, and C<tr///>. =item pseudohash A reference to an array whose initial element happens to hold a reference to a hash. You can treat a pseudohash reference as either an array reference or a hash reference. =item pseudoliteral An L</operator> that looks something like a L</literal>, such as the output-grabbing operator, C<`>I<C<command>>C<`>. =item public domain Something not owned by anybody. Perl is copyrighted and is thus I<not> in the public domain--it's just L</freely available> and L</freely redistributable>. =item pumpkin A notional "baton" handed around the Perl community indicating who is the lead integrator in some arena of development. =item pumpking A L</pumpkin> holder, the person in charge of pumping the pump, or at least priming it. Must be willing to play the part of the Great Pumpkin now and then. =item PV A "pointer value", which is Perl Internals Talk for a C<char*>. =back =head2 Q =over 4 =item qualified Possessing a complete name. The symbol C<$Ent::moot> is qualified; C<$moot> is unqualified. A fully qualified filename is specified from the top-level directory. =item quantifier A component of a L</regular expression> specifying how many times the foregoing L</atom> may occur. =back =head2 R =over 4 =item readable With respect to files, one that has the proper permission bit set to let you access the file. With respect to computer programs, one that's written well enough that someone has a chance of figuring out what it's trying to do. =item reaping The last rites performed by a parent L</process> on behalf of a deceased child process so that it doesn't remain a L</zombie>. See the L<wait|perlfunc/wait> and L<waitpid|perlfunc/waitpid> function calls. =item record A set of related data values in a L</file> or L</stream>, often associated with a unique L</key> field. In Unix, often commensurate with a L</line>, or a blank-line-terminated set of lines (a "paragraph"). Each line of the I</etc/passwd> file is a record, keyed on login name, containing information about that user. =item recursion The art of defining something (at least partly) in terms of itself, which is a naughty no-no in dictionaries but often works out okay in computer programs if you're careful not to recurse forever, which is like an infinite loop with more spectacular failure modes. =item reference Where you look to find a pointer to information somewhere else. (See L</indirection>.) References come in two flavors, L<symbolic references|/symbolic reference> and L<hard references|/hard reference>. =item referent Whatever a reference refers to, which may or may not have a name. Common types of referents include scalars, arrays, hashes, and subroutines. =item regex See L</regular expression>. =item regular expression A single entity with various interpretations, like an elephant. To a computer scientist, it's a grammar for a little language in which some strings are legal and others aren't. To normal people, it's a pattern you can use to find what you're looking for when it varies from case to case. Perl's regular expressions are far from regular in the theoretical sense, but in regular use they work quite well. Here's a regular expression: C</Oh s.*t./>. This will match strings like "C<Oh say can you see by the dawn's early light>" and "C<Oh sit!>". See L<perlre>. =item regular expression modifier An option on a pattern or substitution, such as C</i> to render the pattern case insensitive. See also L</cloister>. =item regular file A L</file> that's not a L</directory>, a L</device>, a named L</pipe> or L</socket>, or a L</symbolic link>. Perl uses the C<-f> file test operator to identify regular files. Sometimes called a "plain" file. =item relational operator An L</operator> that says whether a particular ordering relationship is L</true> about a pair of L<operands|/operand>. Perl has both numeric and string relational operators. See L</collating sequence>. =item reserved words A word with a specific, built-in meaning to a L</compiler>, such as C<if> or L<delete|perlfunc/delete>. In many languages (not Perl), it's illegal to use reserved words to name anything else. (Which is why they're reserved, after all.) In Perl, you just can't use them to name L<labels|/label> or L<filehandles|/filehandle>. Also called "keywords". =item restricted hash A L</hash> with a closed set of allowed keys. See L<Hash::Util>. =item return value The L</value> produced by a L</subroutine> or L</expression> when evaluated. In Perl, a return value may be either a L</list> or a L</scalar>. =item RFC Request For Comment, which despite the timid connotations is the name of a series of important standards documents. =item right shift A L</bit shift> that divides a number by some power of 2. =item root The superuser (UID == 0). Also, the top-level directory of the filesystem. =item RTFM What you are told when someone thinks you should Read The Fine Manual. =item run phase Any time after Perl starts running your main program. See also L</compile phase>. Run phase is mostly spent in L</run time> but may also be spent in L</compile time> when L<require|perlfunc/require>, L<do|perlfunc/do> C<FILE>, or L<eval|perlfunc/eval> C<STRING> operators are executed or when a substitution uses the C</ee> modifier. =item run time The time when Perl is actually doing what your code says to do, as opposed to the earlier period of time when it was trying to figure out whether what you said made any sense whatsoever, which is L</compile time>. =item run-time pattern A pattern that contains one or more variables to be interpolated before parsing the pattern as a L</regular expression>, and that therefore cannot be analyzed at compile time, but must be re-analyzed each time the pattern match operator is evaluated. Run-time patterns are useful but expensive. =item RV A recreational vehicle, not to be confused with vehicular recreation. RV also means an internal Reference Value of the type a L</scalar> can hold. See also L</IV> and L</NV> if you're not confused yet. =item rvalue A L</value> that you might find on the right side of an L</assignment>. See also L</lvalue>. =back =head2 S =over 4 =item scalar A simple, singular value; a number, L</string>, or L</reference>. =item scalar context The situation in which an L</expression> is expected by its surroundings (the code calling it) to return a single L</value> rather than a L</list> of values. See also L</context> and L</list context>. A scalar context sometimes imposes additional constraints on the return value--see L</string context> and L</numeric context>. Sometimes we talk about a L</Boolean context> inside conditionals, but this imposes no additional constraints, since any scalar value, whether numeric or L</string>, is already true or false. =item scalar literal A number or quoted L</string>--an actual L</value> in the text of your program, as opposed to a L</variable>. =item scalar value A value that happens to be a L</scalar> as opposed to a L</list>. =item scalar variable A L</variable> prefixed with C<$> that holds a single value. =item scope How far away you can see a variable from, looking through one. Perl has two visibility mechanisms: it does L</dynamic scoping> of L<local|perlfunc/local> L<variables|/variable>, meaning that the rest of the L</block>, and any L<subroutines|/subroutine> that are called by the rest of the block, can see the variables that are local to the block. Perl does L</lexical scoping> of L<my|perlfunc/my> variables, meaning that the rest of the block can see the variable, but other subroutines called by the block I<cannot> see the variable. =item scratchpad The area in which a particular invocation of a particular file or subroutine keeps some of its temporary values, including any lexically scoped variables. =item script A text L</file> that is a program intended to be L<executed|/execute> directly rather than L<compiled|/compiler> to another form of file before execution. Also, in the context of L</Unicode>, a writing system for a particular language or group of languages, such as Greek, Bengali, or Klingon. =item script kiddie A L</cracker> who is not a L</hacker>, but knows just enough to run canned scripts. A cargo-cult programmer. =item sed A venerable Stream EDitor from which Perl derives some of its ideas. =item semaphore A fancy kind of interlock that prevents multiple L<threads|/thread> or L<processes|/process> from using up the same resources simultaneously. =item separator A L</character> or L</string> that keeps two surrounding strings from being confused with each other. The L<split|perlfunc/split> function works on separators. Not to be confused with L<delimiters|/delimiter> or L<terminators|/terminator>. The "or" in the previous sentence separated the two alternatives. =item serialization Putting a fancy L</data structure> into linear order so that it can be stored as a L</string> in a disk file or database or sent through a L</pipe>. Also called marshalling. =item server In networking, a L</process> that either advertises a L</service> or just hangs around at a known location and waits for L<clients|/client> who need service to get in touch with it. =item service Something you do for someone else to make them happy, like giving them the time of day (or of their life). On some machines, well-known services are listed by the L<getservent|perlfunc/getservent> function. =item setgid Same as L</setuid>, only having to do with giving away L</group> privileges. =item setuid Said of a program that runs with the privileges of its L</owner> rather than (as is usually the case) the privileges of whoever is running it. Also describes the bit in the mode word (L</permission bits>) that controls the feature. This bit must be explicitly set by the owner to enable this feature, and the program must be carefully written not to give away more privileges than it ought to. =item shared memory A piece of L</memory> accessible by two different L<processes|/process> who otherwise would not see each other's memory. =item shebang Irish for the whole McGillicuddy. In Perl culture, a portmanteau of "sharp" and "bang", meaning the C<#!> sequence that tells the system where to find the interpreter. =item shell A L</command>-line L</interpreter>. The program that interactively gives you a prompt, accepts one or more L<lines|/line> of input, and executes the programs you mentioned, feeding each of them their proper L<arguments|/argument> and input data. Shells can also execute scripts containing such commands. Under Unix, typical shells include the Bourne shell (I</bin/sh>), the C shell (I</bin/csh>), and the Korn shell (I</bin/ksh>). Perl is not strictly a shell because it's not interactive (although Perl programs can be interactive). =item side effects Something extra that happens when you evaluate an L</expression>. Nowadays it can refer to almost anything. For example, evaluating a simple assignment statement typically has the "side effect" of assigning a value to a variable. (And you thought assigning the value was your primary intent in the first place!) Likewise, assigning a value to the special variable C<$|> (C<$AUTOFLUSH>) has the side effect of forcing a flush after every L<write|perlfunc/write> or L<print|perlfunc/print> on the currently selected filehandle. =item signal A bolt out of the blue; that is, an event triggered by the L</operating system>, probably when you're least expecting it. =item signal handler A L</subroutine> that, instead of being content to be called in the normal fashion, sits around waiting for a bolt out of the blue before it will deign to L</execute>. Under Perl, bolts out of the blue are called signals, and you send them with the L<kill|perlfunc/kill> built-in. See L<perlvar/%SIG> and L<perlipc/Signals>. =item single inheritance The features you got from your mother, if she told you that you don't have a father. (See also L</inheritance> and L</multiple inheritance>.) In computer languages, the notion that L<classes|/class> reproduce asexually so that a given class can only have one direct ancestor or L</base class>. Perl supplies no such restriction, though you may certainly program Perl that way if you like. =item slice A selection of any number of L<elements|/element> from a L</list>, L</array>, or L</hash>. =item slurp To read an entire L</file> into a L</string> in one operation. =item socket An endpoint for network communication among multiple L<processes|/process> that works much like a telephone or a post office box. The most important thing about a socket is its L</network address> (like a phone number). Different kinds of sockets have different kinds of addresses--some look like filenames, and some don't. =item soft reference See L</symbolic reference>. =item source filter A special kind of L</module> that does L</preprocessing> on your script just before it gets to the L</tokener>. =item stack A device you can put things on the top of, and later take them back off in the opposite order in which you put them on. See L</LIFO>. =item standard Included in the official Perl distribution, as in a standard module, a standard tool, or a standard Perl L</manpage>. =item standard error The default output L</stream> for nasty remarks that don't belong in L</standard output>. Represented within a Perl program by the L</filehandle> L</STDERR>. You can use this stream explicitly, but the L<die|perlfunc/die> and L<warn|perlfunc/warn> built-ins write to your standard error stream automatically. =item standard I/O A standard C library for doing L<buffered|/buffer> input and output to the L</operating system>. (The "standard" of standard I/O is only marginally related to the "standard" of standard input and output.) In general, Perl relies on whatever implementation of standard I/O a given operating system supplies, so the buffering characteristics of a Perl program on one machine may not exactly match those on another machine. Normally this only influences efficiency, not semantics. If your standard I/O package is doing block buffering and you want it to L</flush> the buffer more often, just set the C<$|> variable to a true value. =item standard input The default input L</stream> for your program, which if possible shouldn't care where its data is coming from. Represented within a Perl program by the L</filehandle> L</STDIN>. =item standard output The default output L</stream> for your program, which if possible shouldn't care where its data is going. Represented within a Perl program by the L</filehandle> L</STDOUT>. =item stat structure A special internal spot in which Perl keeps the information about the last L</file> on which you requested information. =item statement A L</command> to the computer about what to do next, like a step in a recipe: "Add marmalade to batter and mix until mixed." A statement is distinguished from a L</declaration>, which doesn't tell the computer to do anything, but just to learn something. =item statement modifier A L</conditional> or L</loop> that you put after the L</statement> instead of before, if you know what we mean. =item static Varying slowly compared to something else. (Unfortunately, everything is relatively stable compared to something else, except for certain elementary particles, and we're not so sure about them.) In computers, where things are supposed to vary rapidly, "static" has a derogatory connotation, indicating a slightly dysfunctional L</variable>, L</subroutine>, or L</method>. In Perl culture, the word is politely avoided. =item static method No such thing. See L</class method>. =item static scoping No such thing. See L</lexical scoping>. =item static variable No such thing. Just use a L</lexical variable> in a scope larger than your L</subroutine>. =item status The L</value> returned to the parent L</process> when one of its child processes dies. This value is placed in the special variable C<$?>. Its upper eight L<bits|/bit> are the exit status of the defunct process, and its lower eight bits identify the signal (if any) that the process died from. On Unix systems, this status value is the same as the status word returned by I<wait>(2). See L<perlfunc/system>. =item STDERR See L</standard error>. =item STDIN See L</standard input>. =item STDIO See L</standard IE<sol>O>. =item STDOUT See L</standard output>. =item stream A flow of data into or out of a process as a steady sequence of bytes or characters, without the appearance of being broken up into packets. This is a kind of L</interface>--the underlying L</implementation> may well break your data up into separate packets for delivery, but this is hidden from you. =item string A sequence of characters such as "He said !@#*&%@#*?!". A string does not have to be entirely printable. =item string context The situation in which an expression is expected by its surroundings (the code calling it) to return a L</string>. See also L</context> and L</numeric context>. =item stringification The process of producing a L</string> representation of an abstract object. =item struct C keyword introducing a structure definition or name. =item structure See L</data structure>. =item subclass See L</derived class>. =item subpattern A component of a L</regular expression> pattern. =item subroutine A named or otherwise accessible piece of program that can be invoked from elsewhere in the program in order to accomplish some sub-goal of the program. A subroutine is often parameterized to accomplish different but related things depending on its input L<arguments|/argument>. If the subroutine returns a meaningful L</value>, it is also called a L</function>. =item subscript A L</value> that indicates the position of a particular L</array> L</element> in an array. =item substitution Changing parts of a string via the C<s///> operator. (We avoid use of this term to mean L</variable interpolation>.) =item substring A portion of a L</string>, starting at a certain L</character> position (L</offset>) and proceeding for a certain number of characters. =item superclass See L</base class>. =item superuser The person whom the L</operating system> will let do almost anything. Typically your system administrator or someone pretending to be your system administrator. On Unix systems, the L</root> user. On Windows systems, usually the Administrator user. =item SV Short for "scalar value". But within the Perl interpreter every L</referent> is treated as a member of a class derived from SV, in an object-oriented sort of way. Every L</value> inside Perl is passed around as a C language C<SV*> pointer. The SV L</struct> knows its own "referent type", and the code is smart enough (we hope) not to try to call a L</hash> function on a L</subroutine>. =item switch An option you give on a command line to influence the way your program works, usually introduced with a minus sign. The word is also used as a nickname for a L</switch statement>. =item switch cluster The combination of multiple command-line switches (e.g., B<-a -b -c>) into one switch (e.g., B<-abc>). Any switch with an additional L</argument> must be the last switch in a cluster. =item switch statement A program technique that lets you evaluate an L</expression> and then, based on the value of the expression, do a multiway branch to the appropriate piece of code for that value. Also called a "case structure", named after the similar Pascal construct. See See L<perlsyn/Basic BLOCKs>. =item symbol Generally, any L</token> or L</metasymbol>. Often used more specifically to mean the sort of name you might find in a L</symbol table>. =item symbol table Where a L</compiler> remembers symbols. A program like Perl must somehow remember all the names of all the L<variables|/variable>, L<filehandles|/filehandle>, and L<subroutines|/subroutine> you've used. It does this by placing the names in a symbol table, which is implemented in Perl using a L</hash table>. There is a separate symbol table for each L</package> to give each package its own L</namespace>. =item symbolic debugger A program that lets you step through the L<execution|/execute> of your program, stopping or printing things out here and there to see whether anything has gone wrong, and if so, what. The "symbolic" part just means that you can talk to the debugger using the same symbols with which your program is written. =item symbolic link An alternate filename that points to the real L</filename>, which in turn points to the real L</file>. Whenever the L</operating system> is trying to parse a L</pathname> containing a symbolic link, it merely substitutes the new name and continues parsing. =item symbolic reference A variable whose value is the name of another variable or subroutine. By L<dereferencing|/dereference> the first variable, you can get at the second one. Symbolic references are illegal under L<use strict 'refs'|strict/strict refs>. =item synchronous Programming in which the orderly sequence of events can be determined; that is, when things happen one after the other, not at the same time. =item syntactic sugar An alternative way of writing something more easily; a shortcut. =item syntax From Greek, "with-arrangement". How things (particularly symbols) are put together with each other. =item syntax tree An internal representation of your program wherein lower-level L<constructs|/construct> dangle off the higher-level constructs enclosing them. =item syscall A L</function> call directly to the L</operating system>. Many of the important subroutines and functions you use aren't direct system calls, but are built up in one or more layers above the system call level. In general, Perl programmers don't need to worry about the distinction. However, if you do happen to know which Perl functions are really syscalls, you can predict which of these will set the C<$!> (C<$ERRNO>) variable on failure. Unfortunately, beginning programmers often confusingly employ the term "system call" to mean what happens when you call the Perl L<system|perlfunc/system> function, which actually involves many syscalls. To avoid any confusion, we nearly always use say "syscall" for something you could call indirectly via Perl's L<syscall|perlfunc/syscall> function, and never for something you would call with Perl's L<system|perlfunc/system> function. =back =head2 T =over 4 =item tainted Said of data derived from the grubby hands of a user and thus unsafe for a secure program to rely on. Perl does taint checks if you run a L</setuid> (or L</setgid>) program, or if you use the B<-T> switch. =item TCP Short for Transmission Control Protocol. A protocol wrapped around the Internet Protocol to make an unreliable packet transmission mechanism appear to the application program to be a reliable L</stream> of bytes. (Usually.) =item term Short for a "terminal", that is, a leaf node of a L</syntax tree>. A thing that functions grammatically as an L</operand> for the operators in an expression. =item terminator A L</character> or L</string> that marks the end of another string. The C<$/> variable contains the string that terminates a L<readline|perlfunc/readline> operation, which L<chomp|perlfunc/chomp> deletes from the end. Not to be confused with L<delimiters|/delimiter> or L<separators|/separator>. The period at the end of this sentence is a terminator. =item ternary An L</operator> taking three L<operands|/operand>. Sometimes pronounced L</trinary>. =item text A L</string> or L</file> containing primarily printable characters. =item thread Like a forked process, but without L</fork>'s inherent memory protection. A thread is lighter weight than a full process, in that a process could have multiple threads running around in it, all fighting over the same process's memory space unless steps are taken to protect threads from each other. See L<threads>. =item tie The bond between a magical variable and its implementation class. See L<perlfunc/tie> and L<perltie>. =item TMTOWTDI There's More Than One Way To Do It, the Perl Motto. The notion that there can be more than one valid path to solving a programming problem in context. (This doesn't mean that more ways are always better or that all possible paths are equally desirable--just that there need not be One True Way.) Pronounced TimToady. =item token A morpheme in a programming language, the smallest unit of text with semantic significance. =item tokener A module that breaks a program text into a sequence of L<tokens|/token> for later analysis by a parser. =item tokenizing Splitting up a program text into L<tokens|/token>. Also known as "lexing", in which case you get "lexemes" instead of tokens. =item toolbox approach The notion that, with a complete set of simple tools that work well together, you can build almost anything you want. Which is fine if you're assembling a tricycle, but if you're building a defranishizing comboflux regurgalator, you really want your own machine shop in which to build special tools. Perl is sort of a machine shop. =item transliterate To turn one string representation into another by mapping each character of the source string to its corresponding character in the result string. See L<perlop/trE<sol>SEARCHLISTE<sol>REPLACEMENTLISTE<sol>cdsr>. =item trigger An event that causes a L</handler> to be run. =item trinary Not a stellar system with three stars, but an L</operator> taking three L<operands|/operand>. Sometimes pronounced L</ternary>. =item troff A venerable typesetting language from which Perl derives the name of its C<$%> variable and which is secretly used in the production of Camel books. =item true Any scalar value that doesn't evaluate to 0 or C<"">. =item truncating Emptying a file of existing contents, either automatically when opening a file for writing or explicitly via the L<truncate|perlfunc/truncate> function. =item type See L</data type> and L</class>. =item type casting Converting data from one type to another. C permits this. Perl does not need it. Nor want it. =item typed lexical A L</lexical variable> that is declared with a L</class> type: C<my Pony $bill>. =item typedef A type definition in the C language. =item typeglob Use of a single identifier, prefixed with C<*>. For example, C<*name> stands for any or all of C<$name>, C<@name>, C<%name>, C<&name>, or just C<name>. How you use it determines whether it is interpreted as all or only one of them. See L<perldata/Typeglobs and Filehandles>. =item typemap A description of how C types may be transformed to and from Perl types within an L</extension> module written in L</XS>. =back =head2 U =over 4 =item UDP User Datagram Protocol, the typical way to send L<datagrams|/datagram> over the Internet. =item UID A user ID. Often used in the context of L</file> or L</process> ownership. =item umask A mask of those L</permission bits> that should be forced off when creating files or directories, in order to establish a policy of whom you'll ordinarily deny access to. See the L<umask|perlfunc/umask> function. =item unary operator An operator with only one L</operand>, like C<!> or L<chdir|perlfunc/chdir>. Unary operators are usually prefix operators; that is, they precede their operand. The C<++> and C<--> operators can be either prefix or postfix. (Their position I<does> change their meanings.) =item Unicode A character set comprising all the major character sets of the world, more or less. See L<perlunicode> and L<http://www.unicode.org>. =item Unix A very large and constantly evolving language with several alternative and largely incompatible syntaxes, in which anyone can define anything any way they choose, and usually do. Speakers of this language think it's easy to learn because it's so easily twisted to one's own ends, but dialectical differences make tribal intercommunication nearly impossible, and travelers are often reduced to a pidgin-like subset of the language. To be universally understood, a Unix shell programmer must spend years of study in the art. Many have abandoned this discipline and now communicate via an Esperanto-like language called Perl. In ancient times, Unix was also used to refer to some code that a couple of people at Bell Labs wrote to make use of a PDP-7 computer that wasn't doing much of anything else at the time. =back =head2 V =over 4 =item value An actual piece of data, in contrast to all the variables, references, keys, indexes, operators, and whatnot that you need to access the value. =item variable A named storage location that can hold any of various kinds of L</value>, as your program sees fit. =item variable interpolation The L</interpolation> of a scalar or array variable into a string. =item variadic Said of a L</function> that happily receives an indeterminate number of L</actual arguments>. =item vector Mathematical jargon for a list of L<scalar values|/scalar value>. =item virtual Providing the appearance of something without the reality, as in: virtual memory is not real memory. (See also L</memory>.) The opposite of "virtual" is "transparent", which means providing the reality of something without the appearance, as in: Perl handles the variable-length UTF-8 character encoding transparently. =item void context A form of L</scalar context> in which an L</expression> is not expected to return any L</value> at all and is evaluated for its L</side effects> alone. =item v-string A "version" or "vector" L</string> specified with a C<v> followed by a series of decimal integers in dot notation, for instance, C<v1.20.300.4000>. Each number turns into a L</character> with the specified ordinal value. (The C<v> is optional when there are at least three integers.) =back =head2 W =over 4 =item warning A message printed to the L</STDERR> stream to the effect that something might be wrong but isn't worth blowing up over. See L<perlfunc/warn> and the L<warnings> pragma. =item watch expression An expression which, when its value changes, causes a breakpoint in the Perl debugger. =item whitespace A L</character> that moves your cursor but doesn't otherwise put anything on your screen. Typically refers to any of: space, tab, line feed, carriage return, or form feed. =item word In normal "computerese", the piece of data of the size most efficiently handled by your computer, typically 32 bits or so, give or take a few powers of 2. In Perl culture, it more often refers to an alphanumeric L</identifier> (including underscores), or to a string of nonwhitespace L<characters|/character> bounded by whitespace or string boundaries. =item working directory Your current L</directory>, from which relative pathnames are interpreted by the L</operating system>. The operating system knows your current directory because you told it with a L<chdir|perlfunc/chdir> or because you started out in the place where your parent L</process> was when you were born. =item wrapper A program or subroutine that runs some other program or subroutine for you, modifying some of its input or output to better suit your purposes. =item WYSIWYG What You See Is What You Get. Usually used when something that appears on the screen matches how it will eventually look, like Perl's L<format|perlfunc/format> declarations. Also used to mean the opposite of magic because everything works exactly as it appears, as in the three-argument form of L<open|perlfunc/open>. =back =head2 X =over 4 =item XS A language to extend Perl with L<C> and C++. XS is an interface description file format used to create an extension interface between Perl and C code (or a C library) which one wishes to use with Perl. See L<perlxs> for the exact explanation or read the L<perlxstut> tutorial. =item XSUB An external L</subroutine> defined in L</XS>. =back =head2 Y =over 4 =item yacc Yet Another Compiler Compiler. A parser generator without which Perl probably would not have existed. See the file I<perly.y> in the Perl source distribution. =back =head2 Z =over 4 =item zero width A subpattern L</assertion> matching the L</null string> between L<characters|/character>. =item zombie A process that has died (exited) but whose parent has not yet received proper notification of its demise by virtue of having called L<wait|perlfunc/wait> or L<waitpid|perlfunc/waitpid>. If you L<fork|perlfunc/fork>, you must clean up after your child processes when they exit, or else the process table will fill up and your system administrator will Not Be Happy with you. =back =head1 AUTHOR AND COPYRIGHT Based on the Glossary of Programming Perl, Third Edition, by Larry Wall, Tom Christiansen & Jon Orwant. Copyright (c) 2000, 1996, 1991 O'Reilly Media, Inc. This document may be distributed under the same terms as Perl itself. PK PU�\�,��: �: perlfaq9.podnu �[��� =head1 NAME perlfaq9 - Web, Email and Networking =head1 DESCRIPTION This section deals with questions related to running web sites, sending and receiving email as well as general networking. =head2 Should I use a web framework? Yes. If you are building a web site with any level of interactivity (forms / users / databases), you will want to use a framework to make handling requests and responses easier. If there is no interactivity then you may still want to look at using something like L<Template Toolkit|https://metacpan.org/module/Template> or L<Plack::Middleware::TemplateToolkit> so maintenance of your HTML files (and other assets) is easier. =head2 Which web framework should I use? X<framework> X<CGI.pm> X<CGI> X<Catalyst> X<Dancer> There is no simple answer to this question. Perl frameworks can run everything from basic file servers and small scale intranets to massive multinational multilingual websites that are the core to international businesses. Below is a list of a few frameworks with comments which might help you in making a decision, depending on your specific requirements. Start by reading the docs, then ask questions on the relevant mailing list or IRC channel. =over 4 =item L<Catalyst> Strongly object-oriented and fully-featured with a long development history and a large community and addon ecosystem. It is excellent for large and complex applications, where you have full control over the server. =item L<Dancer> Young and free of legacy weight, providing a lightweight and easy to learn API. Has a growing addon ecosystem. It is best used for smaller projects and very easy to learn for beginners. =item L<Mojolicious> Fairly young with a focus on HTML5 and real-time web technologies such as WebSockets. =item L<Web::Simple> Currently experimental, strongly object-oriented, built for speed and intended as a toolkit for building micro web apps, custom frameworks or for tieing together existing Plack-compatible web applications with one central dispatcher. =back All of these interact with or use L<Plack> which is worth understanding the basics of when building a website in Perl (there is a lot of useful L<Plack::Middleware|https://metacpan.org/search?q=plack%3A%3Amiddleware>). =head2 What is Plack and PSGI? L<PSGI> is the Perl Web Server Gateway Interface Specification, it is a standard that many Perl web frameworks use, you should not need to understand it to build a web site, the part you might want to use is L<Plack>. L<Plack> is a set of tools for using the PSGI stack. It contains L<middleware|https://metacpan.org/search?q=plack%3A%3Amiddleware> components, a reference server and utilities for Web application frameworks. Plack is like Ruby's Rack or Python's Paste for WSGI. You could build a web site using L<Plack> and your own code, but for anything other than a very basic web site, using a web framework (that uses L<Plack>) is a better option. =head2 How do I remove HTML from a string? Use L<HTML::Strip>, or L<HTML::FormatText> which not only removes HTML but also attempts to do a little simple formatting of the resulting plain text. =head2 How do I extract URLs? L<HTML::SimpleLinkExtor> will extract URLs from HTML, it handles anchors, images, objects, frames, and many other tags that can contain a URL. If you need anything more complex, you can create your own subclass of L<HTML::LinkExtor> or L<HTML::Parser>. You might even use L<HTML::SimpleLinkExtor> as an example for something specifically suited to your needs. You can use L<URI::Find> to extract URLs from an arbitrary text document. =head2 How do I fetch an HTML file? (contributed by brian d foy) Use the libwww-perl distribution. The L<LWP::Simple> module can fetch web resources and give their content back to you as a string: use LWP::Simple qw(get); my $html = get( "http://www.example.com/index.html" ); It can also store the resource directly in a file: use LWP::Simple qw(getstore); getstore( "http://www.example.com/index.html", "foo.html" ); If you need to do something more complicated, you can use L<LWP::UserAgent> module to create your own user-agent (e.g. browser) to get the job done. If you want to simulate an interactive web browser, you can use the L<WWW::Mechanize> module. =head2 How do I automate an HTML form submission? If you are doing something complex, such as moving through many pages and forms or a web site, you can use L<WWW::Mechanize>. See its documentation for all the details. If you're submitting values using the GET method, create a URL and encode the form using the C<query_form> method: use LWP::Simple; use URI::URL; my $url = url('L<http://www.perl.com/cgi-bin/cpan_mod')>; $url->query_form(module => 'DB_File', readme => 1); $content = get($url); If you're using the POST method, create your own user agent and encode the content appropriately. use HTTP::Request::Common qw(POST); use LWP::UserAgent; my $ua = LWP::UserAgent->new(); my $req = POST 'L<http://www.perl.com/cgi-bin/cpan_mod'>, [ module => 'DB_File', readme => 1 ]; my $content = $ua->request($req)->as_string; =head2 How do I decode or create those %-encodings on the web? X<URI> X<URI::Escape> X<RFC 2396> Most of the time you should not need to do this as your web framework, or if you are making a request, the L<LWP> or other module would handle it for you. To encode a string yourself, use the L<URI::Escape> module. The C<uri_escape> function returns the escaped string: my $original = "Colon : Hash # Percent %"; my $escaped = uri_escape( $original ); print "$escaped\n"; # 'Colon%20%3A%20Hash%20%23%20Percent%20%25' To decode the string, use the C<uri_unescape> function: my $unescaped = uri_unescape( $escaped ); print $unescaped; # back to original Remember not to encode a full URI, you need to escape each component separately and then join them together. =head2 How do I redirect to another page? Most Perl Web Frameworks will have a mechanism for doing this, using the L<Catalyst> framework it would be: $c->res->redirect($url); $c->detach(); If you are using Plack (which most frameworks do), then L<Plack::Middleware::Rewrite> is worth looking at if you are migrating from Apache or have URL's you want to always redirect. =head2 How do I put a password on my web pages? See if the web framework you are using has an authentication system and if that fits your needs. Alternativly look at L<Plack::Middleware::Auth::Basic>, or one of the other L<Plack authentication|https://metacpan.org/search?q=plack+auth> options. =head2 How do I make sure users can't enter values into a form that causes my CGI script to do bad things? (contributed by brian d foy) You can't prevent people from sending your script bad data. Even if you add some client-side checks, people may disable them or bypass them completely. For instance, someone might use a module such as L<LWP> to submit to your web site. If you want to prevent data that try to use SQL injection or other sorts of attacks (and you should want to), you have to not trust any data that enter your program. The L<perlsec> documentation has general advice about data security. If you are using the L<DBI> module, use placeholder to fill in data. If you are running external programs with C<system> or C<exec>, use the list forms. There are many other precautions that you should take, too many to list here, and most of them fall under the category of not using any data that you don't intend to use. Trust no one. =head2 How do I parse a mail header? Use the L<Email::MIME> module. It's well-tested and supports all the craziness that you'll see in the real world (comment-folding whitespace, encodings, comments, etc.). use Email::MIME; my $message = Email::MIME->new($rfc2822); my $subject = $message->header('Subject'); my $from = $message->header('From'); If you've already got some other kind of email object, consider passing it to L<Email::Abstract> and then using its cast method to get an L<Email::MIME> object: my $mail_message_object = read_message(); my $abstract = Email::Abstract->new($mail_message_object); my $email_mime_object = $abstract->cast('Email::MIME'); =head2 How do I check a valid mail address? (partly contributed by Aaron Sherman) This isn't as simple a question as it sounds. There are two parts: a) How do I verify that an email address is correctly formatted? b) How do I verify that an email address targets a valid recipient? Without sending mail to the address and seeing whether there's a human on the other end to answer you, you cannot fully answer part I<b>, but the L<Email::Valid> module will do both part I<a> and part I<b> as far as you can in real-time. Our best advice for verifying a person's mail address is to have them enter their address twice, just as you normally do to change a password. This usually weeds out typos. If both versions match, send mail to that address with a personal message. If you get the message back and they've followed your directions, you can be reasonably assured that it's real. A related strategy that's less open to forgery is to give them a PIN (personal ID number). Record the address and PIN (best that it be a random one) for later processing. In the mail you send, include a link to your site with the PIN included. If the mail bounces, you know it's not valid. If they don't click on the link, either they forged the address or (assuming they got the message) following through wasn't important so you don't need to worry about it. =head2 How do I decode a MIME/BASE64 string? The L<MIME::Base64> package handles this as well as the MIME/QP encoding. Decoding base 64 becomes as simple as: use MIME::Base64; my $decoded = decode_base64($encoded); The L<Email::MIME> module can decode base 64-encoded email message parts transparently so the developer doesn't need to worry about it. =head2 How do I find the user's mail address? Ask them for it. There are so many email providers available that it's unlikely the local system has any idea how to determine a user's email address. The exception is for organization-specific email (e.g. foo@yourcompany.com) where policy can be codified in your program. In that case, you could look at $ENV{USER}, $ENV{LOGNAME}, and getpwuid($<) in scalar context, like so: my $user_name = getpwuid($<) But you still cannot make assumptions about whether this is correct, unless your policy says it is. You really are best off asking the user. =head2 How do I send email? Use the L<Email::MIME> and L<Email::Sender::Simple> modules, like so: # first, create your message my $message = Email::MIME->create( header_str => [ From => 'you@example.com', To => 'friend@example.com', Subject => 'Happy birthday!', ], attributes => { encoding => 'quoted-printable', charset => 'ISO-8859-1', }, body_str => "Happy birthday to you!\n", ); use Email::Sender::Simple qw(sendmail); sendmail($message); By default, L<Email::Sender::Simple> will try `sendmail` first, if it exists in your $PATH. This generally isn't the case. If there's a remote mail server you use to send mail, consider investigating one of the Transport classes. At time of writing, the available transports include: =over 4 =item L<Email::Sender::Transport::Sendmail> This is the default. If you can use the L<mail(1)> or L<mailx(1)> program to send mail from the machine where your code runs, you should be able to use this. =item L<Email::Sender::Transport::SMTP> This transport contacts a remote SMTP server over TCP. It optionally uses SSL and can authenticate to the server via SASL. =item L<Email::Sender::Transport::SMTP::TLS> This is like the SMTP transport, but uses TLS security. You can authenticate with this module as well, using any mechanisms your server supports after STARTTLS. =back Telling L<Email::Sender::Simple> to use your transport is straightforward. sendmail( $message, { transport => $email_sender_transport_object, } ); =head2 How do I use MIME to make an attachment to a mail message? L<Email::MIME> directly supports multipart messages. L<Email::MIME> objects themselves are parts and can be attached to other L<Email::MIME> objects. Consult the L<Email::MIME> documentation for more information, including all of the supported methods and examples of their use. =head2 How do I read email? Use the L<Email::Folder> module, like so: use Email::Folder; my $folder = Email::Folder->new('/path/to/email/folder'); while(my $message = $folder->next_message) { # next_message returns Email::Simple objects, but we want # Email::MIME objects as they're more robust my $mime = Email::MIME->new($message->as_string); } There are different classes in the L<Email::Folder> namespace for supporting various mailbox types. Note that these modules are generally rather limited and only support B<reading> rather than writing. =head2 How do I find out my hostname, domainname, or IP address? X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa, gethostbyname, Socket, Net::Domain, Sys::Hostname> (contributed by brian d foy) The L<Net::Domain> module, which is part of the Standard Library starting in Perl 5.7.3, can get you the fully qualified domain name (FQDN), the host name, or the domain name. use Net::Domain qw(hostname hostfqdn hostdomain); my $host = hostfqdn(); The L<Sys::Hostname> module, part of the Standard Library, can also get the hostname: use Sys::Hostname; $host = hostname(); The L<Sys::Hostname::Long> module takes a different approach and tries harder to return the fully qualified hostname: use Sys::Hostname::Long 'hostname_long'; my $hostname = hostname_long(); To get the IP address, you can use the C<gethostbyname> built-in function to turn the name into a number. To turn that number into the dotted octet form (a.b.c.d) that most people expect, use the C<inet_ntoa> function from the L<Socket> module, which also comes with perl. use Socket; my $address = inet_ntoa( scalar gethostbyname( $host || 'localhost' ) ); =head2 How do I fetch/put an (S)FTP file? L<Net::FTP>, and L<Net::SFTP> allow you to interact with FTP and SFTP (Secure FTP) servers. =head2 How can I do RPC in Perl? Use one of the RPC modules( L<https://metacpan.org/search?q=RPC> ). =head1 AUTHOR AND COPYRIGHT Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved. This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. PK PU�\�y%ç � perlxs.podnu �[��� =head1 NAME perlxs - XS language reference manual =head1 DESCRIPTION =head2 Introduction XS is an interface description file format used to create an extension interface between Perl and C code (or a C library) which one wishes to use with Perl. The XS interface is combined with the library to create a new library which can then be either dynamically loaded or statically linked into perl. The XS interface description is written in the XS language and is the core component of the Perl extension interface. An B<XSUB> forms the basic unit of the XS interface. After compilation by the B<xsubpp> compiler, each XSUB amounts to a C function definition which will provide the glue between Perl calling conventions and C calling conventions. The glue code pulls the arguments from the Perl stack, converts these Perl values to the formats expected by a C function, call this C function, transfers the return values of the C function back to Perl. Return values here may be a conventional C return value or any C function arguments that may serve as output parameters. These return values may be passed back to Perl either by putting them on the Perl stack, or by modifying the arguments supplied from the Perl side. The above is a somewhat simplified view of what really happens. Since Perl allows more flexible calling conventions than C, XSUBs may do much more in practice, such as checking input parameters for validity, throwing exceptions (or returning undef/empty list) if the return value from the C function indicates failure, calling different C functions based on numbers and types of the arguments, providing an object-oriented interface, etc. Of course, one could write such glue code directly in C. However, this would be a tedious task, especially if one needs to write glue for multiple C functions, and/or one is not familiar enough with the Perl stack discipline and other such arcana. XS comes to the rescue here: instead of writing this glue C code in long-hand, one can write a more concise short-hand I<description> of what should be done by the glue, and let the XS compiler B<xsubpp> handle the rest. The XS language allows one to describe the mapping between how the C routine is used, and how the corresponding Perl routine is used. It also allows creation of Perl routines which are directly translated to C code and which are not related to a pre-existing C function. In cases when the C interface coincides with the Perl interface, the XSUB declaration is almost identical to a declaration of a C function (in K&R style). In such circumstances, there is another tool called C<h2xs> that is able to translate an entire C header file into a corresponding XS file that will provide glue to the functions/macros described in the header file. The XS compiler is called B<xsubpp>. This compiler creates the constructs necessary to let an XSUB manipulate Perl values, and creates the glue necessary to let Perl call the XSUB. The compiler uses B<typemaps> to determine how to map C function parameters and output values to Perl values and back. The default typemap (which comes with Perl) handles many common C types. A supplementary typemap may also be needed to handle any special structures and types for the library being linked. For more information on typemaps, see L<perlxstypemap>. A file in XS format starts with a C language section which goes until the first C<MODULE =Z<>> directive. Other XS directives and XSUB definitions may follow this line. The "language" used in this part of the file is usually referred to as the XS language. B<xsubpp> recognizes and skips POD (see L<perlpod>) in both the C and XS language sections, which allows the XS file to contain embedded documentation. See L<perlxstut> for a tutorial on the whole extension creation process. Note: For some extensions, Dave Beazley's SWIG system may provide a significantly more convenient mechanism for creating the extension glue code. See L<http://www.swig.org/> for more information. =head2 On The Road Many of the examples which follow will concentrate on creating an interface between Perl and the ONC+ RPC bind library functions. The rpcb_gettime() function is used to demonstrate many features of the XS language. This function has two parameters; the first is an input parameter and the second is an output parameter. The function also returns a status value. bool_t rpcb_gettime(const char *host, time_t *timep); From C this function will be called with the following statements. #include <rpc/rpc.h> bool_t status; time_t timep; status = rpcb_gettime( "localhost", &timep ); If an XSUB is created to offer a direct translation between this function and Perl, then this XSUB will be used from Perl with the following code. The $status and $timep variables will contain the output of the function. use RPC; $status = rpcb_gettime( "localhost", $timep ); The following XS file shows an XS subroutine, or XSUB, which demonstrates one possible interface to the rpcb_gettime() function. This XSUB represents a direct translation between C and Perl and so preserves the interface even from Perl. This XSUB will be invoked from Perl with the usage shown above. Note that the first three #include statements, for C<EXTERN.h>, C<perl.h>, and C<XSUB.h>, will always be present at the beginning of an XS file. This approach and others will be expanded later in this document. #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include <rpc/rpc.h> MODULE = RPC PACKAGE = RPC bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep Any extension to Perl, including those containing XSUBs, should have a Perl module to serve as the bootstrap which pulls the extension into Perl. This module will export the extension's functions and variables to the Perl program and will cause the extension's XSUBs to be linked into Perl. The following module will be used for most of the examples in this document and should be used from Perl with the C<use> command as shown earlier. Perl modules are explained in more detail later in this document. package RPC; require Exporter; require DynaLoader; @ISA = qw(Exporter DynaLoader); @EXPORT = qw( rpcb_gettime ); bootstrap RPC; 1; Throughout this document a variety of interfaces to the rpcb_gettime() XSUB will be explored. The XSUBs will take their parameters in different orders or will take different numbers of parameters. In each case the XSUB is an abstraction between Perl and the real C rpcb_gettime() function, and the XSUB must always ensure that the real rpcb_gettime() function is called with the correct parameters. This abstraction will allow the programmer to create a more Perl-like interface to the C function. =head2 The Anatomy of an XSUB The simplest XSUBs consist of 3 parts: a description of the return value, the name of the XSUB routine and the names of its arguments, and a description of types or formats of the arguments. The following XSUB allows a Perl program to access a C library function called sin(). The XSUB will imitate the C function which takes a single argument and returns a single value. double sin(x) double x Optionally, one can merge the description of types and the list of argument names, rewriting this as double sin(double x) This makes this XSUB look similar to an ANSI C declaration. An optional semicolon is allowed after the argument list, as in double sin(double x); Parameters with C pointer types can have different semantic: C functions with similar declarations bool string_looks_as_a_number(char *s); bool make_char_uppercase(char *c); are used in absolutely incompatible manner. Parameters to these functions could be described B<xsubpp> like this: char * s char &c Both these XS declarations correspond to the C<char*> C type, but they have different semantics, see L<"The & Unary Operator">. It is convenient to think that the indirection operator C<*> should be considered as a part of the type and the address operator C<&> should be considered part of the variable. See L<perlxstypemap> for more info about handling qualifiers and unary operators in C types. The function name and the return type must be placed on separate lines and should be flush left-adjusted. INCORRECT CORRECT double sin(x) double double x sin(x) double x The rest of the function description may be indented or left-adjusted. The following example shows a function with its body left-adjusted. Most examples in this document will indent the body for better readability. CORRECT double sin(x) double x More complicated XSUBs may contain many other sections. Each section of an XSUB starts with the corresponding keyword, such as INIT: or CLEANUP:. However, the first two lines of an XSUB always contain the same data: descriptions of the return type and the names of the function and its parameters. Whatever immediately follows these is considered to be an INPUT: section unless explicitly marked with another keyword. (See L<The INPUT: Keyword>.) An XSUB section continues until another section-start keyword is found. =head2 The Argument Stack The Perl argument stack is used to store the values which are sent as parameters to the XSUB and to store the XSUB's return value(s). In reality all Perl functions (including non-XSUB ones) keep their values on this stack all the same time, each limited to its own range of positions on the stack. In this document the first position on that stack which belongs to the active function will be referred to as position 0 for that function. XSUBs refer to their stack arguments with the macro B<ST(x)>, where I<x> refers to a position in this XSUB's part of the stack. Position 0 for that function would be known to the XSUB as ST(0). The XSUB's incoming parameters and outgoing return values always begin at ST(0). For many simple cases the B<xsubpp> compiler will generate the code necessary to handle the argument stack by embedding code fragments found in the typemaps. In more complex cases the programmer must supply the code. =head2 The RETVAL Variable The RETVAL variable is a special C variable that is declared automatically for you. The C type of RETVAL matches the return type of the C library function. The B<xsubpp> compiler will declare this variable in each XSUB with non-C<void> return type. By default the generated C function will use RETVAL to hold the return value of the C library function being called. In simple cases the value of RETVAL will be placed in ST(0) of the argument stack where it can be received by Perl as the return value of the XSUB. If the XSUB has a return type of C<void> then the compiler will not declare a RETVAL variable for that function. When using a PPCODE: section no manipulation of the RETVAL variable is required, the section may use direct stack manipulation to place output values on the stack. If PPCODE: directive is not used, C<void> return value should be used only for subroutines which do not return a value, I<even if> CODE: directive is used which sets ST(0) explicitly. Older versions of this document recommended to use C<void> return value in such cases. It was discovered that this could lead to segfaults in cases when XSUB was I<truly> C<void>. This practice is now deprecated, and may be not supported at some future version. Use the return value C<SV *> in such cases. (Currently C<xsubpp> contains some heuristic code which tries to disambiguate between "truly-void" and "old-practice-declared-as-void" functions. Hence your code is at mercy of this heuristics unless you use C<SV *> as return value.) =head2 Returning SVs, AVs and HVs through RETVAL When you're using RETVAL to return an C<SV *>, there's some magic going on behind the scenes that should be mentioned. When you're manipulating the argument stack using the ST(x) macro, for example, you usually have to pay special attention to reference counts. (For more about reference counts, see L<perlguts>.) To make your life easier, the typemap file automatically makes C<RETVAL> mortal when you're returning an C<SV *>. Thus, the following two XSUBs are more or less equivalent: void alpha() PPCODE: ST(0) = newSVpv("Hello World",0); sv_2mortal(ST(0)); XSRETURN(1); SV * beta() CODE: RETVAL = newSVpv("Hello World",0); OUTPUT: RETVAL This is quite useful as it usually improves readability. While this works fine for an C<SV *>, it's unfortunately not as easy to have C<AV *> or C<HV *> as a return value. You I<should> be able to write: AV * array() CODE: RETVAL = newAV(); /* do something with RETVAL */ OUTPUT: RETVAL But due to an unfixable bug (fixing it would break lots of existing CPAN modules) in the typemap file, the reference count of the C<AV *> is not properly decremented. Thus, the above XSUB would leak memory whenever it is being called. The same problem exists for C<HV *>, C<CV *>, and C<SVREF> (which indicates a scalar reference, not a general C<SV *>). In XS code on perls starting with perl 5.16, you can override the typemaps for any of these types with a version that has proper handling of refcounts. In your C<TYPEMAP> section, do AV* T_AVREF_REFCOUNT_FIXED to get the repaired variant. For backward compatibility with older versions of perl, you can instead decrement the reference count manually when you're returning one of the aforementioned types using C<sv_2mortal>: AV * array() CODE: RETVAL = newAV(); sv_2mortal((SV*)RETVAL); /* do something with RETVAL */ OUTPUT: RETVAL Remember that you don't have to do this for an C<SV *>. The reference documentation for all core typemaps can be found in L<perlxstypemap>. =head2 The MODULE Keyword The MODULE keyword is used to start the XS code and to specify the package of the functions which are being defined. All text preceding the first MODULE keyword is considered C code and is passed through to the output with POD stripped, but otherwise untouched. Every XS module will have a bootstrap function which is used to hook the XSUBs into Perl. The package name of this bootstrap function will match the value of the last MODULE statement in the XS source files. The value of MODULE should always remain constant within the same XS file, though this is not required. The following example will start the XS code and will place all functions in a package named RPC. MODULE = RPC =head2 The PACKAGE Keyword When functions within an XS source file must be separated into packages the PACKAGE keyword should be used. This keyword is used with the MODULE keyword and must follow immediately after it when used. MODULE = RPC PACKAGE = RPC [ XS code in package RPC ] MODULE = RPC PACKAGE = RPCB [ XS code in package RPCB ] MODULE = RPC PACKAGE = RPC [ XS code in package RPC ] The same package name can be used more than once, allowing for non-contiguous code. This is useful if you have a stronger ordering principle than package names. Although this keyword is optional and in some cases provides redundant information it should always be used. This keyword will ensure that the XSUBs appear in the desired package. =head2 The PREFIX Keyword The PREFIX keyword designates prefixes which should be removed from the Perl function names. If the C function is C<rpcb_gettime()> and the PREFIX value is C<rpcb_> then Perl will see this function as C<gettime()>. This keyword should follow the PACKAGE keyword when used. If PACKAGE is not used then PREFIX should follow the MODULE keyword. MODULE = RPC PREFIX = rpc_ MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_ =head2 The OUTPUT: Keyword The OUTPUT: keyword indicates that certain function parameters should be updated (new values made visible to Perl) when the XSUB terminates or that certain values should be returned to the calling Perl function. For simple functions which have no CODE: or PPCODE: section, such as the sin() function above, the RETVAL variable is automatically designated as an output value. For more complex functions the B<xsubpp> compiler will need help to determine which variables are output variables. This keyword will normally be used to complement the CODE: keyword. The RETVAL variable is not recognized as an output variable when the CODE: keyword is present. The OUTPUT: keyword is used in this situation to tell the compiler that RETVAL really is an output variable. The OUTPUT: keyword can also be used to indicate that function parameters are output variables. This may be necessary when a parameter has been modified within the function and the programmer would like the update to be seen by Perl. bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep The OUTPUT: keyword will also allow an output parameter to be mapped to a matching piece of code rather than to a typemap. bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep sv_setnv(ST(1), (double)timep); B<xsubpp> emits an automatic C<SvSETMAGIC()> for all parameters in the OUTPUT section of the XSUB, except RETVAL. This is the usually desired behavior, as it takes care of properly invoking 'set' magic on output parameters (needed for hash or array element parameters that must be created if they didn't exist). If for some reason, this behavior is not desired, the OUTPUT section may contain a C<SETMAGIC: DISABLE> line to disable it for the remainder of the parameters in the OUTPUT section. Likewise, C<SETMAGIC: ENABLE> can be used to reenable it for the remainder of the OUTPUT section. See L<perlguts> for more details about 'set' magic. =head2 The NO_OUTPUT Keyword The NO_OUTPUT can be placed as the first token of the XSUB. This keyword indicates that while the C subroutine we provide an interface to has a non-C<void> return type, the return value of this C subroutine should not be returned from the generated Perl subroutine. With this keyword present L<The RETVAL Variable> is created, and in the generated call to the subroutine this variable is assigned to, but the value of this variable is not going to be used in the auto-generated code. This keyword makes sense only if C<RETVAL> is going to be accessed by the user-supplied code. It is especially useful to make a function interface more Perl-like, especially when the C return value is just an error condition indicator. For example, NO_OUTPUT int delete_file(char *name) POSTCALL: if (RETVAL != 0) croak("Error %d while deleting file '%s'", RETVAL, name); Here the generated XS function returns nothing on success, and will die() with a meaningful error message on error. =head2 The CODE: Keyword This keyword is used in more complicated XSUBs which require special handling for the C function. The RETVAL variable is still declared, but it will not be returned unless it is specified in the OUTPUT: section. The following XSUB is for a C function which requires special handling of its parameters. The Perl usage is given first. $status = rpcb_gettime( "localhost", $timep ); The XSUB follows. bool_t rpcb_gettime(host,timep) char *host time_t timep CODE: RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL =head2 The INIT: Keyword The INIT: keyword allows initialization to be inserted into the XSUB before the compiler generates the call to the C function. Unlike the CODE: keyword above, this keyword does not affect the way the compiler handles RETVAL. bool_t rpcb_gettime(host,timep) char *host time_t &timep INIT: printf("# Host is %s\n", host ); OUTPUT: timep Another use for the INIT: section is to check for preconditions before making a call to the C function: long long lldiv(a,b) long long a long long b INIT: if (a == 0 && b == 0) XSRETURN_UNDEF; if (b == 0) croak("lldiv: cannot divide by 0"); =head2 The NO_INIT Keyword The NO_INIT keyword is used to indicate that a function parameter is being used only as an output value. The B<xsubpp> compiler will normally generate code to read the values of all function parameters from the argument stack and assign them to C variables upon entry to the function. NO_INIT will tell the compiler that some parameters will be used for output rather than for input and that they will be handled before the function terminates. The following example shows a variation of the rpcb_gettime() function. This function uses the timep variable only as an output variable and does not care about its initial contents. bool_t rpcb_gettime(host,timep) char *host time_t &timep = NO_INIT OUTPUT: timep =head2 The TYPEMAP: Keyword Starting with Perl 5.16, you can embed typemaps into your XS code instead of or in addition to typemaps in a separate file. Multiple such embedded typemaps will be processed in order of appearance in the XS code and like local typemap files take precendence over the default typemap, the embedded typemaps may overwrite previous definitions of TYPEMAP, INPUT, and OUTPUT stanzas. The syntax for embedded typemaps is TYPEMAP: <<HERE ... your typemap code here ... HERE where the C<TYPEMAP> keyword must appear in the first column of a new line. Refer to L<perlxstypemap> for details on writing typemaps. =head2 Initializing Function Parameters C function parameters are normally initialized with their values from the argument stack (which in turn contains the parameters that were passed to the XSUB from Perl). The typemaps contain the code segments which are used to translate the Perl values to the C parameters. The programmer, however, is allowed to override the typemaps and supply alternate (or additional) initialization code. Initialization code starts with the first C<=>, C<;> or C<+> on a line in the INPUT: section. The only exception happens if this C<;> terminates the line, then this C<;> is quietly ignored. The following code demonstrates how to supply initialization code for function parameters. The initialization code is eval'ed within double quotes by the compiler before it is added to the output so anything which should be interpreted literally [mainly C<$>, C<@>, or C<\\>] must be protected with backslashes. The variables C<$var>, C<$arg>, and C<$type> can be used as in typemaps. bool_t rpcb_gettime(host,timep) char *host = (char *)SvPV_nolen($arg); time_t &timep = 0; OUTPUT: timep This should not be used to supply default values for parameters. One would normally use this when a function parameter must be processed by another library function before it can be used. Default parameters are covered in the next section. If the initialization begins with C<=>, then it is output in the declaration for the input variable, replacing the initialization supplied by the typemap. If the initialization begins with C<;> or C<+>, then it is performed after all of the input variables have been declared. In the C<;> case the initialization normally supplied by the typemap is not performed. For the C<+> case, the declaration for the variable will include the initialization from the typemap. A global variable, C<%v>, is available for the truly rare case where information from one initialization is needed in another initialization. Here's a truly obscure example: bool_t rpcb_gettime(host,timep) time_t &timep; /* \$v{timep}=@{[$v{timep}=$arg]} */ char *host + SvOK($v{timep}) ? SvPV_nolen($arg) : NULL; OUTPUT: timep The construct C<\$v{timep}=@{[$v{timep}=$arg]}> used in the above example has a two-fold purpose: first, when this line is processed by B<xsubpp>, the Perl snippet C<$v{timep}=$arg> is evaluated. Second, the text of the evaluated snippet is output into the generated C file (inside a C comment)! During the processing of C<char *host> line, C<$arg> will evaluate to C<ST(0)>, and C<$v{timep}> will evaluate to C<ST(1)>. =head2 Default Parameter Values Default values for XSUB arguments can be specified by placing an assignment statement in the parameter list. The default value may be a number, a string or the special string C<NO_INIT>. Defaults should always be used on the right-most parameters only. To allow the XSUB for rpcb_gettime() to have a default host value the parameters to the XSUB could be rearranged. The XSUB will then call the real rpcb_gettime() function with the parameters in the correct order. This XSUB can be called from Perl with either of the following statements: $status = rpcb_gettime( $timep, $host ); $status = rpcb_gettime( $timep ); The XSUB will look like the code which follows. A CODE: block is used to call the real rpcb_gettime() function with the parameters in the correct order for that function. bool_t rpcb_gettime(timep,host="localhost") char *host time_t timep = NO_INIT CODE: RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL =head2 The PREINIT: Keyword The PREINIT: keyword allows extra variables to be declared immediately before or after the declarations of the parameters from the INPUT: section are emitted. If a variable is declared inside a CODE: section it will follow any typemap code that is emitted for the input parameters. This may result in the declaration ending up after C code, which is C syntax error. Similar errors may happen with an explicit C<;>-type or C<+>-type initialization of parameters is used (see L<"Initializing Function Parameters">). Declaring these variables in an INIT: section will not help. In such cases, to force an additional variable to be declared together with declarations of other variables, place the declaration into a PREINIT: section. The PREINIT: keyword may be used one or more times within an XSUB. The following examples are equivalent, but if the code is using complex typemaps then the first example is safer. bool_t rpcb_gettime(timep) time_t timep = NO_INIT PREINIT: char *host = "localhost"; CODE: RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL For this particular case an INIT: keyword would generate the same C code as the PREINIT: keyword. Another correct, but error-prone example: bool_t rpcb_gettime(timep) time_t timep = NO_INIT CODE: char *host = "localhost"; RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL Another way to declare C<host> is to use a C block in the CODE: section: bool_t rpcb_gettime(timep) time_t timep = NO_INIT CODE: { char *host = "localhost"; RETVAL = rpcb_gettime( host, &timep ); } OUTPUT: timep RETVAL The ability to put additional declarations before the typemap entries are processed is very handy in the cases when typemap conversions manipulate some global state: MyObject mutate(o) PREINIT: MyState st = global_state; INPUT: MyObject o; CLEANUP: reset_to(global_state, st); Here we suppose that conversion to C<MyObject> in the INPUT: section and from MyObject when processing RETVAL will modify a global variable C<global_state>. After these conversions are performed, we restore the old value of C<global_state> (to avoid memory leaks, for example). There is another way to trade clarity for compactness: INPUT sections allow declaration of C variables which do not appear in the parameter list of a subroutine. Thus the above code for mutate() can be rewritten as MyObject mutate(o) MyState st = global_state; MyObject o; CLEANUP: reset_to(global_state, st); and the code for rpcb_gettime() can be rewritten as bool_t rpcb_gettime(timep) time_t timep = NO_INIT char *host = "localhost"; C_ARGS: host, &timep OUTPUT: timep RETVAL =head2 The SCOPE: Keyword The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If enabled, the XSUB will invoke ENTER and LEAVE automatically. To support potentially complex type mappings, if a typemap entry used by an XSUB contains a comment like C</*scope*/> then scoping will be automatically enabled for that XSUB. To enable scoping: SCOPE: ENABLE To disable scoping: SCOPE: DISABLE =head2 The INPUT: Keyword The XSUB's parameters are usually evaluated immediately after entering the XSUB. The INPUT: keyword can be used to force those parameters to be evaluated a little later. The INPUT: keyword can be used multiple times within an XSUB and can be used to list one or more input variables. This keyword is used with the PREINIT: keyword. The following example shows how the input parameter C<timep> can be evaluated late, after a PREINIT. bool_t rpcb_gettime(host,timep) char *host PREINIT: time_t tt; INPUT: time_t timep CODE: RETVAL = rpcb_gettime( host, &tt ); timep = tt; OUTPUT: timep RETVAL The next example shows each input parameter evaluated late. bool_t rpcb_gettime(host,timep) PREINIT: time_t tt; INPUT: char *host PREINIT: char *h; INPUT: time_t timep CODE: h = host; RETVAL = rpcb_gettime( h, &tt ); timep = tt; OUTPUT: timep RETVAL Since INPUT sections allow declaration of C variables which do not appear in the parameter list of a subroutine, this may be shortened to: bool_t rpcb_gettime(host,timep) time_t tt; char *host; char *h = host; time_t timep; CODE: RETVAL = rpcb_gettime( h, &tt ); timep = tt; OUTPUT: timep RETVAL (We used our knowledge that input conversion for C<char *> is a "simple" one, thus C<host> is initialized on the declaration line, and our assignment C<h = host> is not performed too early. Otherwise one would need to have the assignment C<h = host> in a CODE: or INIT: section.) =head2 The IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT Keywords In the list of parameters for an XSUB, one can precede parameter names by the C<IN>/C<OUTLIST>/C<IN_OUTLIST>/C<OUT>/C<IN_OUT> keywords. C<IN> keyword is the default, the other keywords indicate how the Perl interface should differ from the C interface. Parameters preceded by C<OUTLIST>/C<IN_OUTLIST>/C<OUT>/C<IN_OUT> keywords are considered to be used by the C subroutine I<via pointers>. C<OUTLIST>/C<OUT> keywords indicate that the C subroutine does not inspect the memory pointed by this parameter, but will write through this pointer to provide additional return values. Parameters preceded by C<OUTLIST> keyword do not appear in the usage signature of the generated Perl function. Parameters preceded by C<IN_OUTLIST>/C<IN_OUT>/C<OUT> I<do> appear as parameters to the Perl function. With the exception of C<OUT>-parameters, these parameters are converted to the corresponding C type, then pointers to these data are given as arguments to the C function. It is expected that the C function will write through these pointers. The return list of the generated Perl function consists of the C return value from the function (unless the XSUB is of C<void> return type or C<The NO_OUTPUT Keyword> was used) followed by all the C<OUTLIST> and C<IN_OUTLIST> parameters (in the order of appearance). On the return from the XSUB the C<IN_OUT>/C<OUT> Perl parameter will be modified to have the values written by the C function. For example, an XSUB void day_month(OUTLIST day, IN unix_time, OUTLIST month) int day int unix_time int month should be used from Perl as my ($day, $month) = day_month(time); The C signature of the corresponding function should be void day_month(int *day, int unix_time, int *month); The C<IN>/C<OUTLIST>/C<IN_OUTLIST>/C<IN_OUT>/C<OUT> keywords can be mixed with ANSI-style declarations, as in void day_month(OUTLIST int day, int unix_time, OUTLIST int month) (here the optional C<IN> keyword is omitted). The C<IN_OUT> parameters are identical with parameters introduced with L<The & Unary Operator> and put into the C<OUTPUT:> section (see L<The OUTPUT: Keyword>). The C<IN_OUTLIST> parameters are very similar, the only difference being that the value C function writes through the pointer would not modify the Perl parameter, but is put in the output list. The C<OUTLIST>/C<OUT> parameter differ from C<IN_OUTLIST>/C<IN_OUT> parameters only by the initial value of the Perl parameter not being read (and not being given to the C function - which gets some garbage instead). For example, the same C function as above can be interfaced with as void day_month(OUT int day, int unix_time, OUT int month); or void day_month(day, unix_time, month) int &day = NO_INIT int unix_time int &month = NO_INIT OUTPUT: day month However, the generated Perl function is called in very C-ish style: my ($day, $month); day_month($day, time, $month); =head2 The C<length(NAME)> Keyword If one of the input arguments to the C function is the length of a string argument C<NAME>, one can substitute the name of the length-argument by C<length(NAME)> in the XSUB declaration. This argument must be omitted when the generated Perl function is called. E.g., void dump_chars(char *s, short l) { short n = 0; while (n < l) { printf("s[%d] = \"\\%#03o\"\n", n, (int)s[n]); n++; } } MODULE = x PACKAGE = x void dump_chars(char *s, short length(s)) should be called as C<dump_chars($string)>. This directive is supported with ANSI-type function declarations only. =head2 Variable-length Parameter Lists XSUBs can have variable-length parameter lists by specifying an ellipsis C<(...)> in the parameter list. This use of the ellipsis is similar to that found in ANSI C. The programmer is able to determine the number of arguments passed to the XSUB by examining the C<items> variable which the B<xsubpp> compiler supplies for all XSUBs. By using this mechanism one can create an XSUB which accepts a list of parameters of unknown length. The I<host> parameter for the rpcb_gettime() XSUB can be optional so the ellipsis can be used to indicate that the XSUB will take a variable number of parameters. Perl should be able to call this XSUB with either of the following statements. $status = rpcb_gettime( $timep, $host ); $status = rpcb_gettime( $timep ); The XS code, with ellipsis, follows. bool_t rpcb_gettime(timep, ...) time_t timep = NO_INIT PREINIT: char *host = "localhost"; CODE: if( items > 1 ) host = (char *)SvPV_nolen(ST(1)); RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL =head2 The C_ARGS: Keyword The C_ARGS: keyword allows creating of XSUBS which have different calling sequence from Perl than from C, without a need to write CODE: or PPCODE: section. The contents of the C_ARGS: paragraph is put as the argument to the called C function without any change. For example, suppose that a C function is declared as symbolic nth_derivative(int n, symbolic function, int flags); and that the default flags are kept in a global C variable C<default_flags>. Suppose that you want to create an interface which is called as $second_deriv = $function->nth_derivative(2); To do this, declare the XSUB as symbolic nth_derivative(function, n) symbolic function int n C_ARGS: n, function, default_flags =head2 The PPCODE: Keyword The PPCODE: keyword is an alternate form of the CODE: keyword and is used to tell the B<xsubpp> compiler that the programmer is supplying the code to control the argument stack for the XSUBs return values. Occasionally one will want an XSUB to return a list of values rather than a single value. In these cases one must use PPCODE: and then explicitly push the list of values on the stack. The PPCODE: and CODE: keywords should not be used together within the same XSUB. The actual difference between PPCODE: and CODE: sections is in the initialization of C<SP> macro (which stands for the I<current> Perl stack pointer), and in the handling of data on the stack when returning from an XSUB. In CODE: sections SP preserves the value which was on entry to the XSUB: SP is on the function pointer (which follows the last parameter). In PPCODE: sections SP is moved backward to the beginning of the parameter list, which allows C<PUSH*()> macros to place output values in the place Perl expects them to be when the XSUB returns back to Perl. The generated trailer for a CODE: section ensures that the number of return values Perl will see is either 0 or 1 (depending on the C<void>ness of the return value of the C function, and heuristics mentioned in L<"The RETVAL Variable">). The trailer generated for a PPCODE: section is based on the number of return values and on the number of times C<SP> was updated by C<[X]PUSH*()> macros. Note that macros C<ST(i)>, C<XST_m*()> and C<XSRETURN*()> work equally well in CODE: sections and PPCODE: sections. The following XSUB will call the C rpcb_gettime() function and will return its two output values, timep and status, to Perl as a single list. void rpcb_gettime(host) char *host PREINIT: time_t timep; bool_t status; PPCODE: status = rpcb_gettime( host, &timep ); EXTEND(SP, 2); PUSHs(sv_2mortal(newSViv(status))); PUSHs(sv_2mortal(newSViv(timep))); Notice that the programmer must supply the C code necessary to have the real rpcb_gettime() function called and to have the return values properly placed on the argument stack. The C<void> return type for this function tells the B<xsubpp> compiler that the RETVAL variable is not needed or used and that it should not be created. In most scenarios the void return type should be used with the PPCODE: directive. The EXTEND() macro is used to make room on the argument stack for 2 return values. The PPCODE: directive causes the B<xsubpp> compiler to create a stack pointer available as C<SP>, and it is this pointer which is being used in the EXTEND() macro. The values are then pushed onto the stack with the PUSHs() macro. Now the rpcb_gettime() function can be used from Perl with the following statement. ($status, $timep) = rpcb_gettime("localhost"); When handling output parameters with a PPCODE section, be sure to handle 'set' magic properly. See L<perlguts> for details about 'set' magic. =head2 Returning Undef And Empty Lists Occasionally the programmer will want to return simply C<undef> or an empty list if a function fails rather than a separate status value. The rpcb_gettime() function offers just this situation. If the function succeeds we would like to have it return the time and if it fails we would like to have undef returned. In the following Perl code the value of $timep will either be undef or it will be a valid time. $timep = rpcb_gettime( "localhost" ); The following XSUB uses the C<SV *> return type as a mnemonic only, and uses a CODE: block to indicate to the compiler that the programmer has supplied all the necessary code. The sv_newmortal() call will initialize the return value to undef, making that the default return value. SV * rpcb_gettime(host) char * host PREINIT: time_t timep; bool_t x; CODE: ST(0) = sv_newmortal(); if( rpcb_gettime( host, &timep ) ) sv_setnv( ST(0), (double)timep); The next example demonstrates how one would place an explicit undef in the return value, should the need arise. SV * rpcb_gettime(host) char * host PREINIT: time_t timep; bool_t x; CODE: if( rpcb_gettime( host, &timep ) ){ ST(0) = sv_newmortal(); sv_setnv( ST(0), (double)timep); } else{ ST(0) = &PL_sv_undef; } To return an empty list one must use a PPCODE: block and then not push return values on the stack. void rpcb_gettime(host) char *host PREINIT: time_t timep; PPCODE: if( rpcb_gettime( host, &timep ) ) PUSHs(sv_2mortal(newSViv(timep))); else{ /* Nothing pushed on stack, so an empty * list is implicitly returned. */ } Some people may be inclined to include an explicit C<return> in the above XSUB, rather than letting control fall through to the end. In those situations C<XSRETURN_EMPTY> should be used, instead. This will ensure that the XSUB stack is properly adjusted. Consult L<perlapi> for other C<XSRETURN> macros. Since C<XSRETURN_*> macros can be used with CODE blocks as well, one can rewrite this example as: int rpcb_gettime(host) char *host PREINIT: time_t timep; CODE: RETVAL = rpcb_gettime( host, &timep ); if (RETVAL == 0) XSRETURN_UNDEF; OUTPUT: RETVAL In fact, one can put this check into a POSTCALL: section as well. Together with PREINIT: simplifications, this leads to: int rpcb_gettime(host) char *host time_t timep; POSTCALL: if (RETVAL == 0) XSRETURN_UNDEF; =head2 The REQUIRE: Keyword The REQUIRE: keyword is used to indicate the minimum version of the B<xsubpp> compiler needed to compile the XS module. An XS module which contains the following statement will compile with only B<xsubpp> version 1.922 or greater: REQUIRE: 1.922 =head2 The CLEANUP: Keyword This keyword can be used when an XSUB requires special cleanup procedures before it terminates. When the CLEANUP: keyword is used it must follow any CODE:, PPCODE:, or OUTPUT: blocks which are present in the XSUB. The code specified for the cleanup block will be added as the last statements in the XSUB. =head2 The POSTCALL: Keyword This keyword can be used when an XSUB requires special procedures executed after the C subroutine call is performed. When the POSTCALL: keyword is used it must precede OUTPUT: and CLEANUP: blocks which are present in the XSUB. See examples in L<"The NO_OUTPUT Keyword"> and L<"Returning Undef And Empty Lists">. The POSTCALL: block does not make a lot of sense when the C subroutine call is supplied by user by providing either CODE: or PPCODE: section. =head2 The BOOT: Keyword The BOOT: keyword is used to add code to the extension's bootstrap function. The bootstrap function is generated by the B<xsubpp> compiler and normally holds the statements necessary to register any XSUBs with Perl. With the BOOT: keyword the programmer can tell the compiler to add extra statements to the bootstrap function. This keyword may be used any time after the first MODULE keyword and should appear on a line by itself. The first blank line after the keyword will terminate the code block. BOOT: # The following message will be printed when the # bootstrap function executes. printf("Hello from the bootstrap!\n"); =head2 The VERSIONCHECK: Keyword The VERSIONCHECK: keyword corresponds to B<xsubpp>'s C<-versioncheck> and C<-noversioncheck> options. This keyword overrides the command line options. Version checking is enabled by default. When version checking is enabled the XS module will attempt to verify that its version matches the version of the PM module. To enable version checking: VERSIONCHECK: ENABLE To disable version checking: VERSIONCHECK: DISABLE Note that if the version of the PM module is an NV (a floating point number), it will be stringified with a possible loss of precision (currently chopping to nine decimal places) so that it may not match the version of the XS module anymore. Quoting the $VERSION declaration to make it a string is recommended if long version numbers are used. =head2 The PROTOTYPES: Keyword The PROTOTYPES: keyword corresponds to B<xsubpp>'s C<-prototypes> and C<-noprototypes> options. This keyword overrides the command line options. Prototypes are enabled by default. When prototypes are enabled XSUBs will be given Perl prototypes. This keyword may be used multiple times in an XS module to enable and disable prototypes for different parts of the module. To enable prototypes: PROTOTYPES: ENABLE To disable prototypes: PROTOTYPES: DISABLE =head2 The PROTOTYPE: Keyword This keyword is similar to the PROTOTYPES: keyword above but can be used to force B<xsubpp> to use a specific prototype for the XSUB. This keyword overrides all other prototype options and keywords but affects only the current XSUB. Consult L<perlsub/Prototypes> for information about Perl prototypes. bool_t rpcb_gettime(timep, ...) time_t timep = NO_INIT PROTOTYPE: $;$ PREINIT: char *host = "localhost"; CODE: if( items > 1 ) host = (char *)SvPV_nolen(ST(1)); RETVAL = rpcb_gettime( host, &timep ); OUTPUT: timep RETVAL If the prototypes are enabled, you can disable it locally for a given XSUB as in the following example: void rpcb_gettime_noproto() PROTOTYPE: DISABLE ... =head2 The ALIAS: Keyword The ALIAS: keyword allows an XSUB to have two or more unique Perl names and to know which of those names was used when it was invoked. The Perl names may be fully-qualified with package names. Each alias is given an index. The compiler will setup a variable called C<ix> which contain the index of the alias which was used. When the XSUB is called with its declared name C<ix> will be 0. The following example will create aliases C<FOO::gettime()> and C<BAR::getit()> for this function. bool_t rpcb_gettime(host,timep) char *host time_t &timep ALIAS: FOO::gettime = 1 BAR::getit = 2 INIT: printf("# ix = %d\n", ix ); OUTPUT: timep =head2 The OVERLOAD: Keyword Instead of writing an overloaded interface using pure Perl, you can also use the OVERLOAD keyword to define additional Perl names for your functions (like the ALIAS: keyword above). However, the overloaded functions must be defined with three parameters (except for the nomethod() function which needs four parameters). If any function has the OVERLOAD: keyword, several additional lines will be defined in the c file generated by xsubpp in order to register with the overload magic. Since blessed objects are actually stored as RV's, it is useful to use the typemap features to preprocess parameters and extract the actual SV stored within the blessed RV. See the sample for T_PTROBJ_SPECIAL below. To use the OVERLOAD: keyword, create an XS function which takes three input parameters ( or use the c style '...' definition) like this: SV * cmp (lobj, robj, swap) My_Module_obj lobj My_Module_obj robj IV swap OVERLOAD: cmp <=> { /* function defined here */} In this case, the function will overload both of the three way comparison operators. For all overload operations using non-alpha characters, you must type the parameter without quoting, separating multiple overloads with whitespace. Note that "" (the stringify overload) should be entered as \"\" (i.e. escaped). =head2 The FALLBACK: Keyword In addition to the OVERLOAD keyword, if you need to control how Perl autogenerates missing overloaded operators, you can set the FALLBACK keyword in the module header section, like this: MODULE = RPC PACKAGE = RPC FALLBACK: TRUE ... where FALLBACK can take any of the three values TRUE, FALSE, or UNDEF. If you do not set any FALLBACK value when using OVERLOAD, it defaults to UNDEF. FALLBACK is not used except when one or more functions using OVERLOAD have been defined. Please see L<overload/fallback> for more details. =head2 The INTERFACE: Keyword This keyword declares the current XSUB as a keeper of the given calling signature. If some text follows this keyword, it is considered as a list of functions which have this signature, and should be attached to the current XSUB. For example, if you have 4 C functions multiply(), divide(), add(), subtract() all having the signature: symbolic f(symbolic, symbolic); you can make them all to use the same XSUB using this: symbolic interface_s_ss(arg1, arg2) symbolic arg1 symbolic arg2 INTERFACE: multiply divide add subtract (This is the complete XSUB code for 4 Perl functions!) Four generated Perl function share names with corresponding C functions. The advantage of this approach comparing to ALIAS: keyword is that there is no need to code a switch statement, each Perl function (which shares the same XSUB) knows which C function it should call. Additionally, one can attach an extra function remainder() at runtime by using CV *mycv = newXSproto("Symbolic::remainder", XS_Symbolic_interface_s_ss, __FILE__, "$$"); XSINTERFACE_FUNC_SET(mycv, remainder); say, from another XSUB. (This example supposes that there was no INTERFACE_MACRO: section, otherwise one needs to use something else instead of C<XSINTERFACE_FUNC_SET>, see the next section.) =head2 The INTERFACE_MACRO: Keyword This keyword allows one to define an INTERFACE using a different way to extract a function pointer from an XSUB. The text which follows this keyword should give the name of macros which would extract/set a function pointer. The extractor macro is given return type, C<CV*>, and C<XSANY.any_dptr> for this C<CV*>. The setter macro is given cv, and the function pointer. The default value is C<XSINTERFACE_FUNC> and C<XSINTERFACE_FUNC_SET>. An INTERFACE keyword with an empty list of functions can be omitted if INTERFACE_MACRO keyword is used. Suppose that in the previous example functions pointers for multiply(), divide(), add(), subtract() are kept in a global C array C<fp[]> with offsets being C<multiply_off>, C<divide_off>, C<add_off>, C<subtract_off>. Then one can use #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \ ((XSINTERFACE_CVT_ANON(ret))fp[CvXSUBANY(cv).any_i32]) #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \ CvXSUBANY(cv).any_i32 = CAT2( f, _off ) in C section, symbolic interface_s_ss(arg1, arg2) symbolic arg1 symbolic arg2 INTERFACE_MACRO: XSINTERFACE_FUNC_BYOFFSET XSINTERFACE_FUNC_BYOFFSET_set INTERFACE: multiply divide add subtract in XSUB section. =head2 The INCLUDE: Keyword This keyword can be used to pull other files into the XS module. The other files may have XS code. INCLUDE: can also be used to run a command to generate the XS code to be pulled into the module. The file F<Rpcb1.xsh> contains our C<rpcb_gettime()> function: bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep The XS module can use INCLUDE: to pull that file into it. INCLUDE: Rpcb1.xsh If the parameters to the INCLUDE: keyword are followed by a pipe (C<|>) then the compiler will interpret the parameters as a command. This feature is mildly deprecated in favour of the C<INCLUDE_COMMAND:> directive, as documented below. INCLUDE: cat Rpcb1.xsh | Do not use this to run perl: C<INCLUDE: perl |> will run the perl that happens to be the first in your path and not necessarily the same perl that is used to run C<xsubpp>. See L<"The INCLUDE_COMMAND: Keyword">. =head2 The INCLUDE_COMMAND: Keyword Runs the supplied command and includes its output into the current XS document. C<INCLUDE_COMMAND> assigns special meaning to the C<$^X> token in that it runs the same perl interpreter that is running C<xsubpp>: INCLUDE_COMMAND: cat Rpcb1.xsh INCLUDE_COMMAND: $^X -e ... =head2 The CASE: Keyword The CASE: keyword allows an XSUB to have multiple distinct parts with each part acting as a virtual XSUB. CASE: is greedy and if it is used then all other XS keywords must be contained within a CASE:. This means nothing may precede the first CASE: in the XSUB and anything following the last CASE: is included in that case. A CASE: might switch via a parameter of the XSUB, via the C<ix> ALIAS: variable (see L<"The ALIAS: Keyword">), or maybe via the C<items> variable (see L<"Variable-length Parameter Lists">). The last CASE: becomes the B<default> case if it is not associated with a conditional. The following example shows CASE switched via C<ix> with a function C<rpcb_gettime()> having an alias C<x_gettime()>. When the function is called as C<rpcb_gettime()> its parameters are the usual C<(char *host, time_t *timep)>, but when the function is called as C<x_gettime()> its parameters are reversed, C<(time_t *timep, char *host)>. long rpcb_gettime(a,b) CASE: ix == 1 ALIAS: x_gettime = 1 INPUT: # 'a' is timep, 'b' is host char *b time_t a = NO_INIT CODE: RETVAL = rpcb_gettime( b, &a ); OUTPUT: a RETVAL CASE: # 'a' is host, 'b' is timep char *a time_t &b = NO_INIT OUTPUT: b RETVAL That function can be called with either of the following statements. Note the different argument lists. $status = rpcb_gettime( $host, $timep ); $status = x_gettime( $timep, $host ); =head2 The EXPORT_XSUB_SYMBOLS: Keyword The EXPORT_XSUB_SYMBOLS: keyword is likely something you will never need. In perl versions earlier than 5.16.0, this keyword does nothing. Starting with 5.16, XSUB symbols are no longer exported by default. That is, they are C<static> functions. If you include EXPORT_XSUB_SYMBOLS: ENABLE in your XS code, the XSUBs following this line will not be declared C<static>. You can later disable this with EXPORT_XSUB_SYMBOLS: DISABLE which, again, is the default that you should probably never change. You cannot use this keyword on versions of perl before 5.16 to make XSUBs C<static>. =head2 The & Unary Operator The C<&> unary operator in the INPUT: section is used to tell B<xsubpp> that it should convert a Perl value to/from C using the C type to the left of C<&>, but provide a pointer to this value when the C function is called. This is useful to avoid a CODE: block for a C function which takes a parameter by reference. Typically, the parameter should be not a pointer type (an C<int> or C<long> but not an C<int*> or C<long*>). The following XSUB will generate incorrect C code. The B<xsubpp> compiler will turn this into code which calls C<rpcb_gettime()> with parameters C<(char *host, time_t timep)>, but the real C<rpcb_gettime()> wants the C<timep> parameter to be of type C<time_t*> rather than C<time_t>. bool_t rpcb_gettime(host,timep) char *host time_t timep OUTPUT: timep That problem is corrected by using the C<&> operator. The B<xsubpp> compiler will now turn this into code which calls C<rpcb_gettime()> correctly with parameters C<(char *host, time_t *timep)>. It does this by carrying the C<&> through, so the function call looks like C<rpcb_gettime(host, &timep)>. bool_t rpcb_gettime(host,timep) char *host time_t &timep OUTPUT: timep =head2 Inserting POD, Comments and C Preprocessor Directives C preprocessor directives are allowed within BOOT:, PREINIT: INIT:, CODE:, PPCODE:, POSTCALL:, and CLEANUP: blocks, as well as outside the functions. Comments are allowed anywhere after the MODULE keyword. The compiler will pass the preprocessor directives through untouched and will remove the commented lines. POD documentation is allowed at any point, both in the C and XS language sections. POD must be terminated with a C<=cut> command; C<xsubpp> will exit with an error if it does not. It is very unlikely that human generated C code will be mistaken for POD, as most indenting styles result in whitespace in front of any line starting with C<=>. Machine generated XS files may fall into this trap unless care is taken to ensure that a space breaks the sequence "\n=". Comments can be added to XSUBs by placing a C<#> as the first non-whitespace of a line. Care should be taken to avoid making the comment look like a C preprocessor directive, lest it be interpreted as such. The simplest way to prevent this is to put whitespace in front of the C<#>. If you use preprocessor directives to choose one of two versions of a function, use #if ... version1 #else /* ... version2 */ #endif and not #if ... version1 #endif #if ... version2 #endif because otherwise B<xsubpp> will believe that you made a duplicate definition of the function. Also, put a blank line before the #else/#endif so it will not be seen as part of the function body. =head2 Using XS With C++ If an XSUB name contains C<::>, it is considered to be a C++ method. The generated Perl function will assume that its first argument is an object pointer. The object pointer will be stored in a variable called THIS. The object should have been created by C++ with the new() function and should be blessed by Perl with the sv_setref_pv() macro. The blessing of the object by Perl can be handled by a typemap. An example typemap is shown at the end of this section. If the return type of the XSUB includes C<static>, the method is considered to be a static method. It will call the C++ function using the class::method() syntax. If the method is not static the function will be called using the THIS-E<gt>method() syntax. The next examples will use the following C++ class. class color { public: color(); ~color(); int blue(); void set_blue( int ); private: int c_blue; }; The XSUBs for the blue() and set_blue() methods are defined with the class name but the parameter for the object (THIS, or "self") is implicit and is not listed. int color::blue() void color::set_blue( val ) int val Both Perl functions will expect an object as the first parameter. In the generated C++ code the object is called C<THIS>, and the method call will be performed on this object. So in the C++ code the blue() and set_blue() methods will be called as this: RETVAL = THIS->blue(); THIS->set_blue( val ); You could also write a single get/set method using an optional argument: int color::blue( val = NO_INIT ) int val PROTOTYPE $;$ CODE: if (items > 1) THIS->set_blue( val ); RETVAL = THIS->blue(); OUTPUT: RETVAL If the function's name is B<DESTROY> then the C++ C<delete> function will be called and C<THIS> will be given as its parameter. The generated C++ code for void color::DESTROY() will look like this: color *THIS = ...; // Initialized as in typemap delete THIS; If the function's name is B<new> then the C++ C<new> function will be called to create a dynamic C++ object. The XSUB will expect the class name, which will be kept in a variable called C<CLASS>, to be given as the first argument. color * color::new() The generated C++ code will call C<new>. RETVAL = new color(); The following is an example of a typemap that could be used for this C++ example. TYPEMAP color * O_OBJECT OUTPUT # The Perl object is blessed into 'CLASS', which should be a # char* having the name of the package for the blessing. O_OBJECT sv_setref_pv( $arg, CLASS, (void*)$var ); INPUT O_OBJECT if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) ) $var = ($type)SvIV((SV*)SvRV( $arg )); else{ warn( \"${Package}::$func_name() -- $var is not a blessed SV reference\" ); XSRETURN_UNDEF; } =head2 Interface Strategy When designing an interface between Perl and a C library a straight translation from C to XS (such as created by C<h2xs -x>) is often sufficient. However, sometimes the interface will look very C-like and occasionally nonintuitive, especially when the C function modifies one of its parameters, or returns failure inband (as in "negative return values mean failure"). In cases where the programmer wishes to create a more Perl-like interface the following strategy may help to identify the more critical parts of the interface. Identify the C functions with input/output or output parameters. The XSUBs for these functions may be able to return lists to Perl. Identify the C functions which use some inband info as an indication of failure. They may be candidates to return undef or an empty list in case of failure. If the failure may be detected without a call to the C function, you may want to use an INIT: section to report the failure. For failures detectable after the C function returns one may want to use a POSTCALL: section to process the failure. In more complicated cases use CODE: or PPCODE: sections. If many functions use the same failure indication based on the return value, you may want to create a special typedef to handle this situation. Put typedef int negative_is_failure; near the beginning of XS file, and create an OUTPUT typemap entry for C<negative_is_failure> which converts negative values to C<undef>, or maybe croak()s. After this the return value of type C<negative_is_failure> will create more Perl-like interface. Identify which values are used by only the C and XSUB functions themselves, say, when a parameter to a function should be a contents of a global variable. If Perl does not need to access the contents of the value then it may not be necessary to provide a translation for that value from C to Perl. Identify the pointers in the C function parameter lists and return values. Some pointers may be used to implement input/output or output parameters, they can be handled in XS with the C<&> unary operator, and, possibly, using the NO_INIT keyword. Some others will require handling of types like C<int *>, and one needs to decide what a useful Perl translation will do in such a case. When the semantic is clear, it is advisable to put the translation into a typemap file. Identify the structures used by the C functions. In many cases it may be helpful to use the T_PTROBJ typemap for these structures so they can be manipulated by Perl as blessed objects. (This is handled automatically by C<h2xs -x>.) If the same C type is used in several different contexts which require different translations, C<typedef> several new types mapped to this C type, and create separate F<typemap> entries for these new types. Use these types in declarations of return type and parameters to XSUBs. =head2 Perl Objects And C Structures When dealing with C structures one should select either B<T_PTROBJ> or B<T_PTRREF> for the XS type. Both types are designed to handle pointers to complex objects. The T_PTRREF type will allow the Perl object to be unblessed while the T_PTROBJ type requires that the object be blessed. By using T_PTROBJ one can achieve a form of type-checking because the XSUB will attempt to verify that the Perl object is of the expected type. The following XS code shows the getnetconfigent() function which is used with ONC+ TIRPC. The getnetconfigent() function will return a pointer to a C structure and has the C prototype shown below. The example will demonstrate how the C pointer will become a Perl reference. Perl will consider this reference to be a pointer to a blessed object and will attempt to call a destructor for the object. A destructor will be provided in the XS source to free the memory used by getnetconfigent(). Destructors in XS can be created by specifying an XSUB function whose name ends with the word B<DESTROY>. XS destructors can be used to free memory which may have been malloc'd by another XSUB. struct netconfig *getnetconfigent(const char *netid); A C<typedef> will be created for C<struct netconfig>. The Perl object will be blessed in a class matching the name of the C type, with the tag C<Ptr> appended, and the name should not have embedded spaces if it will be a Perl package name. The destructor will be placed in a class corresponding to the class of the object and the PREFIX keyword will be used to trim the name to the word DESTROY as Perl will expect. typedef struct netconfig Netconfig; MODULE = RPC PACKAGE = RPC Netconfig * getnetconfigent(netid) char *netid MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_ void rpcb_DESTROY(netconf) Netconfig *netconf CODE: printf("Now in NetconfigPtr::DESTROY\n"); free( netconf ); This example requires the following typemap entry. Consult L<perlxstypemap> for more information about adding new typemaps for an extension. TYPEMAP Netconfig * T_PTROBJ This example will be used with the following Perl statements. use RPC; $netconf = getnetconfigent("udp"); When Perl destroys the object referenced by $netconf it will send the object to the supplied XSUB DESTROY function. Perl cannot determine, and does not care, that this object is a C struct and not a Perl object. In this sense, there is no difference between the object created by the getnetconfigent() XSUB and an object created by a normal Perl subroutine. =head2 Safely Storing Static Data in XS Starting with Perl 5.8, a macro framework has been defined to allow static data to be safely stored in XS modules that will be accessed from a multi-threaded Perl. Although primarily designed for use with multi-threaded Perl, the macros have been designed so that they will work with non-threaded Perl as well. It is therefore strongly recommended that these macros be used by all XS modules that make use of static data. The easiest way to get a template set of macros to use is by specifying the C<-g> (C<--global>) option with h2xs (see L<h2xs>). Below is an example module that makes use of the macros. #include "EXTERN.h" #include "perl.h" #include "XSUB.h" /* Global Data */ #define MY_CXT_KEY "BlindMice::_guts" XS_VERSION typedef struct { int count; char name[3][100]; } my_cxt_t; START_MY_CXT MODULE = BlindMice PACKAGE = BlindMice BOOT: { MY_CXT_INIT; MY_CXT.count = 0; strcpy(MY_CXT.name[0], "None"); strcpy(MY_CXT.name[1], "None"); strcpy(MY_CXT.name[2], "None"); } int newMouse(char * name) char * name; PREINIT: dMY_CXT; CODE: if (MY_CXT.count >= 3) { warn("Already have 3 blind mice"); RETVAL = 0; } else { RETVAL = ++ MY_CXT.count; strcpy(MY_CXT.name[MY_CXT.count - 1], name); } char * get_mouse_name(index) int index CODE: dMY_CXT; RETVAL = MY_CXT.lives ++; if (index > MY_CXT.count) croak("There are only 3 blind mice."); else RETVAL = newSVpv(MY_CXT.name[index - 1]); void CLONE(...) CODE: MY_CXT_CLONE; B<REFERENCE> =over 5 =item MY_CXT_KEY This macro is used to define a unique key to refer to the static data for an XS module. The suggested naming scheme, as used by h2xs, is to use a string that consists of the module name, the string "::_guts" and the module version number. #define MY_CXT_KEY "MyModule::_guts" XS_VERSION =item typedef my_cxt_t This struct typedef I<must> always be called C<my_cxt_t>. The other C<CXT*> macros assume the existence of the C<my_cxt_t> typedef name. Declare a typedef named C<my_cxt_t> that is a structure that contains all the data that needs to be interpreter-local. typedef struct { int some_value; } my_cxt_t; =item START_MY_CXT Always place the START_MY_CXT macro directly after the declaration of C<my_cxt_t>. =item MY_CXT_INIT The MY_CXT_INIT macro initialises storage for the C<my_cxt_t> struct. It I<must> be called exactly once, typically in a BOOT: section. If you are maintaining multiple interpreters, it should be called once in each interpreter instance, except for interpreters cloned from existing ones. (But see L</MY_CXT_CLONE> below.) =item dMY_CXT Use the dMY_CXT macro (a declaration) in all the functions that access MY_CXT. =item MY_CXT Use the MY_CXT macro to access members of the C<my_cxt_t> struct. For example, if C<my_cxt_t> is typedef struct { int index; } my_cxt_t; then use this to access the C<index> member dMY_CXT; MY_CXT.index = 2; =item aMY_CXT/pMY_CXT C<dMY_CXT> may be quite expensive to calculate, and to avoid the overhead of invoking it in each function it is possible to pass the declaration onto other functions using the C<aMY_CXT>/C<pMY_CXT> macros, eg void sub1() { dMY_CXT; MY_CXT.index = 1; sub2(aMY_CXT); } void sub2(pMY_CXT) { MY_CXT.index = 2; } Analogously to C<pTHX>, there are equivalent forms for when the macro is the first or last in multiple arguments, where an underscore represents a comma, i.e. C<_aMY_CXT>, C<aMY_CXT_>, C<_pMY_CXT> and C<pMY_CXT_>. =item MY_CXT_CLONE By default, when a new interpreter is created as a copy of an existing one (eg via C<< threads->create() >>), both interpreters share the same physical my_cxt_t structure. Calling C<MY_CXT_CLONE> (typically via the package's C<CLONE()> function), causes a byte-for-byte copy of the structure to be taken, and any future dMY_CXT will cause the copy to be accessed instead. =item MY_CXT_INIT_INTERP(my_perl) =item dMY_CXT_INTERP(my_perl) These are versions of the macros which take an explicit interpreter as an argument. =back Note that these macros will only work together within the I<same> source file; that is, a dMY_CTX in one source file will access a different structure than a dMY_CTX in another source file. =head2 Thread-aware system interfaces Starting from Perl 5.8, in C/C++ level Perl knows how to wrap system/library interfaces that have thread-aware versions (e.g. getpwent_r()) into frontend macros (e.g. getpwent()) that correctly handle the multithreaded interaction with the Perl interpreter. This will happen transparently, the only thing you need to do is to instantiate a Perl interpreter. This wrapping happens always when compiling Perl core source (PERL_CORE is defined) or the Perl core extensions (PERL_EXT is defined). When compiling XS code outside of Perl core the wrapping does not take place. Note, however, that intermixing the _r-forms (as Perl compiled for multithreaded operation will do) and the _r-less forms is neither well-defined (inconsistent results, data corruption, or even crashes become more likely), nor is it very portable. =head1 EXAMPLES File C<RPC.xs>: Interface to some ONC+ RPC bind library functions. #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include <rpc/rpc.h> typedef struct netconfig Netconfig; MODULE = RPC PACKAGE = RPC SV * rpcb_gettime(host="localhost") char *host PREINIT: time_t timep; CODE: ST(0) = sv_newmortal(); if( rpcb_gettime( host, &timep ) ) sv_setnv( ST(0), (double)timep ); Netconfig * getnetconfigent(netid="udp") char *netid MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_ void rpcb_DESTROY(netconf) Netconfig *netconf CODE: printf("NetconfigPtr::DESTROY\n"); free( netconf ); File C<typemap>: Custom typemap for RPC.xs. (cf. L<perlxstypemap>) TYPEMAP Netconfig * T_PTROBJ File C<RPC.pm>: Perl module for the RPC extension. package RPC; require Exporter; require DynaLoader; @ISA = qw(Exporter DynaLoader); @EXPORT = qw(rpcb_gettime getnetconfigent); bootstrap RPC; 1; File C<rpctest.pl>: Perl test program for the RPC extension. use RPC; $netconf = getnetconfigent(); $a = rpcb_gettime(); print "time = $a\n"; print "netconf = $netconf\n"; $netconf = getnetconfigent("tcp"); $a = rpcb_gettime("poplar"); print "time = $a\n"; print "netconf = $netconf\n"; =head1 XS VERSION This document covers features supported by C<ExtUtils::ParseXS> (also known as C<xsubpp>) 3.13_01. =head1 AUTHOR Originally written by Dean Roehrich <F<roehrich@cray.com>>. Maintained since 1996 by The Perl Porters <F<perlbug@perl.org>>. PK PU�\1�T�� � perldelta.podnu �[��� =encoding utf8 =head1 NAME perldelta - what is new for perl v5.16.3 =head1 DESCRIPTION This document describes differences between the 5.16.2 release and the 5.16.3 release. If you are upgrading from an earlier release such as 5.16.1, first read L<perl5162delta>, which describes differences between 5.16.1 and 5.16.2. =head1 Core Enhancements No changes since 5.16.0. =head1 Security This release contains one major and a number of minor security fixes. These latter are included mainly to allow the test suite to pass cleanly with the clang compiler's address sanitizer facility. =head2 CVE-2013-1667: memory exhaustion with arbitrary hash keys With a carefully crafted set of hash keys (for example arguments on a URL), it is possible to cause a hash to consume a large amount of memory and CPU, and thus possibly to achieve a Denial-of-Service. This problem has been fixed. =head2 wrap-around with IO on long strings Reading or writing strings greater than 2**31 bytes in size could segfault due to integer wraparound. This problem has been fixed. =head2 memory leak in Encode The UTF-8 encoding implementation in Encode.xs had a memory leak which has been fixed. =head1 Incompatible Changes There are no changes intentionally incompatible with 5.16.0. If any exist, they are bugs and reports are welcome. =head1 Deprecations There have been no deprecations since 5.16.0. =head1 Modules and Pragmata =head2 Updated Modules and Pragmata =over 4 =item * L<Encode> has been upgraded from version 2.44 to version 2.44_01. =item * L<Module::CoreList> has been upgraded from version 2.76 to version 2.76_02. =item * L<XS::APItest> has been upgraded from version 0.38 to version 0.39. =back =head1 Known Problems None. =head1 Acknowledgements Perl 5.16.3 represents approximately 4 months of development since Perl 5.16.2 and contains approximately 870 lines of changes across 39 files from 7 authors. Perl continues to flourish into its third decade thanks to a vibrant community of users and developers. The following people are known to have contributed the improvements that became Perl 5.16.3: Andy Dougherty, Chris 'BinGOs' Williams, Dave Rolsky, David Mitchell, Michael Schroeder, Ricardo Signes, Yves Orton. The list above is almost certainly incomplete as it is automatically generated from version control history. In particular, it does not include the names of the (very much appreciated) contributors who reported issues to the Perl bug tracker. For a more complete list of all of Perl's historical contributors, please see the F<AUTHORS> file in the Perl source distribution. =head1 Reporting Bugs If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup and the perl bug database at http://rt.perl.org/perlbug/ . There may also be information at http://www.perl.org/ , the Perl Home Page. If you believe you have an unreported bug, please run the L<perlbug> program included with your release. Be sure to trim your bug down to a tiny but sufficient test case. Your bug report, along with the output of C<perl -V>, will be sent off to perlbug@perl.org to be analysed by the Perl porting team. If the bug you are reporting has security implications, which make it inappropriate to send to a publicly archived mailing list, then please send it to perl5-security-report@perl.org. This points to a closed subscription unarchived mailing list, which includes all the core committers, who will be able to help assess the impact of issues, figure out a resolution, and help co-ordinate the release of patches to mitigate or fix the problem across all platforms on which Perl is supported. Please only use this address for security issues in the Perl core, not for modules independently distributed on CPAN. =head1 SEE ALSO The F<Changes> file for an explanation of how to view exhaustive details on what changed. The F<INSTALL> file for how to build Perl. The F<README> file for general stuff. The F<Artistic> and F<Copying> files for copyright information. =cut PK PU�\��ˬd �d perlreapi.podnu �[��� =head1 NAME perlreapi - perl regular expression plugin interface =head1 DESCRIPTION As of Perl 5.9.5 there is a new interface for plugging and using other regular expression engines than the default one. Each engine is supposed to provide access to a constant structure of the following format: typedef struct regexp_engine { REGEXP* (*comp) (pTHX_ const SV * const pattern, const U32 flags); I32 (*exec) (pTHX_ REGEXP * const rx, char* stringarg, char* strend, char* strbeg, I32 minend, SV* screamer, void* data, U32 flags); char* (*intuit) (pTHX_ REGEXP * const rx, SV *sv, char *strpos, char *strend, U32 flags, struct re_scream_pos_data_s *data); SV* (*checkstr) (pTHX_ REGEXP * const rx); void (*free) (pTHX_ REGEXP * const rx); void (*numbered_buff_FETCH) (pTHX_ REGEXP * const rx, const I32 paren, SV * const sv); void (*numbered_buff_STORE) (pTHX_ REGEXP * const rx, const I32 paren, SV const * const value); I32 (*numbered_buff_LENGTH) (pTHX_ REGEXP * const rx, const SV * const sv, const I32 paren); SV* (*named_buff) (pTHX_ REGEXP * const rx, SV * const key, SV * const value, U32 flags); SV* (*named_buff_iter) (pTHX_ REGEXP * const rx, const SV * const lastkey, const U32 flags); SV* (*qr_package)(pTHX_ REGEXP * const rx); #ifdef USE_ITHREADS void* (*dupe) (pTHX_ REGEXP * const rx, CLONE_PARAMS *param); #endif When a regexp is compiled, its C<engine> field is then set to point at the appropriate structure, so that when it needs to be used Perl can find the right routines to do so. In order to install a new regexp handler, C<$^H{regcomp}> is set to an integer which (when casted appropriately) resolves to one of these structures. When compiling, the C<comp> method is executed, and the resulting regexp structure's engine field is expected to point back at the same structure. The pTHX_ symbol in the definition is a macro used by perl under threading to provide an extra argument to the routine holding a pointer back to the interpreter that is executing the regexp. So under threading all routines get an extra argument. =head1 Callbacks =head2 comp REGEXP* comp(pTHX_ const SV * const pattern, const U32 flags); Compile the pattern stored in C<pattern> using the given C<flags> and return a pointer to a prepared C<REGEXP> structure that can perform the match. See L</The REGEXP structure> below for an explanation of the individual fields in the REGEXP struct. The C<pattern> parameter is the scalar that was used as the pattern. previous versions of perl would pass two C<char*> indicating the start and end of the stringified pattern, the following snippet can be used to get the old parameters: STRLEN plen; char* exp = SvPV(pattern, plen); char* xend = exp + plen; Since any scalar can be passed as a pattern it's possible to implement an engine that does something with an array (C<< "ook" =~ [ qw/ eek hlagh / ] >>) or with the non-stringified form of a compiled regular expression (C<< "ook" =~ qr/eek/ >>). perl's own engine will always stringify everything using the snippet above but that doesn't mean other engines have to. The C<flags> parameter is a bitfield which indicates which of the C<msixp> flags the regex was compiled with. It also contains additional info such as whether C<use locale> is in effect. The C<eogc> flags are stripped out before being passed to the comp routine. The regex engine does not need to know whether any of these are set as those flags should only affect what perl does with the pattern and its match variables, not how it gets compiled and executed. By the time the comp callback is called, some of these flags have already had effect (noted below where applicable). However most of their effect occurs after the comp callback has run in routines that read the C<< rx->extflags >> field which it populates. In general the flags should be preserved in C<< rx->extflags >> after compilation, although the regex engine might want to add or delete some of them to invoke or disable some special behavior in perl. The flags along with any special behavior they cause are documented below: The pattern modifiers: =over 4 =item C</m> - RXf_PMf_MULTILINE If this is in C<< rx->extflags >> it will be passed to C<Perl_fbm_instr> by C<pp_split> which will treat the subject string as a multi-line string. =item C</s> - RXf_PMf_SINGLELINE =item C</i> - RXf_PMf_FOLD =item C</x> - RXf_PMf_EXTENDED If present on a regex C<#> comments will be handled differently by the tokenizer in some cases. TODO: Document those cases. =item C</p> - RXf_PMf_KEEPCOPY TODO: Document this =item Character set The character set semantics are determined by an enum that is contained in this field. This is still experimental and subject to change, but the current interface returns the rules by use of the in-line function C<get_regex_charset(const U32 flags)>. The only currently documented value returned from it is REGEX_LOCALE_CHARSET, which is set if C<use locale> is in effect. If present in C<< rx->extflags >>, C<split> will use the locale dependent definition of whitespace when RXf_SKIPWHITE or RXf_WHITE is in effect. ASCII whitespace is defined as per L<isSPACE|perlapi/isSPACE>, and by the internal macros C<is_utf8_space> under UTF-8, and C<isSPACE_LC> under C<use locale>. =back Additional flags: =over 4 =item RXf_UTF8 Set if the pattern is L<SvUTF8()|perlapi/SvUTF8>, set by Perl_pmruntime. A regex engine may want to set or disable this flag during compilation. The perl engine for instance may upgrade non-UTF-8 strings to UTF-8 if the pattern includes constructs such as C<\x{...}> that can only match Unicode values. =item RXf_SPLIT If C<split> is invoked as C<split ' '> or with no arguments (which really means C<split(' ', $_)>, see L<split|perlfunc/split>), perl will set this flag. The regex engine can then check for it and set the SKIPWHITE and WHITE extflags. To do this the perl engine does: if (flags & RXf_SPLIT && r->prelen == 1 && r->precomp[0] == ' ') r->extflags |= (RXf_SKIPWHITE|RXf_WHITE); =back These flags can be set during compilation to enable optimizations in the C<split> operator. =over 4 =item RXf_SKIPWHITE If the flag is present in C<< rx->extflags >> C<split> will delete whitespace from the start of the subject string before it's operated on. What is considered whitespace depends on whether the subject is a UTF-8 string and whether the C<RXf_PMf_LOCALE> flag is set. If RXf_WHITE is set in addition to this flag C<split> will behave like C<split " "> under the perl engine. =item RXf_START_ONLY Tells the split operator to split the target string on newlines (C<\n>) without invoking the regex engine. Perl's engine sets this if the pattern is C</^/> (C<plen == 1 && *exp == '^'>), even under C</^/s>, see L<split|perlfunc>. Of course a different regex engine might want to use the same optimizations with a different syntax. =item RXf_WHITE Tells the split operator to split the target string on whitespace without invoking the regex engine. The definition of whitespace varies depending on whether the target string is a UTF-8 string and on whether RXf_PMf_LOCALE is set. Perl's engine sets this flag if the pattern is C<\s+>. =item RXf_NULL Tells the split operator to split the target string on characters. The definition of character varies depending on whether the target string is a UTF-8 string. Perl's engine sets this flag on empty patterns, this optimization makes C<split //> much faster than it would otherwise be. It's even faster than C<unpack>. =back =head2 exec I32 exec(pTHX_ REGEXP * const rx, char *stringarg, char* strend, char* strbeg, I32 minend, SV* screamer, void* data, U32 flags); Execute a regexp. =head2 intuit char* intuit(pTHX_ REGEXP * const rx, SV *sv, char *strpos, char *strend, const U32 flags, struct re_scream_pos_data_s *data); Find the start position where a regex match should be attempted, or possibly whether the regex engine should not be run because the pattern can't match. This is called as appropriate by the core depending on the values of the extflags member of the regexp structure. =head2 checkstr SV* checkstr(pTHX_ REGEXP * const rx); Return a SV containing a string that must appear in the pattern. Used by C<split> for optimising matches. =head2 free void free(pTHX_ REGEXP * const rx); Called by perl when it is freeing a regexp pattern so that the engine can release any resources pointed to by the C<pprivate> member of the regexp structure. This is only responsible for freeing private data; perl will handle releasing anything else contained in the regexp structure. =head2 Numbered capture callbacks Called to get/set the value of C<$`>, C<$'>, C<$&> and their named equivalents, ${^PREMATCH}, ${^POSTMATCH} and $^{MATCH}, as well as the numbered capture groups (C<$1>, C<$2>, ...). The C<paren> parameter will be C<-2> for C<$`>, C<-1> for C<$'>, C<0> for C<$&>, C<1> for C<$1> and so forth. The names have been chosen by analogy with L<Tie::Scalar> methods names with an additional B<LENGTH> callback for efficiency. However named capture variables are currently not tied internally but implemented via magic. =head3 numbered_buff_FETCH void numbered_buff_FETCH(pTHX_ REGEXP * const rx, const I32 paren, SV * const sv); Fetch a specified numbered capture. C<sv> should be set to the scalar to return, the scalar is passed as an argument rather than being returned from the function because when it's called perl already has a scalar to store the value, creating another one would be redundant. The scalar can be set with C<sv_setsv>, C<sv_setpvn> and friends, see L<perlapi>. This callback is where perl untaints its own capture variables under taint mode (see L<perlsec>). See the C<Perl_reg_numbered_buff_fetch> function in F<regcomp.c> for how to untaint capture variables if that's something you'd like your engine to do as well. =head3 numbered_buff_STORE void (*numbered_buff_STORE) (pTHX_ REGEXP * const rx, const I32 paren, SV const * const value); Set the value of a numbered capture variable. C<value> is the scalar that is to be used as the new value. It's up to the engine to make sure this is used as the new value (or reject it). Example: if ("ook" =~ /(o*)/) { # 'paren' will be '1' and 'value' will be 'ee' $1 =~ tr/o/e/; } Perl's own engine will croak on any attempt to modify the capture variables, to do this in another engine use the following callback (copied from C<Perl_reg_numbered_buff_store>): void Example_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren, SV const * const value) { PERL_UNUSED_ARG(rx); PERL_UNUSED_ARG(paren); PERL_UNUSED_ARG(value); if (!PL_localizing) Perl_croak(aTHX_ PL_no_modify); } Actually perl will not I<always> croak in a statement that looks like it would modify a numbered capture variable. This is because the STORE callback will not be called if perl can determine that it doesn't have to modify the value. This is exactly how tied variables behave in the same situation: package CaptureVar; use base 'Tie::Scalar'; sub TIESCALAR { bless [] } sub FETCH { undef } sub STORE { die "This doesn't get called" } package main; tie my $sv => "CaptureVar"; $sv =~ y/a/b/; Because C<$sv> is C<undef> when the C<y///> operator is applied to it the transliteration won't actually execute and the program won't C<die>. This is different to how 5.8 and earlier versions behaved since the capture variables were READONLY variables then, now they'll just die when assigned to in the default engine. =head3 numbered_buff_LENGTH I32 numbered_buff_LENGTH (pTHX_ REGEXP * const rx, const SV * const sv, const I32 paren); Get the C<length> of a capture variable. There's a special callback for this so that perl doesn't have to do a FETCH and run C<length> on the result, since the length is (in perl's case) known from an offset stored in C<< rx->offs >> this is much more efficient: I32 s1 = rx->offs[paren].start; I32 s2 = rx->offs[paren].end; I32 len = t1 - s1; This is a little bit more complex in the case of UTF-8, see what C<Perl_reg_numbered_buff_length> does with L<is_utf8_string_loclen|perlapi/is_utf8_string_loclen>. =head2 Named capture callbacks Called to get/set the value of C<%+> and C<%-> as well as by some utility functions in L<re>. There are two callbacks, C<named_buff> is called in all the cases the FETCH, STORE, DELETE, CLEAR, EXISTS and SCALAR L<Tie::Hash> callbacks would be on changes to C<%+> and C<%-> and C<named_buff_iter> in the same cases as FIRSTKEY and NEXTKEY. The C<flags> parameter can be used to determine which of these operations the callbacks should respond to, the following flags are currently defined: Which L<Tie::Hash> operation is being performed from the Perl level on C<%+> or C<%+>, if any: RXapif_FETCH RXapif_STORE RXapif_DELETE RXapif_CLEAR RXapif_EXISTS RXapif_SCALAR RXapif_FIRSTKEY RXapif_NEXTKEY Whether C<%+> or C<%-> is being operated on, if any. RXapif_ONE /* %+ */ RXapif_ALL /* %- */ Whether this is being called as C<re::regname>, C<re::regnames> or C<re::regnames_count>, if any. The first two will be combined with C<RXapif_ONE> or C<RXapif_ALL>. RXapif_REGNAME RXapif_REGNAMES RXapif_REGNAMES_COUNT Internally C<%+> and C<%-> are implemented with a real tied interface via L<Tie::Hash::NamedCapture>. The methods in that package will call back into these functions. However the usage of L<Tie::Hash::NamedCapture> for this purpose might change in future releases. For instance this might be implemented by magic instead (would need an extension to mgvtbl). =head3 named_buff SV* (*named_buff) (pTHX_ REGEXP * const rx, SV * const key, SV * const value, U32 flags); =head3 named_buff_iter SV* (*named_buff_iter) (pTHX_ REGEXP * const rx, const SV * const lastkey, const U32 flags); =head2 qr_package SV* qr_package(pTHX_ REGEXP * const rx); The package the qr// magic object is blessed into (as seen by C<ref qr//>). It is recommended that engines change this to their package name for identification regardless of whether they implement methods on the object. The package this method returns should also have the internal C<Regexp> package in its C<@ISA>. C<< qr//->isa("Regexp") >> should always be true regardless of what engine is being used. Example implementation might be: SV* Example_qr_package(pTHX_ REGEXP * const rx) { PERL_UNUSED_ARG(rx); return newSVpvs("re::engine::Example"); } Any method calls on an object created with C<qr//> will be dispatched to the package as a normal object. use re::engine::Example; my $re = qr//; $re->meth; # dispatched to re::engine::Example::meth() To retrieve the C<REGEXP> object from the scalar in an XS function use the C<SvRX> macro, see L<"REGEXP Functions" in perlapi|perlapi/REGEXP Functions>. void meth(SV * rv) PPCODE: REGEXP * re = SvRX(sv); =head2 dupe void* dupe(pTHX_ REGEXP * const rx, CLONE_PARAMS *param); On threaded builds a regexp may need to be duplicated so that the pattern can be used by multiple threads. This routine is expected to handle the duplication of any private data pointed to by the C<pprivate> member of the regexp structure. It will be called with the preconstructed new regexp structure as an argument, the C<pprivate> member will point at the B<old> private structure, and it is this routine's responsibility to construct a copy and return a pointer to it (which perl will then use to overwrite the field as passed to this routine.) This allows the engine to dupe its private data but also if necessary modify the final structure if it really must. On unthreaded builds this field doesn't exist. =head1 The REGEXP structure The REGEXP struct is defined in F<regexp.h>. All regex engines must be able to correctly build such a structure in their L</comp> routine. The REGEXP structure contains all the data that perl needs to be aware of to properly work with the regular expression. It includes data about optimisations that perl can use to determine if the regex engine should really be used, and various other control info that is needed to properly execute patterns in various contexts such as is the pattern anchored in some way, or what flags were used during the compile, or whether the program contains special constructs that perl needs to be aware of. In addition it contains two fields that are intended for the private use of the regex engine that compiled the pattern. These are the C<intflags> and C<pprivate> members. C<pprivate> is a void pointer to an arbitrary structure whose use and management is the responsibility of the compiling engine. perl will never modify either of these values. typedef struct regexp { /* what engine created this regexp? */ const struct regexp_engine* engine; /* what re is this a lightweight copy of? */ struct regexp* mother_re; /* Information about the match that the perl core uses to manage things */ U32 extflags; /* Flags used both externally and internally */ I32 minlen; /* mininum possible length of string to match */ I32 minlenret; /* mininum possible length of $& */ U32 gofs; /* chars left of pos that we search from */ /* substring data about strings that must appear in the final match, used for optimisations */ struct reg_substr_data *substrs; U32 nparens; /* number of capture groups */ /* private engine specific data */ U32 intflags; /* Engine Specific Internal flags */ void *pprivate; /* Data private to the regex engine which created this object. */ /* Data about the last/current match. These are modified during matching*/ U32 lastparen; /* last open paren matched */ U32 lastcloseparen; /* last close paren matched */ regexp_paren_pair *swap; /* Swap copy of *offs */ regexp_paren_pair *offs; /* Array of offsets for (@-) and (@+) */ char *subbeg; /* saved or original string so \digit works forever. */ SV_SAVED_COPY /* If non-NULL, SV which is COW from original */ I32 sublen; /* Length of string pointed by subbeg */ /* Information about the match that isn't often used */ I32 prelen; /* length of precomp */ const char *precomp; /* pre-compilation regular expression */ char *wrapped; /* wrapped version of the pattern */ I32 wraplen; /* length of wrapped */ I32 seen_evals; /* number of eval groups in the pattern - for security checks */ HV *paren_names; /* Optional hash of paren names */ /* Refcount of this regexp */ I32 refcnt; /* Refcount of this regexp */ } regexp; The fields are discussed in more detail below: =head2 C<engine> This field points at a regexp_engine structure which contains pointers to the subroutines that are to be used for performing a match. It is the compiling routine's responsibility to populate this field before returning the regexp object. Internally this is set to C<NULL> unless a custom engine is specified in C<$^H{regcomp}>, perl's own set of callbacks can be accessed in the struct pointed to by C<RE_ENGINE_PTR>. =head2 C<mother_re> TODO, see L<http://www.mail-archive.com/perl5-changes@perl.org/msg17328.html> =head2 C<extflags> This will be used by perl to see what flags the regexp was compiled with, this will normally be set to the value of the flags parameter by the L<comp|/comp> callback. See the L<comp|/comp> documentation for valid flags. =head2 C<minlen> C<minlenret> The minimum string length required for the pattern to match. This is used to prune the search space by not bothering to match any closer to the end of a string than would allow a match. For instance there is no point in even starting the regex engine if the minlen is 10 but the string is only 5 characters long. There is no way that the pattern can match. C<minlenret> is the minimum length of the string that would be found in $& after a match. The difference between C<minlen> and C<minlenret> can be seen in the following pattern: /ns(?=\d)/ where the C<minlen> would be 3 but C<minlenret> would only be 2 as the \d is required to match but is not actually included in the matched content. This distinction is particularly important as the substitution logic uses the C<minlenret> to tell whether it can do in-place substitution which can result in considerable speedup. =head2 C<gofs> Left offset from pos() to start match at. =head2 C<substrs> Substring data about strings that must appear in the final match. This is currently only used internally by perl's engine for but might be used in the future for all engines for optimisations. =head2 C<nparens>, C<lastparen>, and C<lastcloseparen> These fields are used to keep track of how many paren groups could be matched in the pattern, which was the last open paren to be entered, and which was the last close paren to be entered. =head2 C<intflags> The engine's private copy of the flags the pattern was compiled with. Usually this is the same as C<extflags> unless the engine chose to modify one of them. =head2 C<pprivate> A void* pointing to an engine-defined data structure. The perl engine uses the C<regexp_internal> structure (see L<perlreguts/Base Structures>) but a custom engine should use something else. =head2 C<swap> Unused. Left in for compatibility with perl 5.10.0. =head2 C<offs> A C<regexp_paren_pair> structure which defines offsets into the string being matched which correspond to the C<$&> and C<$1>, C<$2> etc. captures, the C<regexp_paren_pair> struct is defined as follows: typedef struct regexp_paren_pair { I32 start; I32 end; } regexp_paren_pair; If C<< ->offs[num].start >> or C<< ->offs[num].end >> is C<-1> then that capture group did not match. C<< ->offs[0].start/end >> represents C<$&> (or C<${^MATCH> under C<//p>) and C<< ->offs[paren].end >> matches C<$$paren> where C<$paren >= 1>. =head2 C<precomp> C<prelen> Used for optimisations. C<precomp> holds a copy of the pattern that was compiled and C<prelen> its length. When a new pattern is to be compiled (such as inside a loop) the internal C<regcomp> operator checks whether the last compiled C<REGEXP>'s C<precomp> and C<prelen> are equivalent to the new one, and if so uses the old pattern instead of compiling a new one. The relevant snippet from C<Perl_pp_regcomp>: if (!re || !re->precomp || re->prelen != (I32)len || memNE(re->precomp, t, len)) /* Compile a new pattern */ =head2 C<paren_names> This is a hash used internally to track named capture groups and their offsets. The keys are the names of the buffers the values are dualvars, with the IV slot holding the number of buffers with the given name and the pv being an embedded array of I32. The values may also be contained independently in the data array in cases where named backreferences are used. =head2 C<substrs> Holds information on the longest string that must occur at a fixed offset from the start of the pattern, and the longest string that must occur at a floating offset from the start of the pattern. Used to do Fast-Boyer-Moore searches on the string to find out if its worth using the regex engine at all, and if so where in the string to search. =head2 C<subbeg> C<sublen> C<saved_copy> Used during execution phase for managing search and replace patterns. =head2 C<wrapped> C<wraplen> Stores the string C<qr//> stringifies to. The perl engine for example stores C<(?^:eek)> in the case of C<qr/eek/>. When using a custom engine that doesn't support the C<(?:)> construct for inline modifiers, it's probably best to have C<qr//> stringify to the supplied pattern, note that this will create undesired patterns in cases such as: my $x = qr/a|b/; # "a|b" my $y = qr/c/i; # "c" my $z = qr/$x$y/; # "a|bc" There's no solution for this problem other than making the custom engine understand a construct like C<(?:)>. =head2 C<seen_evals> This stores the number of eval groups in the pattern. This is used for security purposes when embedding compiled regexes into larger patterns with C<qr//>. =head2 C<refcnt> The number of times the structure is referenced. When this falls to 0 the regexp is automatically freed by a call to pregfree. This should be set to 1 in each engine's L</comp> routine. =head1 HISTORY Originally part of L<perlreguts>. =head1 AUTHORS Originally written by Yves Orton, expanded by E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason. =head1 LICENSE Copyright 2006 Yves Orton and 2007 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK PU�\�!R� � perlbot.podnu �[��� =encoding utf8 =head1 NAME perlbot - This document has been deleted =head1 DESCRIPTION For information on OO programming with Perl, please see L<perlootut> and L<perlobj>. =cut PK PU�\~C &B5 B5 perlunifaq.podnu �[��� =head1 NAME perlunifaq - Perl Unicode FAQ =head1 Q and A This is a list of questions and answers about Unicode in Perl, intended to be read after L<perlunitut>. =head2 perlunitut isn't really a Unicode tutorial, is it? No, and this isn't really a Unicode FAQ. Perl has an abstracted interface for all supported character encodings, so this is actually a generic C<Encode> tutorial and C<Encode> FAQ. But many people think that Unicode is special and magical, and I didn't want to disappoint them, so I decided to call the document a Unicode tutorial. =head2 What character encodings does Perl support? To find out which character encodings your Perl supports, run: perl -MEncode -le "print for Encode->encodings(':all')" =head2 Which version of perl should I use? Well, if you can, upgrade to the most recent, but certainly C<5.8.1> or newer. The tutorial and FAQ assume the latest release. You should also check your modules, and upgrade them if necessary. For example, HTML::Entities requires version >= 1.32 to function correctly, even though the changelog is silent about this. =head2 What about binary data, like images? Well, apart from a bare C<binmode $fh>, you shouldn't treat them specially. (The binmode is needed because otherwise Perl may convert line endings on Win32 systems.) Be careful, though, to never combine text strings with binary strings. If you need text in a binary stream, encode your text strings first using the appropriate encoding, then join them with binary strings. See also: "What if I don't encode?". =head2 When should I decode or encode? Whenever you're communicating text with anything that is external to your perl process, like a database, a text file, a socket, or another program. Even if the thing you're communicating with is also written in Perl. =head2 What if I don't decode? Whenever your encoded, binary string is used together with a text string, Perl will assume that your binary string was encoded with ISO-8859-1, also known as latin-1. If it wasn't latin-1, then your data is unpleasantly converted. For example, if it was UTF-8, the individual bytes of multibyte characters are seen as separate characters, and then again converted to UTF-8. Such double encoding can be compared to double HTML encoding (C<&gt;>), or double URI encoding (C<%253E>). This silent implicit decoding is known as "upgrading". That may sound positive, but it's best to avoid it. =head2 What if I don't encode? Your text string will be sent using the bytes in Perl's internal format. In some cases, Perl will warn you that you're doing something wrong, with a friendly warning: Wide character in print at example.pl line 2. Because the internal format is often UTF-8, these bugs are hard to spot, because UTF-8 is usually the encoding you wanted! But don't be lazy, and don't use the fact that Perl's internal format is UTF-8 to your advantage. Encode explicitly to avoid weird bugs, and to show to maintenance programmers that you thought this through. =head2 Is there a way to automatically decode or encode? If all data that comes from a certain handle is encoded in exactly the same way, you can tell the PerlIO system to automatically decode everything, with the C<encoding> layer. If you do this, you can't accidentally forget to decode or encode anymore, on things that use the layered handle. You can provide this layer when C<open>ing the file: open my $fh, '>:encoding(UTF-8)', $filename; # auto encoding on write open my $fh, '<:encoding(UTF-8)', $filename; # auto decoding on read Or if you already have an open filehandle: binmode $fh, ':encoding(UTF-8)'; Some database drivers for DBI can also automatically encode and decode, but that is sometimes limited to the UTF-8 encoding. =head2 What if I don't know which encoding was used? Do whatever you can to find out, and if you have to: guess. (Don't forget to document your guess with a comment.) You could open the document in a web browser, and change the character set or character encoding until you can visually confirm that all characters look the way they should. There is no way to reliably detect the encoding automatically, so if people keep sending you data without charset indication, you may have to educate them. =head2 Can I use Unicode in my Perl sources? Yes, you can! If your sources are UTF-8 encoded, you can indicate that with the C<use utf8> pragma. use utf8; This doesn't do anything to your input, or to your output. It only influences the way your sources are read. You can use Unicode in string literals, in identifiers (but they still have to be "word characters" according to C<\w>), and even in custom delimiters. =head2 Data::Dumper doesn't restore the UTF8 flag; is it broken? No, Data::Dumper's Unicode abilities are as they should be. There have been some complaints that it should restore the UTF8 flag when the data is read again with C<eval>. However, you should really not look at the flag, and nothing indicates that Data::Dumper should break this rule. Here's what happens: when Perl reads in a string literal, it sticks to 8 bit encoding as long as it can. (But perhaps originally it was internally encoded as UTF-8, when you dumped it.) When it has to give that up because other characters are added to the text string, it silently upgrades the string to UTF-8. If you properly encode your strings for output, none of this is of your concern, and you can just C<eval> dumped data as always. =head2 Why do regex character classes sometimes match only in the ASCII range? =head2 Why do some characters not uppercase or lowercase correctly? Starting in Perl 5.14 (and partially in Perl 5.12), just put a C<use feature 'unicode_strings'> near the beginning of your program. Within its lexical scope you shouldn't have this problem. It also is automatically enabled under C<use feature ':5.12'> or using C<-E> on the command line for Perl 5.12 or higher. The rationale for requiring this is to not break older programs that rely on the way things worked before Unicode came along. Those older programs knew only about the ASCII character set, and so may not work properly for additional characters. When a string is encoded in UTF-8, Perl assumes that the program is prepared to deal with Unicode, but when the string isn't, Perl assumes that only ASCII (unless it is an EBCDIC platform) is wanted, and so those characters that are not ASCII characters aren't recognized as to what they would be in Unicode. C<use feature 'unicode_strings'> tells Perl to treat all characters as Unicode, whether the string is encoded in UTF-8 or not, thus avoiding the problem. However, on earlier Perls, or if you pass strings to subroutines outside the feature's scope, you can force Unicode semantics by changing the encoding to UTF-8 by doing C<utf8::upgrade($string)>. This can be used safely on any string, as it checks and does not change strings that have already been upgraded. For a more detailed discussion, see L<Unicode::Semantics> on CPAN. =head2 How can I determine if a string is a text string or a binary string? You can't. Some use the UTF8 flag for this, but that's misuse, and makes well behaved modules like Data::Dumper look bad. The flag is useless for this purpose, because it's off when an 8 bit encoding (by default ISO-8859-1) is used to store the string. This is something you, the programmer, has to keep track of; sorry. You could consider adopting a kind of "Hungarian notation" to help with this. =head2 How do I convert from encoding FOO to encoding BAR? By first converting the FOO-encoded byte string to a text string, and then the text string to a BAR-encoded byte string: my $text_string = decode('FOO', $foo_string); my $bar_string = encode('BAR', $text_string); or by skipping the text string part, and going directly from one binary encoding to the other: use Encode qw(from_to); from_to($string, 'FOO', 'BAR'); # changes contents of $string or by letting automatic decoding and encoding do all the work: open my $foofh, '<:encoding(FOO)', 'example.foo.txt'; open my $barfh, '>:encoding(BAR)', 'example.bar.txt'; print { $barfh } $_ while <$foofh>; =head2 What are C<decode_utf8> and C<encode_utf8>? These are alternate syntaxes for C<decode('utf8', ...)> and C<encode('utf8', ...)>. =head2 What is a "wide character"? This is a term used both for characters with an ordinal value greater than 127, characters with an ordinal value greater than 255, or any character occupying more than one byte, depending on the context. The Perl warning "Wide character in ..." is caused by a character with an ordinal value greater than 255. With no specified encoding layer, Perl tries to fit things in ISO-8859-1 for backward compatibility reasons. When it can't, it emits this warning (if warnings are enabled), and outputs UTF-8 encoded data instead. To avoid this warning and to avoid having different output encodings in a single stream, always specify an encoding explicitly, for example with a PerlIO layer: binmode STDOUT, ":encoding(UTF-8)"; =head1 INTERNALS =head2 What is "the UTF8 flag"? Please, unless you're hacking the internals, or debugging weirdness, don't think about the UTF8 flag at all. That means that you very probably shouldn't use C<is_utf8>, C<_utf8_on> or C<_utf8_off> at all. The UTF8 flag, also called SvUTF8, is an internal flag that indicates that the current internal representation is UTF-8. Without the flag, it is assumed to be ISO-8859-1. Perl converts between these automatically. (Actually Perl usually assumes the representation is ASCII; see L</Why do regex character classes sometimes match only in the ASCII range?> above.) One of Perl's internal formats happens to be UTF-8. Unfortunately, Perl can't keep a secret, so everyone knows about this. That is the source of much confusion. It's better to pretend that the internal format is some unknown encoding, and that you always have to encode and decode explicitly. =head2 What about the C<use bytes> pragma? Don't use it. It makes no sense to deal with bytes in a text string, and it makes no sense to deal with characters in a byte string. Do the proper conversions (by decoding/encoding), and things will work out well: you get character counts for decoded data, and byte counts for encoded data. C<use bytes> is usually a failed attempt to do something useful. Just forget about it. =head2 What about the C<use encoding> pragma? Don't use it. Unfortunately, it assumes that the programmer's environment and that of the user will use the same encoding. It will use the same encoding for the source code and for STDIN and STDOUT. When a program is copied to another machine, the source code does not change, but the STDIO environment might. If you need non-ASCII characters in your source code, make it a UTF-8 encoded file and C<use utf8>. If you need to set the encoding for STDIN, STDOUT, and STDERR, for example based on the user's locale, C<use open>. =head2 What is the difference between C<:encoding> and C<:utf8>? Because UTF-8 is one of Perl's internal formats, you can often just skip the encoding or decoding step, and manipulate the UTF8 flag directly. Instead of C<:encoding(UTF-8)>, you can simply use C<:utf8>, which skips the encoding step if the data was already represented as UTF8 internally. This is widely accepted as good behavior when you're writing, but it can be dangerous when reading, because it causes internal inconsistency when you have invalid byte sequences. Using C<:utf8> for input can sometimes result in security breaches, so please use C<:encoding(UTF-8)> instead. Instead of C<decode> and C<encode>, you could use C<_utf8_on> and C<_utf8_off>, but this is considered bad style. Especially C<_utf8_on> can be dangerous, for the same reason that C<:utf8> can. There are some shortcuts for oneliners; see L<-C|perlrun/-C [numberE<sol>list]> in L<perlrun>. =head2 What's the difference between C<UTF-8> and C<utf8>? C<UTF-8> is the official standard. C<utf8> is Perl's way of being liberal in what it accepts. If you have to communicate with things that aren't so liberal, you may want to consider using C<UTF-8>. If you have to communicate with things that are too liberal, you may have to use C<utf8>. The full explanation is in L<Encode>. C<UTF-8> is internally known as C<utf-8-strict>. The tutorial uses UTF-8 consistently, even where utf8 is actually used internally, because the distinction can be hard to make, and is mostly irrelevant. For example, utf8 can be used for code points that don't exist in Unicode, like 9999999, but if you encode that to UTF-8, you get a substitution character (by default; see L<Encode/"Handling Malformed Data"> for more ways of dealing with this.) Okay, if you insist: the "internal format" is utf8, not UTF-8. (When it's not some other encoding.) =head2 I lost track; what encoding is the internal format really? It's good that you lost track, because you shouldn't depend on the internal format being any specific encoding. But since you asked: by default, the internal format is either ISO-8859-1 (latin-1), or utf8, depending on the history of the string. On EBCDIC platforms, this may be different even. Perl knows how it stored the string internally, and will use that knowledge when you C<encode>. In other words: don't try to find out what the internal encoding for a certain string is, but instead just encode it into the encoding that you want. =head1 AUTHOR Juerd Waalboer <#####@juerd.nl> =head1 SEE ALSO L<perlunicode>, L<perluniintro>, L<Encode> PK PU�\0���"j "j perlos2.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see perlpod manpage) which is specially designed to be readable as is. =head1 NAME perlos2 - Perl under OS/2, DOS, Win0.3*, Win0.95 and WinNT. =head1 SYNOPSIS One can read this document in the following formats: man perlos2 view perl perlos2 explorer perlos2.html info perlos2 to list some (not all may be available simultaneously), or it may be read I<as is>: either as F<README.os2>, or F<pod/perlos2.pod>. To read the F<.INF> version of documentation (B<very> recommended) outside of OS/2, one needs an IBM's reader (may be available on IBM ftp sites (?) (URL anyone?)) or shipped with PC DOS 7.0 and IBM's Visual Age C++ 3.5. A copy of a Win* viewer is contained in the "Just add OS/2 Warp" package ftp://ftp.software.ibm.com/ps/products/os2/tools/jaow/jaow.zip in F<?:\JUST_ADD\view.exe>. This gives one an access to EMX's F<.INF> docs as well (text form is available in F</emx/doc> in EMX's distribution). There is also a different viewer named xview. Note that if you have F<lynx.exe> or F<netscape.exe> installed, you can follow WWW links from this document in F<.INF> format. If you have EMX docs installed correctly, you can follow library links (you need to have C<view emxbook> working by setting C<EMXBOOK> environment variable as it is described in EMX docs). =cut Contents (This may be a little bit obsolete) perlos2 - Perl under OS/2, DOS, Win0.3*, Win0.95 and WinNT. NAME SYNOPSIS DESCRIPTION - Target - Other OSes - Prerequisites - Starting Perl programs under OS/2 (and DOS and...) - Starting OS/2 (and DOS) programs under Perl Frequently asked questions - "It does not work" - I cannot run external programs - I cannot embed perl into my program, or use perl.dll from my - `` and pipe-open do not work under DOS. - Cannot start find.exe "pattern" file INSTALLATION - Automatic binary installation - Manual binary installation - Warning Accessing documentation - OS/2 .INF file - Plain text - Manpages - HTML - GNU info files - PDF files - LaTeX docs BUILD - The short story - Prerequisites - Getting perl source - Application of the patches - Hand-editing - Making - Testing - Installing the built perl - a.out-style build Build FAQ - Some / became \ in pdksh. - 'errno' - unresolved external - Problems with tr or sed - Some problem (forget which ;-) - Library ... not found - Segfault in make - op/sprintf test failure Specific (mis)features of OS/2 port - setpriority, getpriority - system() - extproc on the first line - Additional modules: - Prebuilt methods: - Prebuilt variables: - Misfeatures - Modifications - Identifying DLLs - Centralized management of resources Perl flavors - perl.exe - perl_.exe - perl__.exe - perl___.exe - Why strange names? - Why dynamic linking? - Why chimera build? ENVIRONMENT - PERLLIB_PREFIX - PERL_BADLANG - PERL_BADFREE - PERL_SH_DIR - USE_PERL_FLOCK - TMP or TEMP Evolution - Text-mode filehandles - Priorities - DLL name mangling: pre 5.6.2 - DLL name mangling: 5.6.2 and beyond - DLL forwarder generation - Threading - Calls to external programs - Memory allocation - Threads BUGS AUTHOR SEE ALSO =head1 DESCRIPTION =head2 Target The target is to make OS/2 one of the best supported platform for using/building/developing Perl and I<Perl applications>, as well as make Perl the best language to use under OS/2. The secondary target is to try to make this work under DOS and Win* as well (but not B<too> hard). The current state is quite close to this target. Known limitations: =over 5 =item * Some *nix programs use fork() a lot; with the mostly useful flavors of perl for OS/2 (there are several built simultaneously) this is supported; but some flavors do not support this (e.g., when Perl is called from inside REXX). Using fork() after I<use>ing dynamically loading extensions would not work with I<very> old versions of EMX. =item * You need a separate perl executable F<perl__.exe> (see L</perl__.exe>) if you want to use PM code in your application (as Perl/Tk or OpenGL Perl modules do) without having a text-mode window present. While using the standard F<perl.exe> from a text-mode window is possible too, I have seen cases when this causes degradation of the system stability. Using F<perl__.exe> avoids such a degradation. =item * There is no simple way to access WPS objects. The only way I know is via C<OS2::REXX> and C<SOM> extensions (see L<OS2::REXX>, L<SOM>). However, we do not have access to convenience methods of Object-REXX. (Is it possible at all? I know of no Object-REXX API.) The C<SOM> extension (currently in alpha-text) may eventually remove this shortcoming; however, due to the fact that DII is not supported by the C<SOM> module, using C<SOM> is not as convenient as one would like it. =back Please keep this list up-to-date by informing me about other items. =head2 Other OSes Since OS/2 port of perl uses a remarkable EMX environment, it can run (and build extensions, and - possibly - be built itself) under any environment which can run EMX. The current list is DOS, DOS-inside-OS/2, Win0.3*, Win0.95 and WinNT. Out of many perl flavors, only one works, see L<"perl_.exe">. Note that not all features of Perl are available under these environments. This depends on the features the I<extender> - most probably RSX - decided to implement. Cf. L</Prerequisites>. =head2 Prerequisites =over 6 =item EMX EMX runtime is required (may be substituted by RSX). Note that it is possible to make F<perl_.exe> to run under DOS without any external support by binding F<emx.exe>/F<rsx.exe> to it, see C<emxbind>. Note that under DOS for best results one should use RSX runtime, which has much more functions working (like C<fork>, C<popen> and so on). In fact RSX is required if there is no VCPI present. Note the RSX requires DPMI. Many implementations of DPMI are known to be very buggy, beware! Only the latest runtime is supported, currently C<0.9d fix 03>. Perl may run under earlier versions of EMX, but this is not tested. One can get different parts of EMX from, say ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/emx+gcc/ http://hobbes.nmsu.edu/h-browse.php?dir=/pub/os2/dev/emx/v0.9d/ The runtime component should have the name F<emxrt.zip>. B<NOTE>. When using F<emx.exe>/F<rsx.exe>, it is enough to have them on your path. One does not need to specify them explicitly (though this emx perl_.exe -de 0 will work as well.) =item RSX To run Perl on DPMI platforms one needs RSX runtime. This is needed under DOS-inside-OS/2, Win0.3*, Win0.95 and WinNT (see L<"Other OSes">). RSX would not work with VCPI only, as EMX would, it requires DMPI. Having RSX and the latest F<sh.exe> one gets a fully functional B<*nix>-ish environment under DOS, say, C<fork>, C<``> and pipe-C<open> work. In fact, MakeMaker works (for static build), so one can have Perl development environment under DOS. One can get RSX from, say http://cd.textfiles.com/hobbesos29804/disk1/EMX09C/ ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/emx+gcc/contrib/ Contact the author on C<rainer@mathematik.uni-bielefeld.de>. The latest F<sh.exe> with DOS hooks is available in http://www.ilyaz.org/software/os2/ as F<sh_dos.zip> or under similar names starting with C<sh>, C<pdksh> etc. =item HPFS Perl does not care about file systems, but the perl library contains many files with long names, so to install it intact one needs a file system which supports long file names. Note that if you do not plan to build the perl itself, it may be possible to fool EMX to truncate file names. This is not supported, read EMX docs to see how to do it. =item pdksh To start external programs with complicated command lines (like with pipes in between, and/or quoting of arguments), Perl uses an external shell. With EMX port such shell should be named F<sh.exe>, and located either in the wired-in-during-compile locations (usually F<F:/bin>), or in configurable location (see L<"PERL_SH_DIR">). For best results use EMX pdksh. The standard binary (5.2.14 or later) runs under DOS (with L</RSX>) as well, see http://www.ilyaz.org/software/os2/ =back =head2 Starting Perl programs under OS/2 (and DOS and...) Start your Perl program F<foo.pl> with arguments C<arg1 arg2 arg3> the same way as on any other platform, by perl foo.pl arg1 arg2 arg3 If you want to specify perl options C<-my_opts> to the perl itself (as opposed to your program), use perl -my_opts foo.pl arg1 arg2 arg3 Alternately, if you use OS/2-ish shell, like CMD or 4os2, put the following at the start of your perl script: extproc perl -S -my_opts rename your program to F<foo.cmd>, and start it by typing foo arg1 arg2 arg3 Note that because of stupid OS/2 limitations the full path of the perl script is not available when you use C<extproc>, thus you are forced to use C<-S> perl switch, and your script should be on the C<PATH>. As a plus side, if you know a full path to your script, you may still start it with perl ../../blah/foo.cmd arg1 arg2 arg3 (note that the argument C<-my_opts> is taken care of by the C<extproc> line in your script, see L<C<extproc> on the first line>). To understand what the above I<magic> does, read perl docs about C<-S> switch - see L<perlrun>, and cmdref about C<extproc>: view perl perlrun man perlrun view cmdref extproc help extproc or whatever method you prefer. There are also endless possibilities to use I<executable extensions> of 4os2, I<associations> of WPS and so on... However, if you use *nixish shell (like F<sh.exe> supplied in the binary distribution), you need to follow the syntax specified in L<perlrun/"Command Switches">. Note that B<-S> switch supports scripts with additional extensions F<.cmd>, F<.btm>, F<.bat>, F<.pl> as well. =head2 Starting OS/2 (and DOS) programs under Perl This is what system() (see L<perlfunc/system>), C<``> (see L<perlop/"I/O Operators">), and I<open pipe> (see L<perlfunc/open>) are for. (Avoid exec() (see L<perlfunc/exec>) unless you know what you do). Note however that to use some of these operators you need to have a sh-syntax shell installed (see L<"Pdksh">, L<"Frequently asked questions">), and perl should be able to find it (see L<"PERL_SH_DIR">). The cases when the shell is used are: =over =item 1 One-argument system() (see L<perlfunc/system>), exec() (see L<perlfunc/exec>) with redirection or shell meta-characters; =item 2 Pipe-open (see L<perlfunc/open>) with the command which contains redirection or shell meta-characters; =item 3 Backticks C<``> (see L<perlop/"I/O Operators">) with the command which contains redirection or shell meta-characters; =item 4 If the executable called by system()/exec()/pipe-open()/C<``> is a script with the "magic" C<#!> line or C<extproc> line which specifies shell; =item 5 If the executable called by system()/exec()/pipe-open()/C<``> is a script without "magic" line, and C<$ENV{EXECSHELL}> is set to shell; =item 6 If the executable called by system()/exec()/pipe-open()/C<``> is not found (is not this remark obsolete?); =item 7 For globbing (see L<perlfunc/glob>, L<perlop/"I/O Operators">) (obsolete? Perl uses builtin globbing nowadays...). =back For the sake of speed for a common case, in the above algorithms backslashes in the command name are not considered as shell metacharacters. Perl starts scripts which begin with cookies C<extproc> or C<#!> directly, without an intervention of shell. Perl uses the same algorithm to find the executable as F<pdksh>: if the path on C<#!> line does not work, and contains C</>, then the directory part of the executable is ignored, and the executable is searched in F<.> and on C<PATH>. To find arguments for these scripts Perl uses a different algorithm than F<pdksh>: up to 3 arguments are recognized, and trailing whitespace is stripped. If a script does not contain such a cooky, then to avoid calling F<sh.exe>, Perl uses the same algorithm as F<pdksh>: if C<$ENV{EXECSHELL}> is set, the script is given as the first argument to this command, if not set, then C<$ENV{COMSPEC} /c> is used (or a hardwired guess if C<$ENV{COMSPEC}> is not set). When starting scripts directly, Perl uses exactly the same algorithm as for the search of script given by B<-S> command-line option: it will look in the current directory, then on components of C<$ENV{PATH}> using the following order of appended extensions: no extension, F<.cmd>, F<.btm>, F<.bat>, F<.pl>. Note that Perl will start to look for scripts only if OS/2 cannot start the specified application, thus C<system 'blah'> will not look for a script if there is an executable file F<blah.exe> I<anywhere> on C<PATH>. In other words, C<PATH> is essentially searched twice: once by the OS for an executable, then by Perl for scripts. Note also that executable files on OS/2 can have an arbitrary extension, but F<.exe> will be automatically appended if no dot is present in the name. The workaround is as simple as that: since F<blah.> and F<blah> denote the same file (at list on FAT and HPFS file systems), to start an executable residing in file F<n:/bin/blah> (no extension) give an argument C<n:/bin/blah.> (dot appended) to system(). Perl will start PM programs from VIO (=text-mode) Perl process in a separate PM session; the opposite is not true: when you start a non-PM program from a PM Perl process, Perl would not run it in a separate session. If a separate session is desired, either ensure that shell will be used, as in C<system 'cmd /c myprog'>, or start it using optional arguments to system() documented in C<OS2::Process> module. This is considered to be a feature. =head1 Frequently asked questions =head2 "It does not work" Perl binary distributions come with a F<testperl.cmd> script which tries to detect common problems with misconfigured installations. There is a pretty large chance it will discover which step of the installation you managed to goof. C<;-)> =head2 I cannot run external programs =over 4 =item * Did you run your programs with C<-w> switch? See L<Starting OSE<sol>2 (and DOS) programs under Perl>. =item * Do you try to run I<internal> shell commands, like C<`copy a b`> (internal for F<cmd.exe>), or C<`glob a*b`> (internal for ksh)? You need to specify your shell explicitly, like C<`cmd /c copy a b`>, since Perl cannot deduce which commands are internal to your shell. =back =head2 I cannot embed perl into my program, or use F<perl.dll> from my program. =over 4 =item Is your program EMX-compiled with C<-Zmt -Zcrtdll>? Well, nowadays Perl DLL should be usable from a differently compiled program too... If you can run Perl code from REXX scripts (see L<OS2::REXX>), then there are some other aspect of interaction which are overlooked by the current hackish code to support differently-compiled principal programs. If everything else fails, you need to build a stand-alone DLL for perl. Contact me, I did it once. Sockets would not work, as a lot of other stuff. =item Did you use L<ExtUtils::Embed>? Some time ago I had reports it does not work. Nowadays it is checked in the Perl test suite, so grep F<./t> subdirectory of the build tree (as well as F<*.t> files in the F<./lib> subdirectory) to find how it should be done "correctly". =back =head2 C<``> and pipe-C<open> do not work under DOS. This may a variant of just L<"I cannot run external programs">, or a deeper problem. Basically: you I<need> RSX (see L</Prerequisites>) for these commands to work, and you may need a port of F<sh.exe> which understands command arguments. One of such ports is listed in L</Prerequisites> under RSX. Do not forget to set variable C<L<"PERL_SH_DIR">> as well. DPMI is required for RSX. =head2 Cannot start C<find.exe "pattern" file> The whole idea of the "standard C API to start applications" is that the forms C<foo> and C<"foo"> of program arguments are completely interchangeable. F<find> breaks this paradigm; find "pattern" file find pattern file are not equivalent; F<find> cannot be started directly using the above API. One needs a way to surround the doublequotes in some other quoting construction, necessarily having an extra non-Unixish shell in between. Use one of system 'cmd', '/c', 'find "pattern" file'; `cmd /c 'find "pattern" file'` This would start F<find.exe> via F<cmd.exe> via C<sh.exe> via C<perl.exe>, but this is a price to pay if you want to use non-conforming program. =head1 INSTALLATION =head2 Automatic binary installation The most convenient way of installing a binary distribution of perl is via perl installer F<install.exe>. Just follow the instructions, and 99% of the installation blues would go away. Note however, that you need to have F<unzip.exe> on your path, and EMX environment I<running>. The latter means that if you just installed EMX, and made all the needed changes to F<Config.sys>, you may need to reboot in between. Check EMX runtime by running emxrev Binary installer also creates a folder on your desktop with some useful objects. If you need to change some aspects of the work of the binary installer, feel free to edit the file F<Perl.pkg>. This may be useful e.g., if you need to run the installer many times and do not want to make many interactive changes in the GUI. B<Things not taken care of by automatic binary installation:> =over 15 =item C<PERL_BADLANG> may be needed if you change your codepage I<after> perl installation, and the new value is not supported by EMX. See L<"PERL_BADLANG">. =item C<PERL_BADFREE> see L<"PERL_BADFREE">. =item F<Config.pm> This file resides somewhere deep in the location you installed your perl library, find it out by perl -MConfig -le "print $INC{'Config.pm'}" While most important values in this file I<are> updated by the binary installer, some of them may need to be hand-edited. I know no such data, please keep me informed if you find one. Moreover, manual changes to the installed version may need to be accompanied by an edit of this file. =back B<NOTE>. Because of a typo the binary installer of 5.00305 would install a variable C<PERL_SHPATH> into F<Config.sys>. Please remove this variable and put C<L</PERL_SH_DIR>> instead. =head2 Manual binary installation As of version 5.00305, OS/2 perl binary distribution comes split into 11 components. Unfortunately, to enable configurable binary installation, the file paths in the zip files are not absolute, but relative to some directory. Note that the extraction with the stored paths is still necessary (default with unzip, specify C<-d> to pkunzip). However, you need to know where to extract the files. You need also to manually change entries in F<Config.sys> to reflect where did you put the files. Note that if you have some primitive unzipper (like C<pkunzip>), you may get a lot of warnings/errors during unzipping. Upgrade to C<(w)unzip>. Below is the sample of what to do to reproduce the configuration on my machine. In F<VIEW.EXE> you can press C<Ctrl-Insert> now, and cut-and-paste from the resulting file - created in the directory you started F<VIEW.EXE> from. For each component, we mention environment variables related to each installation directory. Either choose directories to match your values of the variables, or create/append-to variables to take into account the directories. =over 3 =item Perl VIO and PM executables (dynamically linked) unzip perl_exc.zip *.exe *.ico -d f:/emx.add/bin unzip perl_exc.zip *.dll -d f:/emx.add/dll (have the directories with C<*.exe> on PATH, and C<*.dll> on LIBPATH); =item Perl_ VIO executable (statically linked) unzip perl_aou.zip -d f:/emx.add/bin (have the directory on PATH); =item Executables for Perl utilities unzip perl_utl.zip -d f:/emx.add/bin (have the directory on PATH); =item Main Perl library unzip perl_mlb.zip -d f:/perllib/lib If this directory is exactly the same as the prefix which was compiled into F<perl.exe>, you do not need to change anything. However, for perl to find the library if you use a different path, you need to C<set PERLLIB_PREFIX> in F<Config.sys>, see L<"PERLLIB_PREFIX">. =item Additional Perl modules unzip perl_ste.zip -d f:/perllib/lib/site_perl/5.16.3/ Same remark as above applies. Additionally, if this directory is not one of directories on @INC (and @INC is influenced by C<PERLLIB_PREFIX>), you need to put this directory and subdirectory F<./os2> in C<PERLLIB> or C<PERL5LIB> variable. Do not use C<PERL5LIB> unless you have it set already. See L<perl/"ENVIRONMENT">. B<[Check whether this extraction directory is still applicable with the new directory structure layout!]> =item Tools to compile Perl modules unzip perl_blb.zip -d f:/perllib/lib Same remark as for F<perl_ste.zip>. =item Manpages for Perl and utilities unzip perl_man.zip -d f:/perllib/man This directory should better be on C<MANPATH>. You need to have a working F<man> to access these files. =item Manpages for Perl modules unzip perl_mam.zip -d f:/perllib/man This directory should better be on C<MANPATH>. You need to have a working man to access these files. =item Source for Perl documentation unzip perl_pod.zip -d f:/perllib/lib This is used by the C<perldoc> program (see L<perldoc>), and may be used to generate HTML documentation usable by WWW browsers, and documentation in zillions of other formats: C<info>, C<LaTeX>, C<Acrobat>, C<FrameMaker> and so on. [Use programs such as F<pod2latex> etc.] =item Perl manual in F<.INF> format unzip perl_inf.zip -d d:/os2/book This directory should better be on C<BOOKSHELF>. =item Pdksh unzip perl_sh.zip -d f:/bin This is used by perl to run external commands which explicitly require shell, like the commands using I<redirection> and I<shell metacharacters>. It is also used instead of explicit F</bin/sh>. Set C<PERL_SH_DIR> (see L<"PERL_SH_DIR">) if you move F<sh.exe> from the above location. B<Note.> It may be possible to use some other sh-compatible shell (untested). =back After you installed the components you needed and updated the F<Config.sys> correspondingly, you need to hand-edit F<Config.pm>. This file resides somewhere deep in the location you installed your perl library, find it out by perl -MConfig -le "print $INC{'Config.pm'}" You need to correct all the entries which look like file paths (they currently start with C<f:/>). =head2 B<Warning> The automatic and manual perl installation leave precompiled paths inside perl executables. While these paths are overwriteable (see L<"PERLLIB_PREFIX">, L<"PERL_SH_DIR">), some people may prefer binary editing of paths inside the executables/DLLs. =head1 Accessing documentation Depending on how you built/installed perl you may have (otherwise identical) Perl documentation in the following formats: =head2 OS/2 F<.INF> file Most probably the most convenient form. Under OS/2 view it as view perl view perl perlfunc view perl less view perl ExtUtils::MakeMaker (currently the last two may hit a wrong location, but this may improve soon). Under Win* see L<"SYNOPSIS">. If you want to build the docs yourself, and have I<OS/2 toolkit>, run pod2ipf > perl.ipf in F</perllib/lib/pod> directory, then ipfc /inf perl.ipf (Expect a lot of errors during the both steps.) Now move it on your BOOKSHELF path. =head2 Plain text If you have perl documentation in the source form, perl utilities installed, and GNU groff installed, you may use perldoc perlfunc perldoc less perldoc ExtUtils::MakeMaker to access the perl documentation in the text form (note that you may get better results using perl manpages). Alternately, try running pod2text on F<.pod> files. =head2 Manpages If you have F<man> installed on your system, and you installed perl manpages, use something like this: man perlfunc man 3 less man ExtUtils.MakeMaker to access documentation for different components of Perl. Start with man perl Note that dot (F<.>) is used as a package separator for documentation for packages, and as usual, sometimes you need to give the section - C<3> above - to avoid shadowing by the I<less(1) manpage>. Make sure that the directory B<above> the directory with manpages is on our C<MANPATH>, like this set MANPATH=c:/man;f:/perllib/man for Perl manpages in C<f:/perllib/man/man1/> etc. =head2 HTML If you have some WWW browser available, installed the Perl documentation in the source form, and Perl utilities, you can build HTML docs. Cd to directory with F<.pod> files, and do like this cd f:/perllib/lib/pod pod2html After this you can direct your browser the file F<perl.html> in this directory, and go ahead with reading docs, like this: explore file:///f:/perllib/lib/pod/perl.html Alternatively you may be able to get these docs prebuilt from CPAN. =head2 GNU C<info> files Users of Emacs would appreciate it very much, especially with C<CPerl> mode loaded. You need to get latest C<pod2texi> from C<CPAN>, or, alternately, the prebuilt info pages. =head2 F<PDF> files for C<Acrobat> are available on CPAN (may be for slightly older version of perl). =head2 C<LaTeX> docs can be constructed using C<pod2latex>. =head1 BUILD Here we discuss how to build Perl under OS/2. =head2 The short story Assume that you are a seasoned porter, so are sure that all the necessary tools are already present on your system, and you know how to get the Perl source distribution. Untar it, change to the extract directory, and gnupatch -p0 < os2\diff.configure sh Configure -des -D prefix=f:/perllib make make test make install make aout_test make aout_install This puts the executables in f:/perllib/bin. Manually move them to the C<PATH>, manually move the built F<perl*.dll> to C<LIBPATH> (here for Perl DLL F<*> is a not-very-meaningful hex checksum), and run make installcmd INSTALLCMDDIR=d:/ir/on/path Assuming that the C<man>-files were put on an appropriate location, this completes the installation of minimal Perl system. (The binary distribution contains also a lot of additional modules, and the documentation in INF format.) What follows is a detailed guide through these steps. =head2 Prerequisites You need to have the latest EMX development environment, the full GNU tool suite (gawk renamed to awk, and GNU F<find.exe> earlier on path than the OS/2 F<find.exe>, same with F<sort.exe>, to check use find --version sort --version ). You need the latest version of F<pdksh> installed as F<sh.exe>. Check that you have B<BSD> libraries and headers installed, and - optionally - Berkeley DB headers and libraries, and crypt. Possible locations to get the files: ftp://ftp.uni-heidelberg.de/pub/os2/unix/ http://hobbes.nmsu.edu/h-browse.php?dir=/pub/os2 http://cd.textfiles.com/hobbesos29804/disk1/DEV32/ http://cd.textfiles.com/hobbesos29804/disk1/EMX09C/ It is reported that the following archives contain enough utils to build perl: F<gnufutil.zip>, F<gnusutil.zip>, F<gnututil.zip>, F<gnused.zip>, F<gnupatch.zip>, F<gnuawk.zip>, F<gnumake.zip>, F<gnugrep.zip>, F<bsddev.zip> and F<ksh527rt.zip> (or a later version). Note that all these utilities are known to be available from LEO: ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/ Note also that the F<db.lib> and F<db.a> from the EMX distribution are not suitable for multi-threaded compile (even single-threaded flavor of Perl uses multi-threaded C RTL, for compatibility with XFree86-OS/2). Get a corrected one from http://www.ilyaz.org/software/os2/db_mt.zip If you have I<exactly the same version of Perl> installed already, make sure that no copies or perl are currently running. Later steps of the build may fail since an older version of F<perl.dll> loaded into memory may be found. Running C<make test> becomes meaningless, since the test are checking a previous build of perl (this situation is detected and reported by F<lib/os2_base.t> test). Do not forget to unset C<PERL_EMXLOAD_SEC> in environment. Also make sure that you have F</tmp> directory on the current drive, and F<.> directory in your C<LIBPATH>. One may try to correct the latter condition by set BEGINLIBPATH .\. if you use something like F<CMD.EXE> or latest versions of F<4os2.exe>. (Setting BEGINLIBPATH to just C<.> is ignored by the OS/2 kernel.) Make sure your gcc is good for C<-Zomf> linking: run C<omflibs> script in F</emx/lib> directory. Check that you have link386 installed. It comes standard with OS/2, but may be not installed due to customization. If typing link386 shows you do not have it, do I<Selective install>, and choose C<Link object modules> in I<Optional system utilities/More>. If you get into link386 prompts, press C<Ctrl-C> to exit. =head2 Getting perl source You need to fetch the latest perl source (including developers releases). With some probability it is located in http://www.cpan.org/src/ http://www.cpan.org/src/unsupported If not, you may need to dig in the indices to find it in the directory of the current maintainer. Quick cycle of developers release may break the OS/2 build time to time, looking into http://www.cpan.org/ports/os2/ may indicate the latest release which was publicly released by the maintainer. Note that the release may include some additional patches to apply to the current source of perl. Extract it like this tar vzxf perl5.00409.tar.gz You may see a message about errors while extracting F<Configure>. This is because there is a conflict with a similarly-named file F<configure>. Change to the directory of extraction. =head2 Application of the patches You need to apply the patches in F<./os2/diff.*> like this: gnupatch -p0 < os2\diff.configure You may also need to apply the patches supplied with the binary distribution of perl. It also makes sense to look on the perl5-porters mailing list for the latest OS/2-related patches (see L<http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/>). Such patches usually contain strings C</os2/> and C<patch>, so it makes sense looking for these strings. =head2 Hand-editing You may look into the file F<./hints/os2.sh> and correct anything wrong you find there. I do not expect it is needed anywhere. =head2 Making sh Configure -des -D prefix=f:/perllib C<prefix> means: where to install the resulting perl library. Giving correct prefix you may avoid the need to specify C<PERLLIB_PREFIX>, see L<"PERLLIB_PREFIX">. I<Ignore the message about missing C<ln>, and about C<-c> option to tr>. The latter is most probably already fixed, if you see it and can trace where the latter spurious warning comes from, please inform me. Now make At some moment the built may die, reporting a I<version mismatch> or I<unable to run F<perl>>. This means that you do not have F<.> in your LIBPATH, so F<perl.exe> cannot find the needed F<perl67B2.dll> (treat these hex digits as line noise). After this is fixed the build should finish without a lot of fuss. =head2 Testing Now run make test All tests should succeed (with some of them skipped). If you have the same version of Perl installed, it is crucial that you have C<.> early in your LIBPATH (or in BEGINLIBPATH), otherwise your tests will most probably test the wrong version of Perl. Some tests may generate extra messages similar to =over 4 =item A lot of C<bad free> in database tests related to Berkeley DB. I<This should be fixed already.> If it persists, you may disable this warnings, see L<"PERL_BADFREE">. =item Process terminated by SIGTERM/SIGINT This is a standard message issued by OS/2 applications. *nix applications die in silence. It is considered to be a feature. One can easily disable this by appropriate sighandlers. However the test engine bleeds these message to screen in unexpected moments. Two messages of this kind I<should> be present during testing. =back To get finer test reports, call perl t/harness The report with F<io/pipe.t> failing may look like this: Failed Test Status Wstat Total Fail Failed List of failed ------------------------------------------------------------ io/pipe.t 12 1 8.33% 9 7 tests skipped, plus 56 subtests skipped. Failed 1/195 test scripts, 99.49% okay. 1/6542 subtests failed, 99.98% okay. The reasons for most important skipped tests are: =over 8 =item F<op/fs.t> =over 4 =item 18 Checks C<atime> and C<mtime> of C<stat()> - unfortunately, HPFS provides only 2sec time granularity (for compatibility with FAT?). =item 25 Checks C<truncate()> on a filehandle just opened for write - I do not know why this should or should not work. =back =item F<op/stat.t> Checks C<stat()>. Tests: =over 4 =item 4 Checks C<atime> and C<mtime> of C<stat()> - unfortunately, HPFS provides only 2sec time granularity (for compatibility with FAT?). =back =back =head2 Installing the built perl If you haven't yet moved C<perl*.dll> onto LIBPATH, do it now. Run make install It would put the generated files into needed locations. Manually put F<perl.exe>, F<perl__.exe> and F<perl___.exe> to a location on your PATH, F<perl.dll> to a location on your LIBPATH. Run make installcmd INSTALLCMDDIR=d:/ir/on/path to convert perl utilities to F<.cmd> files and put them on PATH. You need to put F<.EXE>-utilities on path manually. They are installed in C<$prefix/bin>, here C<$prefix> is what you gave to F<Configure>, see L</Making>. If you use C<man>, either move the installed F<*/man/> directories to your C<MANPATH>, or modify C<MANPATH> to match the location. (One could have avoided this by providing a correct C<manpath> option to F<./Configure>, or editing F<./config.sh> between configuring and making steps.) =head2 C<a.out>-style build Proceed as above, but make F<perl_.exe> (see L<"perl_.exe">) by make perl_ test and install by make aout_test make aout_install Manually put F<perl_.exe> to a location on your PATH. B<Note.> The build process for C<perl_> I<does not know> about all the dependencies, so you should make sure that anything is up-to-date, say, by doing make perl_dll first. =head1 Building a binary distribution [This section provides a short overview only...] Building should proceed differently depending on whether the version of perl you install is already present and used on your system, or is a new version not yet used. The description below assumes that the version is new, so installing its DLLs and F<.pm> files will not disrupt the operation of your system even if some intermediate steps are not yet fully working. The other cases require a little bit more convoluted procedures. Below I suppose that the current version of Perl is C<5.8.2>, so the executables are named accordingly. =over =item 1. Fully build and test the Perl distribution. Make sure that no tests are failing with C<test> and C<aout_test> targets; fix the bugs in Perl and the Perl test suite detected by these tests. Make sure that C<all_test> make target runs as clean as possible. Check that F<os2/perlrexx.cmd> runs fine. =item 2. Fully install Perl, including C<installcmd> target. Copy the generated DLLs to C<LIBPATH>; copy the numbered Perl executables (as in F<perl5.8.2.exe>) to C<PATH>; copy C<perl_.exe> to C<PATH> as C<perl_5.8.2.exe>. Think whether you need backward-compatibility DLLs. In most cases you do not need to install them yet; but sometime this may simplify the following steps. =item 3. Make sure that C<CPAN.pm> can download files from CPAN. If not, you may need to manually install C<Net::FTP>. =item 4. Install the bundle C<Bundle::OS2_default> perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_1 This may take a couple of hours on 1GHz processor (when run the first time). And this should not be necessarily a smooth procedure. Some modules may not specify required dependencies, so one may need to repeat this procedure several times until the results stabilize. perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_2 perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_3 Even after they stabilize, some tests may fail. Fix as many discovered bugs as possible. Document all the bugs which are not fixed, and all the failures with unknown reasons. Inspect the produced logs F<00cpan_i_1> to find suspiciously skipped tests, and other fishy events. Keep in mind that I<installation> of some modules may fail too: for example, the DLLs to update may be already loaded by F<CPAN.pm>. Inspect the C<install> logs (in the example above F<00cpan_i_1> etc) for errors, and install things manually, as in cd $CPANHOME/.cpan/build/Digest-MD5-2.31 make install Some distributions may fail some tests, but you may want to install them anyway (as above, or via C<force install> command of C<CPAN.pm> shell-mode). Since this procedure may take quite a long time to complete, it makes sense to "freeze" your CPAN configuration by disabling periodic updates of the local copy of CPAN index: set C<index_expire> to some big value (I use 365), then save the settings CPAN> o conf index_expire 365 CPAN> o conf commit Reset back to the default value C<1> when you are finished. =item 5. When satisfied with the results, rerun the C<installcmd> target. Now you can copy C<perl5.8.2.exe> to C<perl.exe>, and install the other OMF-build executables: C<perl__.exe> etc. They are ready to be used. =item 6. Change to the C<./pod> directory of the build tree, download the Perl logo F<CamelGrayBig.BMP>, and run ( perl2ipf > perl.ipf ) |& tee 00ipf ipfc /INF perl.ipf |& tee 00inf This produces the Perl docs online book C<perl.INF>. Install in on C<BOOKSHELF> path. =item 7. Now is the time to build statically linked executable F<perl_.exe> which includes newly-installed via C<Bundle::OS2_default> modules. Doing testing via C<CPAN.pm> is going to be painfully slow, since it statically links a new executable per XS extension. Here is a possible workaround: create a toplevel F<Makefile.PL> in F<$CPANHOME/.cpan/build/> with contents being (compare with L<Making executables with a custom collection of statically loaded extensions>) use ExtUtils::MakeMaker; WriteMakefile NAME => 'dummy'; execute this as perl_5.8.2.exe Makefile.PL <nul |& tee 00aout_c1 make -k all test <nul |& 00aout_t1 Again, this procedure should not be absolutely smooth. Some C<Makefile.PL>'s in subdirectories may be buggy, and would not run as "child" scripts. The interdependency of modules can strike you; however, since non-XS modules are already installed, the prerequisites of most modules have a very good chance to be present. If you discover some glitches, move directories of problematic modules to a different location; if these modules are non-XS modules, you may just ignore them - they are already installed; the remaining, XS, modules you need to install manually one by one. After each such removal you need to rerun the C<Makefile.PL>/C<make> process; usually this procedure converges soon. (But be sure to convert all the necessary external C libraries from F<.lib> format to F<.a> format: run one of emxaout foo.lib emximp -o foo.a foo.lib whichever is appropriate.) Also, make sure that the DLLs for external libraries are usable with with executables compiled without C<-Zmtd> options. When you are sure that only a few subdirectories lead to failures, you may want to add C<-j4> option to C<make> to speed up skipping subdirectories with already finished build. When you are satisfied with the results of tests, install the build C libraries for extensions: make install |& tee 00aout_i Now you can rename the file F<./perl.exe> generated during the last phase to F<perl_5.8.2.exe>; place it on C<PATH>; if there is an inter-dependency between some XS modules, you may need to repeat the C<test>/C<install> loop with this new executable and some excluded modules - until the procedure converges. Now you have all the necessary F<.a> libraries for these Perl modules in the places where Perl builder can find it. Use the perl builder: change to an empty directory, create a "dummy" F<Makefile.PL> again, and run perl_5.8.2.exe Makefile.PL |& tee 00c make perl |& tee 00p This should create an executable F<./perl.exe> with all the statically loaded extensions built in. Compare the generated F<perlmain.c> files to make sure that during the iterations the number of loaded extensions only increases. Rename F<./perl.exe> to F<perl_5.8.2.exe> on C<PATH>. When it converges, you got a functional variant of F<perl_5.8.2.exe>; copy it to C<perl_.exe>. You are done with generation of the local Perl installation. =item 8. Make sure that the installed modules are actually installed in the location of the new Perl, and are not inherited from entries of @INC given for inheritance from the older versions of Perl: set C<PERLLIB_582_PREFIX> to redirect the new version of Perl to a new location, and copy the installed files to this new location. Redo the tests to make sure that the versions of modules inherited from older versions of Perl are not needed. Actually, the log output of L<pod2ipf(1)> during the step 6 gives a very detailed info about which modules are loaded from which place; so you may use it as an additional verification tool. Check that some temporary files did not make into the perl install tree. Run something like this pfind . -f "!(/\.(pm|pl|ix|al|h|a|lib|txt|pod|imp|bs|dll|ld|bs|inc|xbm|yml|cgi|uu|e2x|skip|packlist|eg|cfg|html|pub|enc|all|ini|po|pot)$/i or /^\w+$/") | less in the install tree (both top one and F<sitelib> one). Compress all the DLLs with F<lxlite>. The tiny F<.exe> can be compressed with C</c:max> (the bug only appears when there is a fixup in the last 6 bytes of a page (?); since the tiny executables are much smaller than a page, the bug will not hit). Do not compress C<perl_.exe> - it would not work under DOS. =item 9. Now you can generate the binary distribution. This is done by running the test of the CPAN distribution C<OS2::SoftInstaller>. Tune up the file F<test.pl> to suit the layout of current version of Perl first. Do not forget to pack the necessary external DLLs accordingly. Include the description of the bugs and test suite failures you could not fix. Include the small-stack versions of Perl executables from Perl build directory. Include F<perl5.def> so that people can relink the perl DLL preserving the binary compatibility, or can create compatibility DLLs. Include the diff files (C<diff -pu old new>) of fixes you did so that people can rebuild your version. Include F<perl5.map> so that one can use remote debugging. =item 10. Share what you did with the other people. Relax. Enjoy fruits of your work. =item 11. Brace yourself for thanks, bug reports, hate mail and spam coming as result of the previous step. No good deed should remain unpunished! =back =head1 Building custom F<.EXE> files The Perl executables can be easily rebuilt at any moment. Moreover, one can use the I<embedding> interface (see L<perlembed>) to make very customized executables. =head2 Making executables with a custom collection of statically loaded extensions It is a little bit easier to do so while I<decreasing> the list of statically loaded extensions. We discuss this case only here. =over =item 1. Change to an empty directory, and create a placeholder <Makefile.PL>: use ExtUtils::MakeMaker; WriteMakefile NAME => 'dummy'; =item 2. Run it with the flavor of Perl (F<perl.exe> or F<perl_.exe>) you want to rebuild. perl_ Makefile.PL =item 3. Ask it to create new Perl executable: make perl (you may need to manually add C<PERLTYPE=-DPERL_CORE> to this commandline on some versions of Perl; the symptom is that the command-line globbing does not work from OS/2 shells with the newly-compiled executable; check with .\perl.exe -wle "print for @ARGV" * ). =item 4. The previous step created F<perlmain.c> which contains a list of newXS() calls near the end. Removing unnecessary calls, and rerunning make perl will produce a customized executable. =back =head2 Making executables with a custom search-paths The default perl executable is flexible enough to support most usages. However, one may want something yet more flexible; for example, one may want to find Perl DLL relatively to the location of the EXE file; or one may want to ignore the environment when setting the Perl-library search patch, etc. If you fill comfortable with I<embedding> interface (see L<perlembed>), such things are easy to do repeating the steps outlined in L<Making executables with a custom collection of statically loaded extensions>, and doing more comprehensive edits to main() of F<perlmain.c>. The people with little desire to understand Perl can just rename main(), and do necessary modification in a custom main() which calls the renamed function in appropriate time. However, there is a third way: perl DLL exports the main() function and several callbacks to customize the search path. Below is a complete example of a "Perl loader" which =over =item 1. Looks for Perl DLL in the directory C<$exedir/../dll>; =item 2. Prepends the above directory to C<BEGINLIBPATH>; =item 3. Fails if the Perl DLL found via C<BEGINLIBPATH> is different from what was loaded on step 1; e.g., another process could have loaded it from C<LIBPATH> or from a different value of C<BEGINLIBPATH>. In these cases one needs to modify the setting of the system so that this other process either does not run, or loads the DLL from C<BEGINLIBPATH> with C<LIBPATHSTRICT=T> (available with kernels after September 2000). =item 4. Loads Perl library from C<$exedir/../dll/lib/>. =item 5. Uses Bourne shell from C<$exedir/../dll/sh/ksh.exe>. =back For best results compile the C file below with the same options as the Perl DLL. However, a lot of functionality will work even if the executable is not an EMX applications, e.g., if compiled with gcc -Wall -DDOSISH -DOS2=1 -O2 -s -Zomf -Zsys perl-starter.c -DPERL_DLL_BASENAME=\"perl312F\" -Zstack 8192 -Zlinker /PM:VIO Here is the sample C file: #define INCL_DOS #define INCL_NOPM /* These are needed for compile if os2.h includes os2tk.h, not os2emx.h */ #define INCL_DOSPROCESS #include <os2.h> #include "EXTERN.h" #define PERL_IN_MINIPERLMAIN_C #include "perl.h" static char *me; HMODULE handle; static void die_with(char *msg1, char *msg2, char *msg3, char *msg4) { ULONG c; char *s = " error: "; DosWrite(2, me, strlen(me), &c); DosWrite(2, s, strlen(s), &c); DosWrite(2, msg1, strlen(msg1), &c); DosWrite(2, msg2, strlen(msg2), &c); DosWrite(2, msg3, strlen(msg3), &c); DosWrite(2, msg4, strlen(msg4), &c); DosWrite(2, "\r\n", 2, &c); exit(255); } typedef ULONG (*fill_extLibpath_t)(int type, char *pre, char *post, int replace, char *msg); typedef int (*main_t)(int type, char *argv[], char *env[]); typedef int (*handler_t)(void* data, int which); #ifndef PERL_DLL_BASENAME # define PERL_DLL_BASENAME "perl" #endif static HMODULE load_perl_dll(char *basename) { char buf[300], fail[260]; STRLEN l, dirl; fill_extLibpath_t f; ULONG rc_fullname; HMODULE handle, handle1; if (_execname(buf, sizeof(buf) - 13) != 0) die_with("Can't find full path: ", strerror(errno), "", ""); /* XXXX Fill 'me' with new value */ l = strlen(buf); while (l && buf[l-1] != '/' && buf[l-1] != '\\') l--; dirl = l - 1; strcpy(buf + l, basename); l += strlen(basename); strcpy(buf + l, ".dll"); if ( (rc_fullname = DosLoadModule(fail, sizeof fail, buf, &handle)) != 0 && DosLoadModule(fail, sizeof fail, basename, &handle) != 0 ) die_with("Can't load DLL ", buf, "", ""); if (rc_fullname) return handle; /* was loaded with short name; all is fine */ if (DosQueryProcAddr(handle, 0, "fill_extLibpath", (PFN*)&f)) die_with(buf, ": DLL exports no symbol ", "fill_extLibpath", ""); buf[dirl] = 0; if (f(0 /*BEGINLIBPATH*/, buf /* prepend */, NULL /* append */, 0 /* keep old value */, me)) die_with(me, ": prepending BEGINLIBPATH", "", ""); if (DosLoadModule(fail, sizeof fail, basename, &handle1) != 0) die_with(me, ": finding perl DLL again via BEGINLIBPATH", "", ""); buf[dirl] = '\\'; if (handle1 != handle) { if (DosQueryModuleName(handle1, sizeof(fail), fail)) strcpy(fail, "???"); die_with(buf, ":\n\tperl DLL via BEGINLIBPATH is different: \n\t", fail, "\n\tYou may need to manipulate global BEGINLIBPATH and LIBPATHSTRICT" "\n\tso that the other copy is loaded via BEGINLIBPATH."); } return handle; } int main(int argc, char **argv, char **env) { main_t f; handler_t h; me = argv[0]; /**/ handle = load_perl_dll(PERL_DLL_BASENAME); if (DosQueryProcAddr(handle, 0, "Perl_OS2_handler_install", (PFN*)&h)) die_with(PERL_DLL_BASENAME, ": DLL exports no symbol ", "Perl_OS2_handler_install", ""); if ( !h((void *)"~installprefix", Perlos2_handler_perllib_from) || !h((void *)"~dll", Perlos2_handler_perllib_to) || !h((void *)"~dll/sh/ksh.exe", Perlos2_handler_perl_sh) ) die_with(PERL_DLL_BASENAME, ": Can't install @INC manglers", "", ""); if (DosQueryProcAddr(handle, 0, "dll_perlmain", (PFN*)&f)) die_with(PERL_DLL_BASENAME, ": DLL exports no symbol ", "dll_perlmain", ""); return f(argc, argv, env); } =head1 Build FAQ =head2 Some C</> became C<\> in pdksh. You have a very old pdksh. See L</Prerequisites>. =head2 C<'errno'> - unresolved external You do not have MT-safe F<db.lib>. See L</Prerequisites>. =head2 Problems with tr or sed reported with very old version of tr and sed. =head2 Some problem (forget which ;-) You have an older version of F<perl.dll> on your LIBPATH, which broke the build of extensions. =head2 Library ... not found You did not run C<omflibs>. See L</Prerequisites>. =head2 Segfault in make You use an old version of GNU make. See L</Prerequisites>. =head2 op/sprintf test failure This can result from a bug in emx sprintf which was fixed in 0.9d fix 03. =head1 Specific (mis)features of OS/2 port =head2 C<setpriority>, C<getpriority> Note that these functions are compatible with *nix, not with the older ports of '94 - 95. The priorities are absolute, go from 32 to -95, lower is quicker. 0 is the default priority. B<WARNING>. Calling C<getpriority> on a non-existing process could lock the system before Warp3 fixpak22. Starting with Warp3, Perl will use a workaround: it aborts getpriority() if the process is not present. This is not possible on older versions C<2.*>, and has a race condition anyway. =head2 C<system()> Multi-argument form of C<system()> allows an additional numeric argument. The meaning of this argument is described in L<OS2::Process>. When finding a program to run, Perl first asks the OS to look for executables on C<PATH> (OS/2 adds extension F<.exe> if no extension is present). If not found, it looks for a script with possible extensions added in this order: no extension, F<.cmd>, F<.btm>, F<.bat>, F<.pl>. If found, Perl checks the start of the file for magic strings C<"#!"> and C<"extproc ">. If found, Perl uses the rest of the first line as the beginning of the command line to run this script. The only mangling done to the first line is extraction of arguments (currently up to 3), and ignoring of the path-part of the "interpreter" name if it can't be found using the full path. E.g., C<system 'foo', 'bar', 'baz'> may lead Perl to finding F<C:/emx/bin/foo.cmd> with the first line being extproc /bin/bash -x -c If F</bin/bash.exe> is not found, then Perl looks for an executable F<bash.exe> on C<PATH>. If found in F<C:/emx.add/bin/bash.exe>, then the above system() is translated to system qw(C:/emx.add/bin/bash.exe -x -c C:/emx/bin/foo.cmd bar baz) One additional translation is performed: instead of F</bin/sh> Perl uses the hardwired-or-customized shell (see C<L<"PERL_SH_DIR">>). The above search for "interpreter" is recursive: if F<bash> executable is not found, but F<bash.btm> is found, Perl will investigate its first line etc. The only hardwired limit on the recursion depth is implicit: there is a limit 4 on the number of additional arguments inserted before the actual arguments given to system(). In particular, if no additional arguments are specified on the "magic" first lines, then the limit on the depth is 4. If Perl finds that the found executable is of PM type when the current session is not, it will start the new process in a separate session of necessary type. Call via C<OS2::Process> to disable this magic. B<WARNING>. Due to the described logic, you need to explicitly specify F<.com> extension if needed. Moreover, if the executable F<perl5.6.1> is requested, Perl will not look for F<perl5.6.1.exe>. [This may change in the future.] =head2 C<extproc> on the first line If the first chars of a Perl script are C<"extproc ">, this line is treated as C<#!>-line, thus all the switches on this line are processed (twice if script was started via cmd.exe). See L<perlrun/DESCRIPTION>. =head2 Additional modules: L<OS2::Process>, L<OS2::DLL>, L<OS2::REXX>, L<OS2::PrfDB>, L<OS2::ExtAttr>. These modules provide access to additional numeric argument for C<system> and to the information about the running process, to DLLs having functions with REXX signature and to the REXX runtime, to OS/2 databases in the F<.INI> format, and to Extended Attributes. Two additional extensions by Andreas Kaiser, C<OS2::UPM>, and C<OS2::FTP>, are included into C<ILYAZ> directory, mirrored on CPAN. Other OS/2-related extensions are available too. =head2 Prebuilt methods: =over 4 =item C<File::Copy::syscopy> used by C<File::Copy::copy>, see L<File::Copy>. =item C<DynaLoader::mod2fname> used by C<DynaLoader> for DLL name mangling. =item C<Cwd::current_drive()> Self explanatory. =item C<Cwd::sys_chdir(name)> leaves drive as it is. =item C<Cwd::change_drive(name)> changes the "current" drive. =item C<Cwd::sys_is_absolute(name)> means has drive letter and is_rooted. =item C<Cwd::sys_is_rooted(name)> means has leading C<[/\\]> (maybe after a drive-letter:). =item C<Cwd::sys_is_relative(name)> means changes with current dir. =item C<Cwd::sys_cwd(name)> Interface to cwd from EMX. Used by C<Cwd::cwd>. =item C<Cwd::sys_abspath(name, dir)> Really really odious function to implement. Returns absolute name of file which would have C<name> if CWD were C<dir>. C<Dir> defaults to the current dir. =item C<Cwd::extLibpath([type])> Get current value of extended library search path. If C<type> is present and positive, works with C<END_LIBPATH>, if negative, works with C<LIBPATHSTRICT>, otherwise with C<BEGIN_LIBPATH>. =item C<Cwd::extLibpath_set( path [, type ] )> Set current value of extended library search path. If C<type> is present and positive, works with <END_LIBPATH>, if negative, works with C<LIBPATHSTRICT>, otherwise with C<BEGIN_LIBPATH>. =item C<OS2::Error(do_harderror,do_exception)> Returns C<undef> if it was not called yet, otherwise bit 1 is set if on the previous call do_harderror was enabled, bit 2 is set if on previous call do_exception was enabled. This function enables/disables error popups associated with hardware errors (Disk not ready etc.) and software exceptions. I know of no way to find out the state of popups I<before> the first call to this function. =item C<OS2::Errors2Drive(drive)> Returns C<undef> if it was not called yet, otherwise return false if errors were not requested to be written to a hard drive, or the drive letter if this was requested. This function may redirect error popups associated with hardware errors (Disk not ready etc.) and software exceptions to the file POPUPLOG.OS2 at the root directory of the specified drive. Overrides OS2::Error() specified by individual programs. Given argument undef will disable redirection. Has global effect, persists after the application exits. I know of no way to find out the state of redirection of popups to the disk I<before> the first call to this function. =item OS2::SysInfo() Returns a hash with system information. The keys of the hash are MAX_PATH_LENGTH, MAX_TEXT_SESSIONS, MAX_PM_SESSIONS, MAX_VDM_SESSIONS, BOOT_DRIVE, DYN_PRI_VARIATION, MAX_WAIT, MIN_SLICE, MAX_SLICE, PAGE_SIZE, VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION, MS_COUNT, TIME_LOW, TIME_HIGH, TOTPHYSMEM, TOTRESMEM, TOTAVAILMEM, MAXPRMEM, MAXSHMEM, TIMER_INTERVAL, MAX_COMP_LENGTH, FOREGROUND_FS_SESSION, FOREGROUND_PROCESS =item OS2::BootDrive() Returns a letter without colon. =item C<OS2::MorphPM(serve)>, C<OS2::UnMorphPM(serve)> Transforms the current application into a PM application and back. The argument true means that a real message loop is going to be served. OS2::MorphPM() returns the PM message queue handle as an integer. See L<"Centralized management of resources"> for additional details. =item C<OS2::Serve_Messages(force)> Fake on-demand retrieval of outstanding PM messages. If C<force> is false, will not dispatch messages if a real message loop is known to be present. Returns number of messages retrieved. Dies with "QUITing..." if WM_QUIT message is obtained. =item C<OS2::Process_Messages(force [, cnt])> Retrieval of PM messages until window creation/destruction. If C<force> is false, will not dispatch messages if a real message loop is known to be present. Returns change in number of windows. If C<cnt> is given, it is incremented by the number of messages retrieved. Dies with "QUITing..." if WM_QUIT message is obtained. =item C<OS2::_control87(new,mask)> the same as L<_control87(3)> of EMX. Takes integers as arguments, returns the previous coprocessor control word as an integer. Only bits in C<new> which are present in C<mask> are changed in the control word. =item OS2::get_control87() gets the coprocessor control word as an integer. =item C<OS2::set_control87_em(new=MCW_EM,mask=MCW_EM)> The variant of OS2::_control87() with default values good for handling exception mask: if no C<mask>, uses exception mask part of C<new> only. If no C<new>, disables all the floating point exceptions. See L<"Misfeatures"> for details. =item C<OS2::DLLname([how [, \&xsub]])> Gives the information about the Perl DLL or the DLL containing the C function bound to by C<&xsub>. The meaning of C<how> is: default (2): full name; 0: handle; 1: module name. =back (Note that some of these may be moved to different libraries - eventually). =head2 Prebuilt variables: =over 4 =item $OS2::emx_rev numeric value is the same as _emx_rev of EMX, a string value the same as _emx_vprt (similar to C<0.9c>). =item $OS2::emx_env same as _emx_env of EMX, a number similar to 0x8001. =item $OS2::os_ver a number C<OS_MAJOR + 0.001 * OS_MINOR>. =item $OS2::is_aout true if the Perl library was compiled in AOUT format. =item $OS2::can_fork true if the current executable is an AOUT EMX executable, so Perl can fork. Do not use this, use the portable check for $Config::Config{dfork}. =item $OS2::nsyserror This variable (default is 1) controls whether to enforce the contents of $^E to start with C<SYS0003>-like id. If set to 0, then the string value of $^E is what is available from the OS/2 message file. (Some messages in this file have an C<SYS0003>-like id prepended, some not.) =back =head2 Misfeatures =over 4 =item * Since L<flock(3)> is present in EMX, but is not functional, it is emulated by perl. To disable the emulations, set environment variable C<USE_PERL_FLOCK=0>. =item * Here is the list of things which may be "broken" on EMX (from EMX docs): =over 4 =item * The functions L<recvmsg(3)>, L<sendmsg(3)>, and L<socketpair(3)> are not implemented. =item * L<sock_init(3)> is not required and not implemented. =item * L<flock(3)> is not yet implemented (dummy function). (Perl has a workaround.) =item * L<kill(3)>: Special treatment of PID=0, PID=1 and PID=-1 is not implemented. =item * L<waitpid(3)>: WUNTRACED Not implemented. waitpid() is not implemented for negative values of PID. =back Note that C<kill -9> does not work with the current version of EMX. =item * See L<"Text-mode filehandles">. =item * Unix-domain sockets on OS/2 live in a pseudo-file-system C</sockets/...>. To avoid a failure to create a socket with a name of a different form, C<"/socket/"> is prepended to the socket name (unless it starts with this already). This may lead to problems later in case the socket is accessed via the "usual" file-system calls using the "initial" name. =item * Apparently, IBM used a compiler (for some period of time around '95?) which changes FP mask right and left. This is not I<that> bad for IBM's programs, but the same compiler was used for DLLs which are used with general-purpose applications. When these DLLs are used, the state of floating-point flags in the application is not predictable. What is much worse, some DLLs change the floating point flags when in _DLLInitTerm() (e.g., F<TCP32IP>). This means that even if you do not I<call> any function in the DLL, just the act of loading this DLL will reset your flags. What is worse, the same compiler was used to compile some HOOK DLLs. Given that HOOK dlls are executed in the context of I<all> the applications in the system, this means a complete unpredictability of floating point flags on systems using such HOOK DLLs. E.g., F<GAMESRVR.DLL> of B<DIVE> origin changes the floating point flags on each write to the TTY of a VIO (windowed text-mode) applications. Some other (not completely debugged) situations when FP flags change include some video drivers (?), and some operations related to creation of the windows. People who code B<OpenGL> may have more experience on this. Perl is generally used in the situation when all the floating-point exceptions are ignored, as is the default under EMX. If they are not ignored, some benign Perl programs would get a C<SIGFPE> and would die a horrible death. To circumvent this, Perl uses two hacks. They help against I<one> type of damage only: FP flags changed when loading a DLL. One of the hacks is to disable floating point exceptions on Perl startup (as is the default with EMX). This helps only with compile-time-linked DLLs changing the flags before main() had a chance to be called. The other hack is to restore FP flags after a call to dlopen(). This helps against similar damage done by DLLs _DLLInitTerm() at runtime. Currently no way to switch these hacks off is provided. =back =head2 Modifications Perl modifies some standard C library calls in the following ways: =over 9 =item C<popen> C<my_popen> uses F<sh.exe> if shell is required, cf. L<"PERL_SH_DIR">. =item C<tmpnam> is created using C<TMP> or C<TEMP> environment variable, via C<tempnam>. =item C<tmpfile> If the current directory is not writable, file is created using modified C<tmpnam>, so there may be a race condition. =item C<ctermid> a dummy implementation. =item C<stat> C<os2_stat> special-cases F</dev/tty> and F</dev/con>. =item C<mkdir>, C<rmdir> these EMX functions do not work if the path contains a trailing C</>. Perl contains a workaround for this. =item C<flock> Since L<flock(3)> is present in EMX, but is not functional, it is emulated by perl. To disable the emulations, set environment variable C<USE_PERL_FLOCK=0>. =back =head2 Identifying DLLs All the DLLs built with the current versions of Perl have ID strings identifying the name of the extension, its version, and the version of Perl required for this DLL. Run C<bldlevel DLL-name> to find this info. =head2 Centralized management of resources Since to call certain OS/2 API one needs to have a correctly initialized C<Win> subsystem, OS/2-specific extensions may require getting C<HAB>s and C<HMQ>s. If an extension would do it on its own, another extension could fail to initialize. Perl provides a centralized management of these resources: =over =item C<HAB> To get the HAB, the extension should call C<hab = perl_hab_GET()> in C. After this call is performed, C<hab> may be accessed as C<Perl_hab>. There is no need to release the HAB after it is used. If by some reasons F<perl.h> cannot be included, use extern int Perl_hab_GET(void); instead. =item C<HMQ> There are two cases: =over =item * the extension needs an C<HMQ> only because some API will not work otherwise. Use C<serve = 0> below. =item * the extension needs an C<HMQ> since it wants to engage in a PM event loop. Use C<serve = 1> below. =back To get an C<HMQ>, the extension should call C<hmq = perl_hmq_GET(serve)> in C. After this call is performed, C<hmq> may be accessed as C<Perl_hmq>. To signal to Perl that HMQ is not needed any more, call C<perl_hmq_UNSET(serve)>. Perl process will automatically morph/unmorph itself into/from a PM process if HMQ is needed/not-needed. Perl will automatically enable/disable C<WM_QUIT> message during shutdown if the message queue is served/not-served. B<NOTE>. If during a shutdown there is a message queue which did not disable WM_QUIT, and which did not process the received WM_QUIT message, the shutdown will be automatically cancelled. Do not call C<perl_hmq_GET(1)> unless you are going to process messages on an orderly basis. =item Treating errors reported by OS/2 API There are two principal conventions (it is useful to call them C<Dos*> and C<Win*> - though this part of the function signature is not always determined by the name of the API) of reporting the error conditions of OS/2 API. Most of C<Dos*> APIs report the error code as the result of the call (so 0 means success, and there are many types of errors). Most of C<Win*> API report success/fail via the result being C<TRUE>/C<FALSE>; to find the reason for the failure one should call WinGetLastError() API. Some C<Win*> entry points also overload a "meaningful" return value with the error indicator; having a 0 return value indicates an error. Yet some other C<Win*> entry points overload things even more, and 0 return value may mean a successful call returning a valid value 0, as well as an error condition; in the case of a 0 return value one should call WinGetLastError() API to distinguish a successful call from a failing one. By convention, all the calls to OS/2 API should indicate their failures by resetting $^E. All the Perl-accessible functions which call OS/2 API may be broken into two classes: some die()s when an API error is encountered, the other report the error via a false return value (of course, this does not concern Perl-accessible functions which I<expect> a failure of the OS/2 API call, having some workarounds coded). Obviously, in the situation of the last type of the signature of an OS/2 API, it is must more convenient for the users if the failure is indicated by die()ing: one does not need to check $^E to know that something went wrong. If, however, this solution is not desirable by some reason, the code in question should reset $^E to 0 before making this OS/2 API call, so that the caller of this Perl-accessible function has a chance to distinguish a success-but-0-return value from a failure. (One may return undef as an alternative way of reporting an error.) The macros to simplify this type of error propagation are =over =item C<CheckOSError(expr)> Returns true on error, sets $^E. Expects expr() be a call of C<Dos*>-style API. =item C<CheckWinError(expr)> Returns true on error, sets $^E. Expects expr() be a call of C<Win*>-style API. =item C<SaveWinError(expr)> Returns C<expr>, sets $^E from WinGetLastError() if C<expr> is false. =item C<SaveCroakWinError(expr,die,name1,name2)> Returns C<expr>, sets $^E from WinGetLastError() if C<expr> is false, and die()s if C<die> and $^E are true. The message to die is the concatenated strings C<name1> and C<name2>, separated by C<": "> from the contents of $^E. =item C<WinError_2_Perl_rc> Sets C<Perl_rc> to the return value of WinGetLastError(). =item C<FillWinError> Sets C<Perl_rc> to the return value of WinGetLastError(), and sets $^E to the corresponding value. =item C<FillOSError(rc)> Sets C<Perl_rc> to C<rc>, and sets $^E to the corresponding value. =back =item Loading DLLs and ordinals in DLLs Some DLLs are only present in some versions of OS/2, or in some configurations of OS/2. Some exported entry points are present only in DLLs shipped with some versions of OS/2. If these DLLs and entry points were linked directly for a Perl executable/DLL or from a Perl extensions, this binary would work only with the specified versions/setups. Even if these entry points were not needed, the I<load> of the executable (or DLL) would fail. For example, many newer useful APIs are not present in OS/2 v2; many PM-related APIs require DLLs not available on floppy-boot setup. To make these calls fail I<only when the calls are executed>, one should call these API via a dynamic linking API. There is a subsystem in Perl to simplify such type of calls. A large number of entry points available for such linking is provided (see C<entries_ordinals> - and also C<PMWIN_entries> - in F<os2ish.h>). These ordinals can be accessed via the APIs: CallORD(), DeclFuncByORD(), DeclVoidFuncByORD(), DeclOSFuncByORD(), DeclWinFuncByORD(), AssignFuncPByORD(), DeclWinFuncByORD_CACHE(), DeclWinFuncByORD_CACHE_survive(), DeclWinFuncByORD_CACHE_resetError_survive(), DeclWinFunc_CACHE(), DeclWinFunc_CACHE_resetError(), DeclWinFunc_CACHE_survive(), DeclWinFunc_CACHE_resetError_survive() See the header files and the C code in the supplied OS/2-related modules for the details on usage of these functions. Some of these functions also combine dynaloading semantic with the error-propagation semantic discussed above. =back =head1 Perl flavors Because of idiosyncrasies of OS/2 one cannot have all the eggs in the same basket (though EMX environment tries hard to overcome this limitations, so the situation may somehow improve). There are 4 executables for Perl provided by the distribution: =head2 F<perl.exe> The main workhorse. This is a chimera executable: it is compiled as an C<a.out>-style executable, but is linked with C<omf>-style dynamic library F<perl.dll>, and with dynamic CRT DLL. This executable is a VIO application. It can load perl dynamic extensions, and it can fork(). B<Note.> Keep in mind that fork() is needed to open a pipe to yourself. =head2 F<perl_.exe> This is a statically linked C<a.out>-style executable. It cannot load dynamic Perl extensions. The executable supplied in binary distributions has a lot of extensions prebuilt, thus the above restriction is important only if you use custom-built extensions. This executable is a VIO application. I<This is the only executable with does not require OS/2.> The friends locked into C<M$> world would appreciate the fact that this executable runs under DOS, Win0.3*, Win0.95 and WinNT with an appropriate extender. See L<"Other OSes">. =head2 F<perl__.exe> This is the same executable as F<perl___.exe>, but it is a PM application. B<Note.> Usually (unless explicitly redirected during the startup) STDIN, STDERR, and STDOUT of a PM application are redirected to F<nul>. However, it is possible to I<see> them if you start C<perl__.exe> from a PM program which emulates a console window, like I<Shell mode> of Emacs or EPM. Thus it I<is possible> to use Perl debugger (see L<perldebug>) to debug your PM application (but beware of the message loop lockups - this will not work if you have a message queue to serve, unless you hook the serving into the getc() function of the debugger). Another way to see the output of a PM program is to run it as pm_prog args 2>&1 | cat - with a shell I<different> from F<cmd.exe>, so that it does not create a link between a VIO session and the session of C<pm_porg>. (Such a link closes the VIO window.) E.g., this works with F<sh.exe> - or with Perl! open P, 'pm_prog args 2>&1 |' or die; print while <P>; The flavor F<perl__.exe> is required if you want to start your program without a VIO window present, but not C<detach>ed (run C<help detach> for more info). Very useful for extensions which use PM, like C<Perl/Tk> or C<OpenGL>. Note also that the differences between PM and VIO executables are only in the I<default> behaviour. One can start I<any> executable in I<any> kind of session by using the arguments C</fs>, C</pm> or C</win> switches of the command C<start> (of F<CMD.EXE> or a similar shell). Alternatively, one can use the numeric first argument of the C<system> Perl function (see L<OS2::Process>). =head2 F<perl___.exe> This is an C<omf>-style executable which is dynamically linked to F<perl.dll> and CRT DLL. I know no advantages of this executable over C<perl.exe>, but it cannot fork() at all. Well, one advantage is that the build process is not so convoluted as with C<perl.exe>. It is a VIO application. =head2 Why strange names? Since Perl processes the C<#!>-line (cf. L<perlrun/DESCRIPTION>, L<perlrun/Command Switches>, L<perldiag/"No Perl script found in input">), it should know when a program I<is a Perl>. There is some naming convention which allows Perl to distinguish correct lines from wrong ones. The above names are almost the only names allowed by this convention which do not contain digits (which have absolutely different semantics). =head2 Why dynamic linking? Well, having several executables dynamically linked to the same huge library has its advantages, but this would not substantiate the additional work to make it compile. The reason is the complicated-to-developers but very quick and convenient-to-users "hard" dynamic linking used by OS/2. There are two distinctive features of the dyna-linking model of OS/2: first, all the references to external functions are resolved at the compile time; second, there is no runtime fixup of the DLLs after they are loaded into memory. The first feature is an enormous advantage over other models: it avoids conflicts when several DLLs used by an application export entries with the same name. In such cases "other" models of dyna-linking just choose between these two entry points using some random criterion - with predictable disasters as results. But it is the second feature which requires the build of F<perl.dll>. The address tables of DLLs are patched only once, when they are loaded. The addresses of the entry points into DLLs are guaranteed to be the same for all the programs which use the same DLL. This removes the runtime fixup - once DLL is loaded, its code is read-only. While this allows some (significant?) performance advantages, this makes life much harder for developers, since the above scheme makes it impossible for a DLL to be "linked" to a symbol in the F<.EXE> file. Indeed, this would need a DLL to have different relocations tables for the (different) executables which use this DLL. However, a dynamically loaded Perl extension is forced to use some symbols from the perl executable, e.g., to know how to find the arguments to the functions: the arguments live on the perl internal evaluation stack. The solution is to put the main code of the interpreter into a DLL, and make the F<.EXE> file which just loads this DLL into memory and supplies command-arguments. The extension DLL cannot link to symbols in F<.EXE>, but it has no problem linking to symbols in the F<.DLL>. This I<greatly> increases the load time for the application (as well as complexity of the compilation). Since interpreter is in a DLL, the C RTL is basically forced to reside in a DLL as well (otherwise extensions would not be able to use CRT). There are some advantages if you use different flavors of perl, such as running F<perl.exe> and F<perl__.exe> simultaneously: they share the memory of F<perl.dll>. B<NOTE>. There is one additional effect which makes DLLs more wasteful: DLLs are loaded in the shared memory region, which is a scarse resource given the 512M barrier of the "standard" OS/2 virtual memory. The code of F<.EXE> files is also shared by all the processes which use the particular F<.EXE>, but they are "shared in the private address space of the process"; this is possible because the address at which different sections of the F<.EXE> file are loaded is decided at compile-time, thus all the processes have these sections loaded at same addresses, and no fixup of internal links inside the F<.EXE> is needed. Since DLLs may be loaded at run time, to have the same mechanism for DLLs one needs to have the address range of I<any of the loaded> DLLs in the system to be available I<in all the processes> which did not load a particular DLL yet. This is why the DLLs are mapped to the shared memory region. =head2 Why chimera build? Current EMX environment does not allow DLLs compiled using Unixish C<a.out> format to export symbols for data (or at least some types of data). This forces C<omf>-style compile of F<perl.dll>. Current EMX environment does not allow F<.EXE> files compiled in C<omf> format to fork(). fork() is needed for exactly three Perl operations: =over 4 =item * explicit fork() in the script, =item * C<open FH, "|-"> =item * C<open FH, "-|">, in other words, opening pipes to itself. =back While these operations are not questions of life and death, they are needed for a lot of useful scripts. This forces C<a.out>-style compile of F<perl.exe>. =head1 ENVIRONMENT Here we list environment variables with are either OS/2- and DOS- and Win*-specific, or are more important under OS/2 than under other OSes. =head2 C<PERLLIB_PREFIX> Specific for EMX port. Should have the form path1;path2 or path1 path2 If the beginning of some prebuilt path matches F<path1>, it is substituted with F<path2>. Should be used if the perl library is moved from the default location in preference to C<PERL(5)LIB>, since this would not leave wrong entries in @INC. For example, if the compiled version of perl looks for @INC in F<f:/perllib/lib>, and you want to install the library in F<h:/opt/gnu>, do set PERLLIB_PREFIX=f:/perllib/lib;h:/opt/gnu This will cause Perl with the prebuilt @INC of f:/perllib/lib/5.00553/os2 f:/perllib/lib/5.00553 f:/perllib/lib/site_perl/5.00553/os2 f:/perllib/lib/site_perl/5.00553 . to use the following @INC: h:/opt/gnu/5.00553/os2 h:/opt/gnu/5.00553 h:/opt/gnu/site_perl/5.00553/os2 h:/opt/gnu/site_perl/5.00553 . =head2 C<PERL_BADLANG> If 0, perl ignores setlocale() failing. May be useful with some strange I<locale>s. =head2 C<PERL_BADFREE> If 0, perl would not warn of in case of unwarranted free(). With older perls this might be useful in conjunction with the module DB_File, which was buggy when dynamically linked and OMF-built. Should not be set with newer Perls, since this may hide some I<real> problems. =head2 C<PERL_SH_DIR> Specific for EMX port. Gives the directory part of the location for F<sh.exe>. =head2 C<USE_PERL_FLOCK> Specific for EMX port. Since L<flock(3)> is present in EMX, but is not functional, it is emulated by perl. To disable the emulations, set environment variable C<USE_PERL_FLOCK=0>. =head2 C<TMP> or C<TEMP> Specific for EMX port. Used as storage place for temporary files. =head1 Evolution Here we list major changes which could make you by surprise. =head2 Text-mode filehandles Starting from version 5.8, Perl uses a builtin translation layer for text-mode files. This replaces the efficient well-tested EMX layer by some code which should be best characterized as a "quick hack". In addition to possible bugs and an inability to follow changes to the translation policy with off/on switches of TERMIO translation, this introduces a serious incompatible change: before sysread() on text-mode filehandles would go through the translation layer, now it would not. =head2 Priorities C<setpriority> and C<getpriority> are not compatible with earlier ports by Andreas Kaiser. See C<"setpriority, getpriority">. =head2 DLL name mangling: pre 5.6.2 With the release 5.003_01 the dynamically loadable libraries should be rebuilt when a different version of Perl is compiled. In particular, DLLs (including F<perl.dll>) are now created with the names which contain a checksum, thus allowing workaround for OS/2 scheme of caching DLLs. It may be possible to code a simple workaround which would =over =item * find the old DLLs looking through the old @INC; =item * mangle the names according to the scheme of new perl and copy the DLLs to these names; =item * edit the internal C<LX> tables of DLL to reflect the change of the name (probably not needed for Perl extension DLLs, since the internally coded names are not used for "specific" DLLs, they used only for "global" DLLs). =item * edit the internal C<IMPORT> tables and change the name of the "old" F<perl????.dll> to the "new" F<perl????.dll>. =back =head2 DLL name mangling: 5.6.2 and beyond In fact mangling of I<extension> DLLs was done due to misunderstanding of the OS/2 dynaloading model. OS/2 (effectively) maintains two different tables of loaded DLL: =over =item Global DLLs those loaded by the base name from C<LIBPATH>; including those associated at link time; =item specific DLLs loaded by the full name. =back When resolving a request for a global DLL, the table of already-loaded specific DLLs is (effectively) ignored; moreover, specific DLLs are I<always> loaded from the prescribed path. There is/was a minor twist which makes this scheme fragile: what to do with DLLs loaded from =over =item C<BEGINLIBPATH> and C<ENDLIBPATH> (which depend on the process) =item F<.> from C<LIBPATH> which I<effectively> depends on the process (although C<LIBPATH> is the same for all the processes). =back Unless C<LIBPATHSTRICT> is set to C<T> (and the kernel is after 2000/09/01), such DLLs are considered to be global. When loading a global DLL it is first looked in the table of already-loaded global DLLs. Because of this the fact that one executable loaded a DLL from C<BEGINLIBPATH> and C<ENDLIBPATH>, or F<.> from C<LIBPATH> may affect I<which> DLL is loaded when I<another> executable requests a DLL with the same name. I<This> is the reason for version-specific mangling of the DLL name for perl DLL. Since the Perl extension DLLs are always loaded with the full path, there is no need to mangle their names in a version-specific ways: their directory already reflects the corresponding version of perl, and @INC takes into account binary compatibility with older version. Starting from C<5.6.2> the name mangling scheme is fixed to be the same as for Perl 5.005_53 (same as in a popular binary release). Thus new Perls will be able to I<resolve the names> of old extension DLLs if @INC allows finding their directories. However, this still does not guarantee that these DLL may be loaded. The reason is the mangling of the name of the I<Perl DLL>. And since the extension DLLs link with the Perl DLL, extension DLLs for older versions would load an older Perl DLL, and would most probably segfault (since the data in this DLL is not properly initialized). There is a partial workaround (which can be made complete with newer OS/2 kernels): create a forwarder DLL with the same name as the DLL of the older version of Perl, which forwards the entry points to the newer Perl's DLL. Make this DLL accessible on (say) the C<BEGINLIBPATH> of the new Perl executable. When the new executable accesses old Perl's extension DLLs, they would request the old Perl's DLL by name, get the forwarder instead, so effectively will link with the currently running (new) Perl DLL. This may break in two ways: =over =item * Old perl executable is started when a new executable is running has loaded an extension compiled for the old executable (ouph!). In this case the old executable will get a forwarder DLL instead of the old perl DLL, so would link with the new perl DLL. While not directly fatal, it will behave the same as new executable. This beats the whole purpose of explicitly starting an old executable. =item * A new executable loads an extension compiled for the old executable when an old perl executable is running. In this case the extension will not pick up the forwarder - with fatal results. =back With support for C<LIBPATHSTRICT> this may be circumvented - unless one of DLLs is started from F<.> from C<LIBPATH> (I do not know whether C<LIBPATHSTRICT> affects this case). B<REMARK>. Unless newer kernels allow F<.> in C<BEGINLIBPATH> (older do not), this mess cannot be completely cleaned. (It turns out that as of the beginning of 2002, F<.> is not allowed, but F<.\.> is - and it has the same effect.) B<REMARK>. C<LIBPATHSTRICT>, C<BEGINLIBPATH> and C<ENDLIBPATH> are not environment variables, although F<cmd.exe> emulates them on C<SET ...> lines. From Perl they may be accessed by L<Cwd::extLibpath|/Cwd::extLibpath([type])> and L<Cwd::extLibpath_set|/Cwd::extLibpath_set( path [, type ] )>. =head2 DLL forwarder generation Assume that the old DLL is named F<perlE0AC.dll> (as is one for 5.005_53), and the new version is 5.6.1. Create a file F<perl5shim.def-leader> with LIBRARY 'perlE0AC' INITINSTANCE TERMINSTANCE DESCRIPTION '@#perl5-porters@perl.org:5.006001#@ Perl module for 5.00553 -> Perl 5.6.1 forwarder' CODE LOADONCALL DATA LOADONCALL NONSHARED MULTIPLE EXPORTS modifying the versions/names as needed. Run perl -wnle "next if 0../EXPORTS/; print qq( \"$1\") if /\"(\w+)\"/" perl5.def >lst in the Perl build directory (to make the DLL smaller replace perl5.def with the definition file for the older version of Perl if present). cat perl5shim.def-leader lst >perl5shim.def gcc -Zomf -Zdll -o perlE0AC.dll perl5shim.def -s -llibperl (ignore multiple C<warning L4085>). =head2 Threading As of release 5.003_01 perl is linked to multithreaded C RTL DLL. If perl itself is not compiled multithread-enabled, so will not be perl's malloc(). However, extensions may use multiple thread on their own risk. This was needed to compile C<Perl/Tk> for XFree86-OS/2 out-of-the-box, and link with DLLs for other useful libraries, which typically are compiled with C<-Zmt -Zcrtdll>. =head2 Calls to external programs Due to a popular demand the perl external program calling has been changed wrt Andreas Kaiser's port. I<If> perl needs to call an external program I<via shell>, the F<f:/bin/sh.exe> will be called, or whatever is the override, see L<"PERL_SH_DIR">. Thus means that you need to get some copy of a F<sh.exe> as well (I use one from pdksh). The path F<F:/bin> above is set up automatically during the build to a correct value on the builder machine, but is overridable at runtime, B<Reasons:> a consensus on C<perl5-porters> was that perl should use one non-overridable shell per platform. The obvious choices for OS/2 are F<cmd.exe> and F<sh.exe>. Having perl build itself would be impossible with F<cmd.exe> as a shell, thus I picked up C<sh.exe>. This assures almost 100% compatibility with the scripts coming from *nix. As an added benefit this works as well under DOS if you use DOS-enabled port of pdksh (see L</Prerequisites>). B<Disadvantages:> currently F<sh.exe> of pdksh calls external programs via fork()/exec(), and there is I<no> functioning exec() on OS/2. exec() is emulated by EMX by an asynchronous call while the caller waits for child completion (to pretend that the C<pid> did not change). This means that 1 I<extra> copy of F<sh.exe> is made active via fork()/exec(), which may lead to some resources taken from the system (even if we do not count extra work needed for fork()ing). Note that this a lesser issue now when we do not spawn F<sh.exe> unless needed (metachars found). One can always start F<cmd.exe> explicitly via system 'cmd', '/c', 'mycmd', 'arg1', 'arg2', ... If you need to use F<cmd.exe>, and do not want to hand-edit thousands of your scripts, the long-term solution proposed on p5-p is to have a directive use OS2::Cmd; which will override system(), exec(), C<``>, and C<open(,'...|')>. With current perl you may override only system(), readpipe() - the explicit version of C<``>, and maybe exec(). The code will substitute the one-argument call to system() by C<CORE::system('cmd.exe', '/c', shift)>. If you have some working code for C<OS2::Cmd>, please send it to me, I will include it into distribution. I have no need for such a module, so cannot test it. For the details of the current situation with calling external programs, see L<Starting OSE<sol>2 (and DOS) programs under Perl>. Set us mention a couple of features: =over 4 =item * External scripts may be called by their basename. Perl will try the same extensions as when processing B<-S> command-line switch. =item * External scripts starting with C<#!> or C<extproc > will be executed directly, without calling the shell, by calling the program specified on the rest of the first line. =back =head2 Memory allocation Perl uses its own malloc() under OS/2 - interpreters are usually malloc-bound for speed, but perl is not, since its malloc is lightning-fast. Perl-memory-usage-tuned benchmarks show that Perl's malloc is 5 times quicker than EMX one. I do not have convincing data about memory footprint, but a (pretty random) benchmark showed that Perl's one is 5% better. Combination of perl's malloc() and rigid DLL name resolution creates a special problem with library functions which expect their return value to be free()d by system's free(). To facilitate extensions which need to call such functions, system memory-allocation functions are still available with the prefix C<emx_> added. (Currently only DLL perl has this, it should propagate to F<perl_.exe> shortly.) =head2 Threads One can build perl with thread support enabled by providing C<-D usethreads> option to F<Configure>. Currently OS/2 support of threads is very preliminary. Most notable problems: =over 4 =item C<COND_WAIT> may have a race condition (but probably does not due to edge-triggered nature of OS/2 Event semaphores). (Needs a reimplementation (in terms of chaining waiting threads, with the linked list stored in per-thread structure?)?) =item F<os2.c> has a couple of static variables used in OS/2-specific functions. (Need to be moved to per-thread structure, or serialized?) =back Note that these problems should not discourage experimenting, since they have a low probability of affecting small programs. =head1 BUGS This description is not updated often (since 5.6.1?), see F<./os2/Changes> for more info. =cut OS/2 extensions ~~~~~~~~~~~~~~~ I include 3 extensions by Andreas Kaiser, OS2::REXX, OS2::UPM, and OS2::FTP, into my ftp directory, mirrored on CPAN. I made some minor changes needed to compile them by standard tools. I cannot test UPM and FTP, so I will appreciate your feedback. Other extensions there are OS2::ExtAttr, OS2::PrfDB for tied access to EAs and .INI files - and maybe some other extensions at the time you read it. Note that OS2 perl defines 2 pseudo-extension functions OS2::Copy::copy and DynaLoader::mod2fname (many more now, see L<Prebuilt methods>). The -R switch of older perl is deprecated. If you need to call a REXX code which needs access to variables, include the call into a REXX compartment created by REXX_call {...block...}; Two new functions are supported by REXX code, REXX_eval 'string'; REXX_eval_with 'string', REXX_function_name => \&perl_sub_reference; If you have some other extensions you want to share, send the code to me. At least two are available: tied access to EA's, and tied access to system databases. =head1 AUTHOR Ilya Zakharevich, cpan@ilyaz.org =head1 SEE ALSO perl(1). =cut PK PU�\��+ƍ ƍ perluniintro.podnu �[��� =head1 NAME perluniintro - Perl Unicode introduction =head1 DESCRIPTION This document gives a general idea of Unicode and how to use Unicode in Perl. See L</Further Resources> for references to more in-depth treatments of Unicode. =head2 Unicode Unicode is a character set standard which plans to codify all of the writing systems of the world, plus many other symbols. Unicode and ISO/IEC 10646 are coordinated standards that unify almost all other modern character set standards, covering more than 80 writing systems and hundreds of languages, including all commercially-important modern languages. All characters in the largest Chinese, Japanese, and Korean dictionaries are also encoded. The standards will eventually cover almost all characters in more than 250 writing systems and thousands of languages. Unicode 1.0 was released in October 1991, and 6.0 in October 2010. A Unicode I<character> is an abstract entity. It is not bound to any particular integer width, especially not to the C language C<char>. Unicode is language-neutral and display-neutral: it does not encode the language of the text, and it does not generally define fonts or other graphical layout details. Unicode operates on characters and on text built from those characters. Unicode defines characters like C<LATIN CAPITAL LETTER A> or C<GREEK SMALL LETTER ALPHA> and unique numbers for the characters, in this case 0x0041 and 0x03B1, respectively. These unique numbers are called I<code points>. A code point is essentially the position of the character within the set of all possible Unicode characters, and thus in Perl, the term I<ordinal> is often used interchangeably with it. The Unicode standard prefers using hexadecimal notation for the code points. If numbers like C<0x0041> are unfamiliar to you, take a peek at a later section, L</"Hexadecimal Notation">. The Unicode standard uses the notation C<U+0041 LATIN CAPITAL LETTER A>, to give the hexadecimal code point and the normative name of the character. Unicode also defines various I<properties> for the characters, like "uppercase" or "lowercase", "decimal digit", or "punctuation"; these properties are independent of the names of the characters. Furthermore, various operations on the characters like uppercasing, lowercasing, and collating (sorting) are defined. A Unicode I<logical> "character" can actually consist of more than one internal I<actual> "character" or code point. For Western languages, this is adequately modelled by a I<base character> (like C<LATIN CAPITAL LETTER A>) followed by one or more I<modifiers> (like C<COMBINING ACUTE ACCENT>). This sequence of base character and modifiers is called a I<combining character sequence>. Some non-western languages require more complicated models, so Unicode created the I<grapheme cluster> concept, which was later further refined into the I<extended grapheme cluster>. For example, a Korean Hangul syllable is considered a single logical character, but most often consists of three actual Unicode characters: a leading consonant followed by an interior vowel followed by a trailing consonant. Whether to call these extended grapheme clusters "characters" depends on your point of view. If you are a programmer, you probably would tend towards seeing each element in the sequences as one unit, or "character". However from the user's point of view, the whole sequence could be seen as one "character" since that's probably what it looks like in the context of the user's language. In this document, we take the programmer's point of view: one "character" is one Unicode code point. For some combinations of base character and modifiers, there are I<precomposed> characters. There is a single character equivalent, for example, to the sequence C<LATIN CAPITAL LETTER A> followed by C<COMBINING ACUTE ACCENT>. It is called C<LATIN CAPITAL LETTER A WITH ACUTE>. These precomposed characters are, however, only available for some combinations, and are mainly meant to support round-trip conversions between Unicode and legacy standards (like ISO 8859). Using sequences, as Unicode does, allows for needing fewer basic building blocks (code points) to express many more potential grapheme clusters. To support conversion between equivalent forms, various I<normalization forms> are also defined. Thus, C<LATIN CAPITAL LETTER A WITH ACUTE> is in I<Normalization Form Composed>, (abbreviated NFC), and the sequence C<LATIN CAPITAL LETTER A> followed by C<COMBINING ACUTE ACCENT> represents the same character in I<Normalization Form Decomposed> (NFD). Because of backward compatibility with legacy encodings, the "a unique number for every character" idea breaks down a bit: instead, there is "at least one number for every character". The same character could be represented differently in several legacy encodings. The converse is not also true: some code points do not have an assigned character. Firstly, there are unallocated code points within otherwise used blocks. Secondly, there are special Unicode control characters that do not represent true characters. When Unicode was first conceived, it was thought that all the world's characters could be represented using a 16-bit word; that is a maximum of C<0x10000> (or 65536) characters from C<0x0000> to C<0xFFFF> would be needed. This soon proved to be false, and since Unicode 2.0 (July 1996), Unicode has been defined all the way up to 21 bits (C<0x10FFFF>), and Unicode 3.1 (March 2001) defined the first characters above C<0xFFFF>. The first C<0x10000> characters are called the I<Plane 0>, or the I<Basic Multilingual Plane> (BMP). With Unicode 3.1, 17 (yes, seventeen) planes in all were defined--but they are nowhere near full of defined characters, yet. When a new language is being encoded, Unicode generally will choose a C<block> of consecutive unallocated code points for its characters. So far, the number of code points in these blocks has always been evenly divisible by 16. Extras in a block, not currently needed, are left unallocated, for future growth. But there have been occasions when a later relase needed more code points than the available extras, and a new block had to allocated somewhere else, not contiguous to the initial one, to handle the overflow. Thus, it became apparent early on that "block" wasn't an adequate organizing principal, and so the C<Script> property was created. (Later an improved script property was added as well, the C<Script_Extensions> property.) Those code points that are in overflow blocks can still have the same script as the original ones. The script concept fits more closely with natural language: there is C<Latin> script, C<Greek> script, and so on; and there are several artificial scripts, like C<Common> for characters that are used in multiple scripts, such as mathematical symbols. Scripts usually span varied parts of several blocks. For more information about scripts, see L<perlunicode/Scripts>. The division into blocks exists, but it is almost completely accidental--an artifact of how the characters have been and still are allocated. (Note that this paragraph has oversimplified things for the sake of this being an introduction. Unicode doesn't really encode languages, but the writing systems for them--their scripts; and one script can be used by many languages. Unicode also encodes things that aren't really about languages, such as symbols like C<BAGGAGE CLAIM>.) The Unicode code points are just abstract numbers. To input and output these abstract numbers, the numbers must be I<encoded> or I<serialised> somehow. Unicode defines several I<character encoding forms>, of which I<UTF-8> is perhaps the most popular. UTF-8 is a variable length encoding that encodes Unicode characters as 1 to 6 bytes. Other encodings include UTF-16 and UTF-32 and their big- and little-endian variants (UTF-8 is byte-order independent) The ISO/IEC 10646 defines the UCS-2 and UCS-4 encoding forms. For more information about encodings--for instance, to learn what I<surrogates> and I<byte order marks> (BOMs) are--see L<perlunicode>. =head2 Perl's Unicode Support Starting from Perl 5.6.0, Perl has had the capacity to handle Unicode natively. Perl 5.8.0, however, is the first recommended release for serious Unicode work. The maintenance release 5.6.1 fixed many of the problems of the initial Unicode implementation, but for example regular expressions still do not work with Unicode in 5.6.1. Perl 5.14.0 is the first release where Unicode support is (almost) seamlessly integrable without some gotchas (the exception being some differences in L<quotemeta|perlfunc/quotemeta>, which is fixed starting in Perl 5.16.0). To enable this seamless support, you should C<use feature 'unicode_strings'> (which is automatically selected if you C<use 5.012> or higher). See L<feature>. (5.14 also fixes a number of bugs and departures from the Unicode standard.) Before Perl 5.8.0, the use of C<use utf8> was used to declare that operations in the current block or file would be Unicode-aware. This model was found to be wrong, or at least clumsy: the "Unicodeness" is now carried with the data, instead of being attached to the operations. Starting with Perl 5.8.0, only one case remains where an explicit C<use utf8> is needed: if your Perl script itself is encoded in UTF-8, you can use UTF-8 in your identifier names, and in string and regular expression literals, by saying C<use utf8>. This is not the default because scripts with legacy 8-bit data in them would break. See L<utf8>. =head2 Perl's Unicode Model Perl supports both pre-5.6 strings of eight-bit native bytes, and strings of Unicode characters. The general principle is that Perl tries to keep its data as eight-bit bytes for as long as possible, but as soon as Unicodeness cannot be avoided, the data is transparently upgraded to Unicode. Prior to Perl 5.14, the upgrade was not completely transparent (see L<perlunicode/The "Unicode Bug">), and for backwards compatibility, full transparency is not gained unless C<use feature 'unicode_strings'> (see L<feature>) or C<use 5.012> (or higher) is selected. Internally, Perl currently uses either whatever the native eight-bit character set of the platform (for example Latin-1) is, defaulting to UTF-8, to encode Unicode strings. Specifically, if all code points in the string are C<0xFF> or less, Perl uses the native eight-bit character set. Otherwise, it uses UTF-8. A user of Perl does not normally need to know nor care how Perl happens to encode its internal strings, but it becomes relevant when outputting Unicode strings to a stream without a PerlIO layer (one with the "default" encoding). In such a case, the raw bytes used internally (the native character set or UTF-8, as appropriate for each string) will be used, and a "Wide character" warning will be issued if those strings contain a character beyond 0x00FF. For example, perl -e 'print "\x{DF}\n", "\x{0100}\x{DF}\n"' produces a fairly useless mixture of native bytes and UTF-8, as well as a warning: Wide character in print at ... To output UTF-8, use the C<:encoding> or C<:utf8> output layer. Prepending binmode(STDOUT, ":utf8"); to this sample program ensures that the output is completely UTF-8, and removes the program's warning. You can enable automatic UTF-8-ification of your standard file handles, default C<open()> layer, and C<@ARGV> by using either the C<-C> command line switch or the C<PERL_UNICODE> environment variable, see L<perlrun> for the documentation of the C<-C> switch. Note that this means that Perl expects other software to work the same way: if Perl has been led to believe that STDIN should be UTF-8, but then STDIN coming in from another command is not UTF-8, Perl will likely complain about the malformed UTF-8. All features that combine Unicode and I/O also require using the new PerlIO feature. Almost all Perl 5.8 platforms do use PerlIO, though: you can see whether yours is by running "perl -V" and looking for C<useperlio=define>. =head2 Unicode and EBCDIC Perl 5.8.0 also supports Unicode on EBCDIC platforms. There, Unicode support is somewhat more complex to implement since additional conversions are needed at every step. Later Perl releases have added code that will not work on EBCDIC platforms, and no one has complained, so the divergence has continued. If you want to run Perl on an EBCDIC platform, send email to perlbug@perl.org On EBCDIC platforms, the internal Unicode encoding form is UTF-EBCDIC instead of UTF-8. The difference is that as UTF-8 is "ASCII-safe" in that ASCII characters encode to UTF-8 as-is, while UTF-EBCDIC is "EBCDIC-safe". =head2 Creating Unicode To create Unicode characters in literals for code points above C<0xFF>, use the C<\x{...}> notation in double-quoted strings: my $smiley = "\x{263a}"; Similarly, it can be used in regular expression literals $smiley =~ /\x{263a}/; At run-time you can use C<chr()>: my $hebrew_alef = chr(0x05d0); See L</"Further Resources"> for how to find all these numeric codes. Naturally, C<ord()> will do the reverse: it turns a character into a code point. Note that C<\x..> (no C<{}> and only two hexadecimal digits), C<\x{...}>, and C<chr(...)> for arguments less than C<0x100> (decimal 256) generate an eight-bit character for backward compatibility with older Perls. For arguments of C<0x100> or more, Unicode characters are always produced. If you want to force the production of Unicode characters regardless of the numeric value, use C<pack("U", ...)> instead of C<\x..>, C<\x{...}>, or C<chr()>. You can invoke characters by name in double-quoted strings: my $arabic_alef = "\N{ARABIC LETTER ALEF}"; And, as mentioned above, you can also C<pack()> numbers into Unicode characters: my $georgian_an = pack("U", 0x10a0); Note that both C<\x{...}> and C<\N{...}> are compile-time string constants: you cannot use variables in them. if you want similar run-time functionality, use C<chr()> and C<charnames::string_vianame()>. If you want to force the result to Unicode characters, use the special C<"U0"> prefix. It consumes no arguments but causes the following bytes to be interpreted as the UTF-8 encoding of Unicode characters: my $chars = pack("U0W*", 0x80, 0x42); Likewise, you can stop such UTF-8 interpretation by using the special C<"C0"> prefix. =head2 Handling Unicode Handling Unicode is for the most part transparent: just use the strings as usual. Functions like C<index()>, C<length()>, and C<substr()> will work on the Unicode characters; regular expressions will work on the Unicode characters (see L<perlunicode> and L<perlretut>). Note that Perl considers grapheme clusters to be separate characters, so for example print length("\N{LATIN CAPITAL LETTER A}\N{COMBINING ACUTE ACCENT}"), "\n"; will print 2, not 1. The only exception is that regular expressions have C<\X> for matching an extended grapheme cluster. (Thus C<\X> in a regular expression would match the entire sequence of both the example characters.) Life is not quite so transparent, however, when working with legacy encodings, I/O, and certain special cases: =head2 Legacy Encodings When you combine legacy data and Unicode, the legacy data needs to be upgraded to Unicode. Normally the legacy data is assumed to be ISO 8859-1 (or EBCDIC, if applicable). The C<Encode> module knows about many encodings and has interfaces for doing conversions between those encodings: use Encode 'decode'; $data = decode("iso-8859-3", $data); # convert from legacy to utf-8 =head2 Unicode I/O Normally, writing out Unicode data print FH $some_string_with_unicode, "\n"; produces raw bytes that Perl happens to use to internally encode the Unicode string. Perl's internal encoding depends on the system as well as what characters happen to be in the string at the time. If any of the characters are at code points C<0x100> or above, you will get a warning. To ensure that the output is explicitly rendered in the encoding you desire--and to avoid the warning--open the stream with the desired encoding. Some examples: open FH, ">:utf8", "file"; open FH, ">:encoding(ucs2)", "file"; open FH, ">:encoding(UTF-8)", "file"; open FH, ">:encoding(shift_jis)", "file"; and on already open streams, use C<binmode()>: binmode(STDOUT, ":utf8"); binmode(STDOUT, ":encoding(ucs2)"); binmode(STDOUT, ":encoding(UTF-8)"); binmode(STDOUT, ":encoding(shift_jis)"); The matching of encoding names is loose: case does not matter, and many encodings have several aliases. Note that the C<:utf8> layer must always be specified exactly like that; it is I<not> subject to the loose matching of encoding names. Also note that currently C<:utf8> is unsafe for input, because it accepts the data without validating that it is indeed valid UTF-8; you should instead use C<:encoding(utf-8)> (with or without a hyphen). See L<PerlIO> for the C<:utf8> layer, L<PerlIO::encoding> and L<Encode::PerlIO> for the C<:encoding()> layer, and L<Encode::Supported> for many encodings supported by the C<Encode> module. Reading in a file that you know happens to be encoded in one of the Unicode or legacy encodings does not magically turn the data into Unicode in Perl's eyes. To do that, specify the appropriate layer when opening files open(my $fh,'<:encoding(utf8)', 'anything'); my $line_of_unicode = <$fh>; open(my $fh,'<:encoding(Big5)', 'anything'); my $line_of_unicode = <$fh>; The I/O layers can also be specified more flexibly with the C<open> pragma. See L<open>, or look at the following example. use open ':encoding(utf8)'; # input/output default encoding will be # UTF-8 open X, ">file"; print X chr(0x100), "\n"; close X; open Y, "<file"; printf "%#x\n", ord(<Y>); # this should print 0x100 close Y; With the C<open> pragma you can use the C<:locale> layer BEGIN { $ENV{LC_ALL} = $ENV{LANG} = 'ru_RU.KOI8-R' } # the :locale will probe the locale environment variables like # LC_ALL use open OUT => ':locale'; # russki parusski open(O, ">koi8"); print O chr(0x430); # Unicode CYRILLIC SMALL LETTER A = KOI8-R 0xc1 close O; open(I, "<koi8"); printf "%#x\n", ord(<I>), "\n"; # this should print 0xc1 close I; These methods install a transparent filter on the I/O stream that converts data from the specified encoding when it is read in from the stream. The result is always Unicode. The L<open> pragma affects all the C<open()> calls after the pragma by setting default layers. If you want to affect only certain streams, use explicit layers directly in the C<open()> call. You can switch encodings on an already opened stream by using C<binmode()>; see L<perlfunc/binmode>. The C<:locale> does not currently (as of Perl 5.8.0) work with C<open()> and C<binmode()>, only with the C<open> pragma. The C<:utf8> and C<:encoding(...)> methods do work with all of C<open()>, C<binmode()>, and the C<open> pragma. Similarly, you may use these I/O layers on output streams to automatically convert Unicode to the specified encoding when it is written to the stream. For example, the following snippet copies the contents of the file "text.jis" (encoded as ISO-2022-JP, aka JIS) to the file "text.utf8", encoded as UTF-8: open(my $nihongo, '<:encoding(iso-2022-jp)', 'text.jis'); open(my $unicode, '>:utf8', 'text.utf8'); while (<$nihongo>) { print $unicode $_ } The naming of encodings, both by the C<open()> and by the C<open> pragma allows for flexible names: C<koi8-r> and C<KOI8R> will both be understood. Common encodings recognized by ISO, MIME, IANA, and various other standardisation organisations are recognised; for a more detailed list see L<Encode::Supported>. C<read()> reads characters and returns the number of characters. C<seek()> and C<tell()> operate on byte counts, as do C<sysread()> and C<sysseek()>. Notice that because of the default behaviour of not doing any conversion upon input if there is no default layer, it is easy to mistakenly write code that keeps on expanding a file by repeatedly encoding the data: # BAD CODE WARNING open F, "file"; local $/; ## read in the whole file of 8-bit characters $t = <F>; close F; open F, ">:encoding(utf8)", "file"; print F $t; ## convert to UTF-8 on output close F; If you run this code twice, the contents of the F<file> will be twice UTF-8 encoded. A C<use open ':encoding(utf8)'> would have avoided the bug, or explicitly opening also the F<file> for input as UTF-8. B<NOTE>: the C<:utf8> and C<:encoding> features work only if your Perl has been built with the new PerlIO feature (which is the default on most systems). =head2 Displaying Unicode As Text Sometimes you might want to display Perl scalars containing Unicode as simple ASCII (or EBCDIC) text. The following subroutine converts its argument so that Unicode characters with code points greater than 255 are displayed as C<\x{...}>, control characters (like C<\n>) are displayed as C<\x..>, and the rest of the characters as themselves: sub nice_string { join("", map { $_ > 255 ? # if wide character... sprintf("\\x{%04X}", $_) : # \x{...} chr($_) =~ /[[:cntrl:]]/ ? # else if control character... sprintf("\\x%02X", $_) : # \x.. quotemeta(chr($_)) # else quoted or as themselves } unpack("W*", $_[0])); # unpack Unicode characters } For example, nice_string("foo\x{100}bar\n") returns the string 'foo\x{0100}bar\x0A' which is ready to be printed. =head2 Special Cases =over 4 =item * Bit Complement Operator ~ And vec() The bit complement operator C<~> may produce surprising results if used on strings containing characters with ordinal values above 255. In such a case, the results are consistent with the internal encoding of the characters, but not with much else. So don't do that. Similarly for C<vec()>: you will be operating on the internally-encoded bit patterns of the Unicode characters, not on the code point values, which is very probably not what you want. =item * Peeking At Perl's Internal Encoding Normal users of Perl should never care how Perl encodes any particular Unicode string (because the normal ways to get at the contents of a string with Unicode--via input and output--should always be via explicitly-defined I/O layers). But if you must, there are two ways of looking behind the scenes. One way of peeking inside the internal encoding of Unicode characters is to use C<unpack("C*", ...> to get the bytes of whatever the string encoding happens to be, or C<unpack("U0..", ...)> to get the bytes of the UTF-8 encoding: # this prints c4 80 for the UTF-8 bytes 0xc4 0x80 print join(" ", unpack("U0(H2)*", pack("U", 0x100))), "\n"; Yet another way would be to use the Devel::Peek module: perl -MDevel::Peek -e 'Dump(chr(0x100))' That shows the C<UTF8> flag in FLAGS and both the UTF-8 bytes and Unicode characters in C<PV>. See also later in this document the discussion about the C<utf8::is_utf8()> function. =back =head2 Advanced Topics =over 4 =item * String Equivalence The question of string equivalence turns somewhat complicated in Unicode: what do you mean by "equal"? (Is C<LATIN CAPITAL LETTER A WITH ACUTE> equal to C<LATIN CAPITAL LETTER A>?) The short answer is that by default Perl compares equivalence (C<eq>, C<ne>) based only on code points of the characters. In the above case, the answer is no (because 0x00C1 != 0x0041). But sometimes, any CAPITAL LETTER A's should be considered equal, or even A's of any case. The long answer is that you need to consider character normalization and casing issues: see L<Unicode::Normalize>, Unicode Technical Report #15, L<Unicode Normalization Forms|http://www.unicode.org/unicode/reports/tr15> and sections on case mapping in the L<Unicode Standard|http://www.unicode.org>. As of Perl 5.8.0, the "Full" case-folding of I<Case Mappings/SpecialCasing> is implemented, but bugs remain in C<qr//i> with them, mostly fixed by 5.14. =item * String Collation People like to see their strings nicely sorted--or as Unicode parlance goes, collated. But again, what do you mean by collate? (Does C<LATIN CAPITAL LETTER A WITH ACUTE> come before or after C<LATIN CAPITAL LETTER A WITH GRAVE>?) The short answer is that by default, Perl compares strings (C<lt>, C<le>, C<cmp>, C<ge>, C<gt>) based only on the code points of the characters. In the above case, the answer is "after", since C<0x00C1> > C<0x00C0>. The long answer is that "it depends", and a good answer cannot be given without knowing (at the very least) the language context. See L<Unicode::Collate>, and I<Unicode Collation Algorithm> L<http://www.unicode.org/unicode/reports/tr10/> =back =head2 Miscellaneous =over 4 =item * Character Ranges and Classes Character ranges in regular expression bracketed character classes ( e.g., C</[a-z]/>) and in the C<tr///> (also known as C<y///>) operator are not magically Unicode-aware. What this means is that C<[A-Za-z]> will not magically start to mean "all alphabetic letters" (not that it does mean that even for 8-bit characters; for those, if you are using locales (L<perllocale>), use C</[[:alpha:]]/>; and if not, use the 8-bit-aware property C<\p{alpha}>). All the properties that begin with C<\p> (and its inverse C<\P>) are actually character classes that are Unicode-aware. There are dozens of them, see L<perluniprops>. You can use Unicode code points as the end points of character ranges, and the range will include all Unicode code points that lie between those end points. =item * String-To-Number Conversions Unicode does define several other decimal--and numeric--characters besides the familiar 0 to 9, such as the Arabic and Indic digits. Perl does not support string-to-number conversion for digits other than ASCII 0 to 9 (and ASCII a to f for hexadecimal). To get safe conversions from any Unicode string, use L<Unicode::UCD/num()>. =back =head2 Questions With Answers =over 4 =item * Will My Old Scripts Break? Very probably not. Unless you are generating Unicode characters somehow, old behaviour should be preserved. About the only behaviour that has changed and which could start generating Unicode is the old behaviour of C<chr()> where supplying an argument more than 255 produced a character modulo 255. C<chr(300)>, for example, was equal to C<chr(45)> or "-" (in ASCII), now it is LATIN CAPITAL LETTER I WITH BREVE. =item * How Do I Make My Scripts Work With Unicode? Very little work should be needed since nothing changes until you generate Unicode data. The most important thing is getting input as Unicode; for that, see the earlier I/O discussion. To get full seamless Unicode support, add C<use feature 'unicode_strings'> (or C<use 5.012> or higher) to your script. =item * How Do I Know Whether My String Is In Unicode? You shouldn't have to care. But you may if your Perl is before 5.14.0 or you haven't specified C<use feature 'unicode_strings'> or C<use 5.012> (or higher) because otherwise the semantics of the code points in the range 128 to 255 are different depending on whether the string they are contained within is in Unicode or not. (See L<perlunicode/When Unicode Does Not Happen>.) To determine if a string is in Unicode, use: print utf8::is_utf8($string) ? 1 : 0, "\n"; But note that this doesn't mean that any of the characters in the string are necessary UTF-8 encoded, or that any of the characters have code points greater than 0xFF (255) or even 0x80 (128), or that the string has any characters at all. All the C<is_utf8()> does is to return the value of the internal "utf8ness" flag attached to the C<$string>. If the flag is off, the bytes in the scalar are interpreted as a single byte encoding. If the flag is on, the bytes in the scalar are interpreted as the (variable-length, potentially multi-byte) UTF-8 encoded code points of the characters. Bytes added to a UTF-8 encoded string are automatically upgraded to UTF-8. If mixed non-UTF-8 and UTF-8 scalars are merged (double-quoted interpolation, explicit concatenation, or printf/sprintf parameter substitution), the result will be UTF-8 encoded as if copies of the byte strings were upgraded to UTF-8: for example, $a = "ab\x80c"; $b = "\x{100}"; print "$a = $b\n"; the output string will be UTF-8-encoded C<ab\x80c = \x{100}\n>, but C<$a> will stay byte-encoded. Sometimes you might really need to know the byte length of a string instead of the character length. For that use either the C<Encode::encode_utf8()> function or the C<bytes> pragma and the C<length()> function: my $unicode = chr(0x100); print length($unicode), "\n"; # will print 1 require Encode; print length(Encode::encode_utf8($unicode)),"\n"; # will print 2 use bytes; print length($unicode), "\n"; # will also print 2 # (the 0xC4 0x80 of the UTF-8) no bytes; =item * How Do I Find Out What Encoding a File Has? You might try L<Encode::Guess>, but it has a number of limitations. =item * How Do I Detect Data That's Not Valid In a Particular Encoding? Use the C<Encode> package to try converting it. For example, use Encode 'decode_utf8'; if (eval { decode_utf8($string, Encode::FB_CROAK); 1 }) { # $string is valid utf8 } else { # $string is not valid utf8 } Or use C<unpack> to try decoding it: use warnings; @chars = unpack("C0U*", $string_of_bytes_that_I_think_is_utf8); If invalid, a C<Malformed UTF-8 character> warning is produced. The "C0" means "process the string character per character". Without that, the C<unpack("U*", ...)> would work in C<U0> mode (the default if the format string starts with C<U>) and it would return the bytes making up the UTF-8 encoding of the target string, something that will always work. =item * How Do I Convert Binary Data Into a Particular Encoding, Or Vice Versa? This probably isn't as useful as you might think. Normally, you shouldn't need to. In one sense, what you are asking doesn't make much sense: encodings are for characters, and binary data are not "characters", so converting "data" into some encoding isn't meaningful unless you know in what character set and encoding the binary data is in, in which case it's not just binary data, now is it? If you have a raw sequence of bytes that you know should be interpreted via a particular encoding, you can use C<Encode>: use Encode 'from_to'; from_to($data, "iso-8859-1", "utf-8"); # from latin-1 to utf-8 The call to C<from_to()> changes the bytes in C<$data>, but nothing material about the nature of the string has changed as far as Perl is concerned. Both before and after the call, the string C<$data> contains just a bunch of 8-bit bytes. As far as Perl is concerned, the encoding of the string remains as "system-native 8-bit bytes". You might relate this to a fictional 'Translate' module: use Translate; my $phrase = "Yes"; Translate::from_to($phrase, 'english', 'deutsch'); ## phrase now contains "Ja" The contents of the string changes, but not the nature of the string. Perl doesn't know any more after the call than before that the contents of the string indicates the affirmative. Back to converting data. If you have (or want) data in your system's native 8-bit encoding (e.g. Latin-1, EBCDIC, etc.), you can use pack/unpack to convert to/from Unicode. $native_string = pack("W*", unpack("U*", $Unicode_string)); $Unicode_string = pack("U*", unpack("W*", $native_string)); If you have a sequence of bytes you B<know> is valid UTF-8, but Perl doesn't know it yet, you can make Perl a believer, too: use Encode 'decode_utf8'; $Unicode = decode_utf8($bytes); or: $Unicode = pack("U0a*", $bytes); You can find the bytes that make up a UTF-8 sequence with @bytes = unpack("C*", $Unicode_string) and you can create well-formed Unicode with $Unicode_string = pack("U*", 0xff, ...) =item * How Do I Display Unicode? How Do I Input Unicode? See L<http://www.alanwood.net/unicode/> and L<http://www.cl.cam.ac.uk/~mgk25/unicode.html> =item * How Does Unicode Work With Traditional Locales? Starting in Perl 5.16, you can specify use locale ':not_characters'; to get Perl to work well with tradtional locales. The catch is that you have to translate from the locale character set to/from Unicode yourself. See L</Unicode IE<sol>O> above for how to use open ':locale'; to accomplish this, but full details are in L<perllocale/Unicode and UTF-8>, including gotchas that happen if you don't specifiy C<:not_characters>. =back =head2 Hexadecimal Notation The Unicode standard prefers using hexadecimal notation because that more clearly shows the division of Unicode into blocks of 256 characters. Hexadecimal is also simply shorter than decimal. You can use decimal notation, too, but learning to use hexadecimal just makes life easier with the Unicode standard. The C<U+HHHH> notation uses hexadecimal, for example. The C<0x> prefix means a hexadecimal number, the digits are 0-9 I<and> a-f (or A-F, case doesn't matter). Each hexadecimal digit represents four bits, or half a byte. C<print 0x..., "\n"> will show a hexadecimal number in decimal, and C<printf "%x\n", $decimal> will show a decimal number in hexadecimal. If you have just the "hex digits" of a hexadecimal number, you can use the C<hex()> function. print 0x0009, "\n"; # 9 print 0x000a, "\n"; # 10 print 0x000f, "\n"; # 15 print 0x0010, "\n"; # 16 print 0x0011, "\n"; # 17 print 0x0100, "\n"; # 256 print 0x0041, "\n"; # 65 printf "%x\n", 65; # 41 printf "%#x\n", 65; # 0x41 print hex("41"), "\n"; # 65 =head2 Further Resources =over 4 =item * Unicode Consortium L<http://www.unicode.org/> =item * Unicode FAQ L<http://www.unicode.org/unicode/faq/> =item * Unicode Glossary L<http://www.unicode.org/glossary/> =item * Unicode Recommended Reading List The Unicode Consortium has a list of articles and books, some of which give a much more in depth treatment of Unicode: L<http://unicode.org/resources/readinglist.html> =item * Unicode Useful Resources L<http://www.unicode.org/unicode/onlinedat/resources.html> =item * Unicode and Multilingual Support in HTML, Fonts, Web Browsers and Other Applications L<http://www.alanwood.net/unicode/> =item * UTF-8 and Unicode FAQ for Unix/Linux L<http://www.cl.cam.ac.uk/~mgk25/unicode.html> =item * Legacy Character Sets L<http://www.czyborra.com/> L<http://www.eki.ee/letter/> =item * You can explore various information from the Unicode data files using the C<Unicode::UCD> module. =back =head1 UNICODE IN OLDER PERLS If you cannot upgrade your Perl to 5.8.0 or later, you can still do some Unicode processing by using the modules C<Unicode::String>, C<Unicode::Map8>, and C<Unicode::Map>, available from CPAN. If you have the GNU recode installed, you can also use the Perl front-end C<Convert::Recode> for character conversions. The following are fast conversions from ISO 8859-1 (Latin-1) bytes to UTF-8 bytes and back, the code works even with older Perl 5 versions. # ISO 8859-1 to UTF-8 s/([\x80-\xFF])/chr(0xC0|ord($1)>>6).chr(0x80|ord($1)&0x3F)/eg; # UTF-8 to ISO 8859-1 s/([\xC2\xC3])([\x80-\xBF])/chr(ord($1)<<6&0xC0|ord($2)&0x3F)/eg; =head1 SEE ALSO L<perlunitut>, L<perlunicode>, L<Encode>, L<open>, L<utf8>, L<bytes>, L<perlretut>, L<perlrun>, L<Unicode::Collate>, L<Unicode::Normalize>, L<Unicode::UCD> =head1 ACKNOWLEDGMENTS Thanks to the kind readers of the perl5-porters@perl.org, perl-unicode@perl.org, linux-utf8@nl.linux.org, and unicore@unicode.org mailing lists for their valuable feedback. =head1 AUTHOR, COPYRIGHT, AND LICENSE Copyright 2001-2011 Jarkko Hietaniemi E<lt>jhi@iki.fiE<gt> This document may be distributed under the same terms as Perl itself. PK PU�\d�Ι�[ �[ perlxstypemap.podnu �[��� =head1 NAME perlxstypemap - Perl XS C/Perl type mapping =head1 DESCRIPTION The more you think about interfacing between two languages, the more you'll realize that the majority of programmer effort has to go into converting between the data structures that are native to either of the languages involved. This trumps other matter such as differing calling conventions because the problem space is so much greater. There are simply more ways to shove data into memory than there are ways to implement a function call. Perl XS' attempt at a solution to this is the concept of typemaps. At an abstract level, a Perl XS typemap is nothing but a recipe for converting from a certain Perl data structure to a certain C data structure and vice versa. Since there can be C types that are sufficiently similar to warrant converting with the same logic, XS typemaps are represented by a unique identifier, henceforth called an <XS type> in this document. You can then tell the XS compiler that multiple C types are to be mapped with the same XS typemap. In your XS code, when you define an argument with a C type or when you are using a C<CODE:> and an C<OUTPUT:> section together with a C return type of your XSUB, it'll be the typemapping mechanism that makes this easy. =head2 Anatomy of a typemap In more practical terms, the typemap is a collection of code fragments which are used by the B<xsubpp> compiler to map C function parameters and values to Perl values. The typemap file may consist of three sections labelled C<TYPEMAP>, C<INPUT>, and C<OUTPUT>. An unlabelled initial section is assumed to be a C<TYPEMAP> section. The INPUT section tells the compiler how to translate Perl values into variables of certain C types. The OUTPUT section tells the compiler how to translate the values from certain C types into values Perl can understand. The TYPEMAP section tells the compiler which of the INPUT and OUTPUT code fragments should be used to map a given C type to a Perl value. The section labels C<TYPEMAP>, C<INPUT>, or C<OUTPUT> must begin in the first column on a line by themselves, and must be in uppercase. Each type of section can appear an arbitrary number of times and does not have to appear at all. For example, a typemap may commonly lack C<INPUT> and C<OUTPUT> sections if all it needs to do is associate additional C types with core XS types like T_PTROBJ. Lines that start with a hash C<#> are considered comments and ignored in the C<TYPEMAP> section, but are considered significant in C<INPUT> and C<OUTPUT>. Blank lines are generally ignored. Traditionally, typemaps needed to be written to a separate file, conventionally called C<typemap> in a CPAN distribution. With ExtUtils::ParseXS (the XS compiler) version 3.12 or better which comes with perl 5.16, typemaps can also be embedded directly into XS code using a HERE-doc like syntax: TYPEMAP: <<HERE ... HERE where C<HERE> can be replaced by other identifiers like with normal Perl HERE-docs. All details below about the typemap textual format remain valid. The C<TYPEMAP> section should contain one pair of C type and XS type per line as follows. An example from the core typemap file: TYPEMAP # all variants of char* is handled by the T_PV typemap char * T_PV const char * T_PV unsigned char * T_PV ... The C<INPUT> and C<OUTPUT> sections have identical formats, that is, each unindented line starts a new in- or output map respectively. A new in- or output map must start with the name of the XS type to map on a line by itself, followed by the code that implements it indented on the following lines. Example: INPUT T_PV $var = ($type)SvPV_nolen($arg) T_PTR $var = INT2PTR($type,SvIV($arg)) We'll get to the meaning of those Perlish-looking variables in a little bit. Finally, here's an example of the full typemap file for mapping C strings of the C<char *> type to Perl scalars/strings: TYPEMAP char * T_PV INPUT T_PV $var = ($type)SvPV_nolen($arg) OUTPUT T_PV sv_setpv((SV*)$arg, $var); Here's a more complicated example: suppose that you wanted C<struct netconfig> to be blessed into the class C<Net::Config>. One way to do this is to use underscores (_) to separate package names, as follows: typedef struct netconfig * Net_Config; And then provide a typemap entry C<T_PTROBJ_SPECIAL> that maps underscores to double-colons (::), and declare C<Net_Config> to be of that type: TYPEMAP Net_Config T_PTROBJ_SPECIAL INPUT T_PTROBJ_SPECIAL if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")){ IV tmp = SvIV((SV*)SvRV($arg)); $var = INT2PTR($type, tmp); } else croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\") OUTPUT T_PTROBJ_SPECIAL sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\", (void*)$var); The INPUT and OUTPUT sections substitute underscores for double-colons on the fly, giving the desired effect. This example demonstrates some of the power and versatility of the typemap facility. The C<INT2PTR> macro (defined in perl.h) casts an integer to a pointer of a given type, taking care of the possible different size of integers and pointers. There are also C<PTR2IV>, C<PTR2UV>, C<PTR2NV> macros, to map the other way, which may be useful in OUTPUT sections. =head2 The Role of the typemap File in Your Distribution The default typemap in the F<lib/ExtUtils> directory of the Perl source contains many useful types which can be used by Perl extensions. Some extensions define additional typemaps which they keep in their own directory. These additional typemaps may reference INPUT and OUTPUT maps in the main typemap. The B<xsubpp> compiler will allow the extension's own typemap to override any mappings which are in the default typemap. Instead of using an additional F<typemap> file, typemaps may be embedded verbatim in XS with a heredoc-like syntax. See the documentation on the C<TYPEMAP:> XS keyword. For CPAN distributions, you can assume that the XS types defined by the perl core are already available. Additionally, the core typemap has default XS types for a large number of C types. For example, if you simply return a C<char *> from your XSUB, the core typemap will have this C type associated with the T_PV XS type. That means your C string will be copied into the PV (pointer value) slot of a new scalar that will be returned from your XSUB to to Perl. If you're developing a CPAN distribution using XS, you may add your own file called F<typemap> to the distribution. That file may contain typemaps that either map types that are specific to your code or that override the core typemap file's mappings for common C types. =head2 Sharing typemaps Between CPAN Distributions Starting with ExtUtils::ParseXS version 3.13_01 (comes with perl 5.16 and better), it is rather easy to share typemap code between multiple CPAN distributions. The general idea is to share it as a module that offers a certain API and have the dependent modules declare that as a built-time requirement and import the typemap into the XS. An example of such a typemap-sharing module on CPAN is C<ExtUtils::Typemaps::Basic>. Two steps to getting that module's typemaps available in your code: =over 4 =item * Declare C<ExtUtils::Typemaps::Basic> as a build-time dependency in C<Makefile.PL> (use C<BUILD_REQUIRES>), or in your C<Build.PL> (use C<build_requires>). =item * Include the following line in the XS section of your XS file: (don't break the line) INCLUDE_COMMAND: $^X -MExtUtils::Typemaps::Cmd -e "print embeddable_typemap(q{Basic})" =back =head2 Writing typemap Entries Each INPUT or OUTPUT typemap entry is a double-quoted Perl string that will be evaluated in the presence of certain variables to get the final C code for mapping a certain C type. This means that you can embed Perl code in your typemap (C) code using constructs such as C<${ perl code that evaluates to scalar reference here }>. A common use case is to generate error messages that refer to the true function name even when using the ALIAS XS feature: ${ $ALIAS ? \q[GvNAME(CvGV(cv))] : \qq[\"$pname\"] } For many typemap examples, refer to the core typemap file that can be found in the perl source tree at F<lib/ExtUtils/typemap>. The Perl variables that are available for interpolation into typemaps are the following: =over 4 =item * I<$var> - the name of the input or output variable, eg. RETVAL for return values. =item * I<$type> - the raw C type of the parameter, any C<:> replaced with C<_>. =item * I<$ntype> - the supplied type with C<*> replaced with C<Ptr>. e.g. for a type of C<Foo::Bar>, I<$ntype> is C<Foo::Bar> =item * I<$arg> - the stack entry, that the parameter is input from or output to, e.g. C<ST(0)> =item * I<$argoff> - the argument stack offset of the argument. ie. 0 for the first argument, etc. =item * I<$pname> - the full name of the XSUB, with including the C<PACKAGE> name, with any C<PREFIX> stripped. This is the non-ALIAS name. =item * I<$Package> - the package specified by the most recent C<PACKAGE> keyword. =item * I<$ALIAS> - non-zero if the current XSUB has any aliases declared with C<ALIAS>. =back =head2 Full Listing of Core Typemaps Each C type is represented by an entry in the typemap file that is responsible for converting perl variables (SV, AV, HV, CV, etc.) to and from that type. The following sections list all XS types that come with perl by default. =over 4 =item T_SV This simply passes the C representation of the Perl variable (an SV*) in and out of the XS layer. This can be used if the C code wants to deal directly with the Perl variable. =item T_SVREF Used to pass in and return a reference to an SV. Note that this typemap does not decrement the reference count when returning the reference to an SV*. See also: T_SVREF_REFCOUNT_FIXED =item T_SVREF_FIXED Used to pass in and return a reference to an SV. This is a fixed variant of T_SVREF that decrements the refcount appropriately when returning a reference to an SV*. Introduced in perl 5.15.4. =item T_AVREF From the perl level this is a reference to a perl array. From the C level this is a pointer to an AV. Note that this typemap does not decrement the reference count when returning an AV*. See also: T_AVREF_REFCOUNT_FIXED =item T_AVREF_REFCOUNT_FIXED From the perl level this is a reference to a perl array. From the C level this is a pointer to an AV. This is a fixed variant of T_AVREF that decrements the refcount appropriately when returning an AV*. Introduced in perl 5.15.4. =item T_HVREF From the perl level this is a reference to a perl hash. From the C level this is a pointer to an HV. Note that this typemap does not decrement the reference count when returning an HV*. See also: T_HVREF_REFCOUNT_FIXED =item T_HVREF_REFCOUNT_FIXED From the perl level this is a reference to a perl hash. From the C level this is a pointer to an HV. This is a fixed variant of T_HVREF that decrements the refcount appropriately when returning an HV*. Introduced in perl 5.15.4. =item T_CVREF From the perl level this is a reference to a perl subroutine (e.g. $sub = sub { 1 };). From the C level this is a pointer to a CV. Note that this typemap does not decrement the reference count when returning an HV*. See also: T_HVREF_REFCOUNT_FIXED =item T_CVREF_REFCOUNT_FIXED From the perl level this is a reference to a perl subroutine (e.g. $sub = sub { 1 };). From the C level this is a pointer to a CV. This is a fixed variant of T_HVREF that decrements the refcount appropriately when returning an HV*. Introduced in perl 5.15.4. =item T_SYSRET The T_SYSRET typemap is used to process return values from system calls. It is only meaningful when passing values from C to perl (there is no concept of passing a system return value from Perl to C). System calls return -1 on error (setting ERRNO with the reason) and (usually) 0 on success. If the return value is -1 this typemap returns C<undef>. If the return value is not -1, this typemap translates a 0 (perl false) to "0 but true" (which is perl true) or returns the value itself, to indicate that the command succeeded. The L<POSIX|POSIX> module makes extensive use of this type. =item T_UV An unsigned integer. =item T_IV A signed integer. This is cast to the required integer type when passed to C and converted to an IV when passed back to Perl. =item T_INT A signed integer. This typemap converts the Perl value to a native integer type (the C<int> type on the current platform). When returning the value to perl it is processed in the same way as for T_IV. Its behaviour is identical to using an C<int> type in XS with T_IV. =item T_ENUM An enum value. Used to transfer an enum component from C. There is no reason to pass an enum value to C since it is stored as an IV inside perl. =item T_BOOL A boolean type. This can be used to pass true and false values to and from C. =item T_U_INT This is for unsigned integers. It is equivalent to using T_UV but explicitly casts the variable to type C<unsigned int>. The default type for C<unsigned int> is T_UV. =item T_SHORT Short integers. This is equivalent to T_IV but explicitly casts the return to type C<short>. The default typemap for C<short> is T_IV. =item T_U_SHORT Unsigned short integers. This is equivalent to T_UV but explicitly casts the return to type C<unsigned short>. The default typemap for C<unsigned short> is T_UV. T_U_SHORT is used for type C<U16> in the standard typemap. =item T_LONG Long integers. This is equivalent to T_IV but explicitly casts the return to type C<long>. The default typemap for C<long> is T_IV. =item T_U_LONG Unsigned long integers. This is equivalent to T_UV but explicitly casts the return to type C<unsigned long>. The default typemap for C<unsigned long> is T_UV. T_U_LONG is used for type C<U32> in the standard typemap. =item T_CHAR Single 8-bit characters. =item T_U_CHAR An unsigned byte. =item T_FLOAT A floating point number. This typemap guarantees to return a variable cast to a C<float>. =item T_NV A Perl floating point number. Similar to T_IV and T_UV in that the return type is cast to the requested numeric type rather than to a specific type. =item T_DOUBLE A double precision floating point number. This typemap guarantees to return a variable cast to a C<double>. =item T_PV A string (char *). =item T_PTR A memory address (pointer). Typically associated with a C<void *> type. =item T_PTRREF Similar to T_PTR except that the pointer is stored in a scalar and the reference to that scalar is returned to the caller. This can be used to hide the actual pointer value from the programmer since it is usually not required directly from within perl. The typemap checks that a scalar reference is passed from perl to XS. =item T_PTROBJ Similar to T_PTRREF except that the reference is blessed into a class. This allows the pointer to be used as an object. Most commonly used to deal with C structs. The typemap checks that the perl object passed into the XS routine is of the correct class (or part of a subclass). The pointer is blessed into a class that is derived from the name of type of the pointer but with all '*' in the name replaced with 'Ptr'. =item T_REF_IV_REF NOT YET =item T_REF_IV_PTR Similar to T_PTROBJ in that the pointer is blessed into a scalar object. The difference is that when the object is passed back into XS it must be of the correct type (inheritance is not supported). The pointer is blessed into a class that is derived from the name of type of the pointer but with all '*' in the name replaced with 'Ptr'. =item T_PTRDESC NOT YET =item T_REFREF Similar to T_PTRREF, except the pointer stored in the referenced scalar is dereferenced and copied to the output variable. This means that T_REFREF is to T_PTRREF as T_OPAQUE is to T_OPAQUEPTR. All clear? Only the INPUT part of this is implemented (Perl to XSUB) and there are no known users in core or on CPAN. =item T_REFOBJ NOT YET =item T_OPAQUEPTR This can be used to store bytes in the string component of the SV. Here the representation of the data is irrelevant to perl and the bytes themselves are just stored in the SV. It is assumed that the C variable is a pointer (the bytes are copied from that memory location). If the pointer is pointing to something that is represented by 8 bytes then those 8 bytes are stored in the SV (and length() will report a value of 8). This entry is similar to T_OPAQUE. In principle the unpack() command can be used to convert the bytes back to a number (if the underlying type is known to be a number). This entry can be used to store a C structure (the number of bytes to be copied is calculated using the C C<sizeof> function) and can be used as an alternative to T_PTRREF without having to worry about a memory leak (since Perl will clean up the SV). =item T_OPAQUE This can be used to store data from non-pointer types in the string part of an SV. It is similar to T_OPAQUEPTR except that the typemap retrieves the pointer directly rather than assuming it is being supplied. For example, if an integer is imported into Perl using T_OPAQUE rather than T_IV the underlying bytes representing the integer will be stored in the SV but the actual integer value will not be available. i.e. The data is opaque to perl. The data may be retrieved using the C<unpack> function if the underlying type of the byte stream is known. T_OPAQUE supports input and output of simple types. T_OPAQUEPTR can be used to pass these bytes back into C if a pointer is acceptable. =item Implicit array xsubpp supports a special syntax for returning packed C arrays to perl. If the XS return type is given as array(type, nelem) xsubpp will copy the contents of C<nelem * sizeof(type)> bytes from RETVAL to an SV and push it onto the stack. This is only really useful if the number of items to be returned is known at compile time and you don't mind having a string of bytes in your SV. Use T_ARRAY to push a variable number of arguments onto the return stack (they won't be packed as a single string though). This is similar to using T_OPAQUEPTR but can be used to process more than one element. =item T_PACKED Calls user-supplied functions for conversion. For C<OUTPUT> (XSUB to Perl), a function named C<XS_pack_$ntype> is called with the output Perl scalar and the C variable to convert from. C<$ntype> is the normalized C type that is to be mapped to Perl. Normalized means that all C<*> are replaced by the string C<Ptr>. The return value of the function is ignored. Conversely for C<INPUT> (Perl to XSUB) mapping, the function named C<XS_unpack_$ntype> is called with the input Perl scalar as argument and the return value is cast to the mapped C type and assigned to the output C variable. An example conversion function for a typemapped struct C<foo_t *> might be: static void XS_pack_foo_tPtr(SV *out, foo_t *in) { dTHX; /* alas, signature does not include pTHX_ */ HV* hash = newHV(); hv_stores(hash, "int_member", newSViv(in->int_member)); hv_stores(hash, "float_member", newSVnv(in->float_member)); /* ... */ /* mortalize as thy stack is not refcounted */ sv_setsv(out, sv_2mortal(newRV_noinc((SV*)hash))); } The conversion from Perl to C is left as an exercise to the reader, but the prototype would be: static foo_t * XS_unpack_foo_tPtr(SV *in); Instead of an actual C function that has to fetch the thread context using C<dTHX>, you can define macros of the same name and avoid the overhead. Also, keep in mind to possibly free the memory allocated by C<XS_unpack_foo_tPtr>. =item T_PACKEDARRAY T_PACKEDARRAY is similar to T_PACKED. In fact, the C<INPUT> (Perl to XSUB) typemap is indentical, but the C<OUTPUT> typemap passes an additional argument to the C<XS_pack_$ntype> function. This third parameter indicates the number of elements in the output so that the function can handle C arrays sanely. The variable needs to be declared by the user and must have the name C<count_$ntype> where C<$ntype> is the normalized C type name as explained above. The signature of the function would be for the example above and C<foo_t **>: static void XS_pack_foo_tPtrPtr(SV *out, foo_t *in, UV count_foo_tPtrPtr); The type of the third parameter is arbitrary as far as the typemap is concerned. It just has to be in line with the declared variable. Of course, unless you know the number of elements in the C<sometype **> C array, within your XSUB, the return value from C<foo_t ** XS_unpack_foo_tPtrPtr(...)> will be hard to decypher. Since the details are all up to the XS author (the typemap user), there are several solutions, none of which particularly elegant. The most commonly seen solution has been to allocate memory for N+1 pointers and assign C<NULL> to the (N+1)th to facilitate iteration. Alternatively, using a customized typemap for your purposes in the first place is probably preferrable. =item T_DATAUNIT NOT YET =item T_CALLBACK NOT YET =item T_ARRAY This is used to convert the perl argument list to a C array and for pushing the contents of a C array onto the perl argument stack. The usual calling signature is @out = array_func( @in ); Any number of arguments can occur in the list before the array but the input and output arrays must be the last elements in the list. When used to pass a perl list to C the XS writer must provide a function (named after the array type but with 'Ptr' substituted for '*') to allocate the memory required to hold the list. A pointer should be returned. It is up to the XS writer to free the memory on exit from the function. The variable C<ix_$var> is set to the number of elements in the new array. When returning a C array to Perl the XS writer must provide an integer variable called C<size_$var> containing the number of elements in the array. This is used to determine how many elements should be pushed onto the return argument stack. This is not required on input since Perl knows how many arguments are on the stack when the routine is called. Ordinarily this variable would be called C<size_RETVAL>. Additionally, the type of each element is determined from the type of the array. If the array uses type C<intArray *> xsubpp will automatically work out that it contains variables of type C<int> and use that typemap entry to perform the copy of each element. All pointer '*' and 'Array' tags are removed from the name to determine the subtype. =item T_STDIO This is used for passing perl filehandles to and from C using C<FILE *> structures. =item T_INOUT This is used for passing perl filehandles to and from C using C<PerlIO *> structures. The file handle can used for reading and writing. This corresponds to the C<+E<lt>> mode, see also T_IN and T_OUT. See L<perliol> for more information on the Perl IO abstraction layer. Perl must have been built with C<-Duseperlio>. There is no check to assert that the filehandle passed from Perl to C was created with the right C<open()> mode. Hint: The L<perlxstut> tutorial covers the T_INOUT, T_IN, and T_OUT XS types nicely. =item T_IN Same as T_INOUT, but the filehandle that is returned from C to Perl can only be used for reading (mode C<E<lt>>). =item T_OUT Same as T_INOUT, but the filehandle that is returned from C to Perl is set to use the open mode C<+E<gt>>. =back PK PU�\�~q�� � perlvar.podnu �[��� =head1 NAME perlvar - Perl predefined variables =head1 DESCRIPTION =head2 The Syntax of Variable Names Variable names in Perl can have several formats. Usually, they must begin with a letter or underscore, in which case they can be arbitrarily long (up to an internal limit of 251 characters) and may contain letters, digits, underscores, or the special sequence C<::> or C<'>. In this case, the part before the last C<::> or C<'> is taken to be a I<package qualifier>; see L<perlmod>. Perl variable names may also be a sequence of digits or a single punctuation or control character. These names are all reserved for special uses by Perl; for example, the all-digits names are used to hold data captured by backreferences after a regular expression match. Perl has a special syntax for the single-control-character names: It understands C<^X> (caret C<X>) to mean the control-C<X> character. For example, the notation C<$^W> (dollar-sign caret C<W>) is the scalar variable whose name is the single character control-C<W>. This is better than typing a literal control-C<W> into your program. Since Perl 5.6, Perl variable names may be alphanumeric strings that begin with control characters (or better yet, a caret). These variables must be written in the form C<${^Foo}>; the braces are not optional. C<${^Foo}> denotes the scalar variable whose name is a control-C<F> followed by two C<o>'s. These variables are reserved for future special uses by Perl, except for the ones that begin with C<^_> (control-underscore or caret-underscore). No control-character name that begins with C<^_> will acquire a special meaning in any future version of Perl; such names may therefore be used safely in programs. C<$^_> itself, however, I<is> reserved. Perl identifiers that begin with digits, control characters, or punctuation characters are exempt from the effects of the C<package> declaration and are always forced to be in package C<main>; they are also exempt from C<strict 'vars'> errors. A few other names are also exempt in these ways: ENV STDIN INC STDOUT ARGV STDERR ARGVOUT SIG In particular, the special C<${^_XYZ}> variables are always taken to be in package C<main>, regardless of any C<package> declarations presently in scope. =head1 SPECIAL VARIABLES The following names have special meaning to Perl. Most punctuation names have reasonable mnemonics, or analogs in the shells. Nevertheless, if you wish to use long variable names, you need only say: use English; at the top of your program. This aliases all the short names to the long names in the current package. Some even have medium names, generally borrowed from B<awk>. To avoid a performance hit, if you don't need the C<$PREMATCH>, C<$MATCH>, or C<$POSTMATCH> it's best to use the C<English> module without them: use English '-no_match_vars'; Before you continue, note the sort order for variables. In general, we first list the variables in case-insensitive, almost-lexigraphical order (ignoring the C<{> or C<^> preceding words, as in C<${^UNICODE}> or C<$^T>), although C<$_> and C<@_> move up to the top of the pile. For variables with the same identifier, we list it in order of scalar, array, hash, and bareword. =head2 General Variables =over 8 =item $ARG =item $_ X<$_> X<$ARG> The default input and pattern-searching space. The following pairs are equivalent: while (<>) {...} # equivalent only in while! while (defined($_ = <>)) {...} /^Subject:/ $_ =~ /^Subject:/ tr/a-z/A-Z/ $_ =~ tr/a-z/A-Z/ chomp chomp($_) Here are the places where Perl will assume C<$_> even if you don't use it: =over 3 =item * The following functions use C<$_> as a default argument: abs, alarm, chomp, chop, chr, chroot, cos, defined, eval, evalbytes, exp, glob, hex, int, lc, lcfirst, length, log, lstat, mkdir, oct, ord, pos, print, quotemeta, readlink, readpipe, ref, require, reverse (in scalar context only), rmdir, sin, split (on its second argument), sqrt, stat, study, uc, ucfirst, unlink, unpack. =item * All file tests (C<-f>, C<-d>) except for C<-t>, which defaults to STDIN. See L<perlfunc/-X> =item * The pattern matching operations C<m//>, C<s///> and C<tr///> (aka C<y///>) when used without an C<=~> operator. =item * The default iterator variable in a C<foreach> loop if no other variable is supplied. =item * The implicit iterator variable in the C<grep()> and C<map()> functions. =item * The implicit variable of C<given()>. =item * The default place to put an input record when a C<< <FH> >> operation's result is tested by itself as the sole criterion of a C<while> test. Outside a C<while> test, this will not happen. =back As C<$_> is a global variable, this may lead in some cases to unwanted side-effects. As of perl 5.10, you can now use a lexical version of C<$_> by declaring it in a file or in a block with C<my>. Moreover, declaring C<our $_> restores the global C<$_> in the current scope. Mnemonic: underline is understood in certain operations. =item @ARG =item @_ X<@_> X<@ARG> Within a subroutine the array C<@_> contains the parameters passed to that subroutine. Inside a subroutine, C<@_> is the default array for the array operators C<push>, C<pop>, C<shift>, and C<unshift>. See L<perlsub>. =item $LIST_SEPARATOR =item $" X<$"> X<$LIST_SEPARATOR> When an array or an array slice is interpolated into a double-quoted string or a similar context such as C</.../>, its elements are separated by this value. Default is a space. For example, this: print "The array is: @array\n"; is equivalent to this: print "The array is: " . join($", @array) . "\n"; Mnemonic: works in double-quoted context. =item $PROCESS_ID =item $PID =item $$ X<$$> X<$PID> X<$PROCESS_ID> The process number of the Perl running this script. Though you I<can> set this variable, doing so is generally discouraged, although it can be invaluable for some testing purposes. It will be reset automatically across C<fork()> calls. Note for Linux and Debian GNU/kFreeBSD users: Before Perl v5.16.0 perl would emulate POSIX semantics on Linux systems using LinuxThreads, a partial implementation of POSIX Threads that has since been superseded by the Native POSIX Thread Library (NPTL). LinuxThreads is now obsolete on Linux, and and caching C<getpid()> like this made embedding perl unnecessarily complex (since you'd have to manually update the value of $$), so now C<$$> and C<getppid()> will always return the same values as the underlying C library. Debian GNU/kFreeBSD systems also used LinuxThreads up until and including the 6.0 release, but after that moved to FreeBSD thread semantics, which are POSIX-like. To see if your system is affected by this discrepancy check if C<getconf GNU_LIBPTHREAD_VERSION | grep -q NPTL> returns a false value. NTPL threads preserve the POSIX semantics. Mnemonic: same as shells. =item $PROGRAM_NAME =item $0 X<$0> X<$PROGRAM_NAME> Contains the name of the program being executed. On some (but not all) operating systems assigning to C<$0> modifies the argument area that the C<ps> program sees. On some platforms you may have to use special C<ps> options or a different C<ps> to see the changes. Modifying the C<$0> is more useful as a way of indicating the current program state than it is for hiding the program you're running. Note that there are platform-specific limitations on the maximum length of C<$0>. In the most extreme case it may be limited to the space occupied by the original C<$0>. In some platforms there may be arbitrary amount of padding, for example space characters, after the modified name as shown by C<ps>. In some platforms this padding may extend all the way to the original length of the argument area, no matter what you do (this is the case for example with Linux 2.2). Note for BSD users: setting C<$0> does not completely remove "perl" from the ps(1) output. For example, setting C<$0> to C<"foobar"> may result in C<"perl: foobar (perl)"> (whether both the C<"perl: "> prefix and the " (perl)" suffix are shown depends on your exact BSD variant and version). This is an operating system feature, Perl cannot help it. In multithreaded scripts Perl coordinates the threads so that any thread may modify its copy of the C<$0> and the change becomes visible to ps(1) (assuming the operating system plays along). Note that the view of C<$0> the other threads have will not change since they have their own copies of it. If the program has been given to perl via the switches C<-e> or C<-E>, C<$0> will contain the string C<"-e">. On Linux as of perl 5.14 the legacy process name will be set with C<prctl(2)>, in addition to altering the POSIX name via C<argv[0]> as perl has done since version 4.000. Now system utilities that read the legacy process name such as ps, top and killall will recognize the name you set when assigning to C<$0>. The string you supply will be cut off at 16 bytes, this is a limitation imposed by Linux. Mnemonic: same as B<sh> and B<ksh>. =item $REAL_GROUP_ID =item $GID =item $( X<$(> X<$GID> X<$REAL_GROUP_ID> The real gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by C<getgid()>, and the subsequent ones by C<getgroups()>, one of which may be the same as the first number. However, a value assigned to C<$(> must be a single number used to set the real gid. So the value given by C<$(> should I<not> be assigned back to C<$(> without being forced numeric, such as by adding zero. Note that this is different to the effective gid (C<$)>) which does take a list. You can change both the real gid and the effective gid at the same time by using C<POSIX::setgid()>. Changes to C<$(> require a check to C<$!> to detect any possible errors after an attempted change. Mnemonic: parentheses are used to I<group> things. The real gid is the group you I<left>, if you're running setgid. =item $EFFECTIVE_GROUP_ID =item $EGID =item $) X<$)> X<$EGID> X<$EFFECTIVE_GROUP_ID> The effective gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by C<getegid()>, and the subsequent ones by C<getgroups()>, one of which may be the same as the first number. Similarly, a value assigned to C<$)> must also be a space-separated list of numbers. The first number sets the effective gid, and the rest (if any) are passed to C<setgroups()>. To get the effect of an empty list for C<setgroups()>, just repeat the new effective gid; that is, to force an effective gid of 5 and an effectively empty C<setgroups()> list, say C< $) = "5 5" >. You can change both the effective gid and the real gid at the same time by using C<POSIX::setgid()> (use only a single numeric argument). Changes to C<$)> require a check to C<$!> to detect any possible errors after an attempted change. C<< $< >>, C<< $> >>, C<$(> and C<$)> can be set only on machines that support the corresponding I<set[re][ug]id()> routine. C<$(> and C<$)> can be swapped only on machines supporting C<setregid()>. Mnemonic: parentheses are used to I<group> things. The effective gid is the group that's I<right> for you, if you're running setgid. =item $REAL_USER_ID =item $UID =item $< X<< $< >> X<$UID> X<$REAL_USER_ID> The real uid of this process. You can change both the real uid and the effective uid at the same time by using C<POSIX::setuid()>. Since changes to C<< $< >> require a system call, check C<$!> after a change attempt to detect any possible errors. Mnemonic: it's the uid you came I<from>, if you're running setuid. =item $EFFECTIVE_USER_ID =item $EUID =item $> X<< $> >> X<$EUID> X<$EFFECTIVE_USER_ID> The effective uid of this process. For example: $< = $>; # set real to effective uid ($<,$>) = ($>,$<); # swap real and effective uids You can change both the effective uid and the real uid at the same time by using C<POSIX::setuid()>. Changes to C<< $> >> require a check to C<$!> to detect any possible errors after an attempted change. C<< $< >> and C<< $> >> can be swapped only on machines supporting C<setreuid()>. Mnemonic: it's the uid you went I<to>, if you're running setuid. =item $SUBSCRIPT_SEPARATOR =item $SUBSEP =item $; X<$;> X<$SUBSEP> X<SUBSCRIPT_SEPARATOR> The subscript separator for multidimensional array emulation. If you refer to a hash element as $foo{$a,$b,$c} it really means $foo{join($;, $a, $b, $c)} But don't put @foo{$a,$b,$c} # a slice--note the @ which means ($foo{$a},$foo{$b},$foo{$c}) Default is "\034", the same as SUBSEP in B<awk>. If your keys contain binary data there might not be any safe value for C<$;>. Consider using "real" multidimensional arrays as described in L<perllol>. Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon. =item $a =item $b X<$a> X<$b> Special package variables when using C<sort()>, see L<perlfunc/sort>. Because of this specialness C<$a> and C<$b> don't need to be declared (using C<use vars>, or C<our()>) even when using the C<strict 'vars'> pragma. Don't lexicalize them with C<my $a> or C<my $b> if you want to be able to use them in the C<sort()> comparison block or function. =item %ENV X<%ENV> The hash C<%ENV> contains your current environment. Setting a value in C<ENV> changes the environment for any child processes you subsequently C<fork()> off. =item $SYSTEM_FD_MAX =item $^F X<$^F> X<$SYSTEM_FD_MAX> The maximum system file descriptor, ordinarily 2. System file descriptors are passed to C<exec()>ed processes, while higher file descriptors are not. Also, during an C<open()>, system file descriptors are preserved even if the C<open()> fails (ordinary file descriptors are closed before the C<open()> is attempted). The close-on-exec status of a file descriptor will be decided according to the value of C<$^F> when the corresponding file, pipe, or socket was opened, not the time of the C<exec()>. =item @F X<@F> The array C<@F> contains the fields of each line read in when autosplit mode is turned on. See L<perlrun> for the B<-a> switch. This array is package-specific, and must be declared or given a full package name if not in package main when running under C<strict 'vars'>. =item @INC X<@INC> The array C<@INC> contains the list of places that the C<do EXPR>, C<require>, or C<use> constructs look for their library files. It initially consists of the arguments to any B<-I> command-line switches, followed by the default Perl library, probably F</usr/local/lib/perl>, followed by ".", to represent the current directory. ("." will not be appended if taint checks are enabled, either by C<-T> or by C<-t>.) If you need to modify this at runtime, you should use the C<use lib> pragma to get the machine-dependent library properly loaded also: use lib '/mypath/libdir/'; use SomeMod; You can also insert hooks into the file inclusion system by putting Perl code directly into C<@INC>. Those hooks may be subroutine references, array references or blessed objects. See L<perlfunc/require> for details. =item %INC X<%INC> The hash C<%INC> contains entries for each filename included via the C<do>, C<require>, or C<use> operators. The key is the filename you specified (with module names converted to pathnames), and the value is the location of the file found. The C<require> operator uses this hash to determine whether a particular file has already been included. If the file was loaded via a hook (e.g. a subroutine reference, see L<perlfunc/require> for a description of these hooks), this hook is by default inserted into C<%INC> in place of a filename. Note, however, that the hook may have set the C<%INC> entry by itself to provide some more specific info. =item $INPLACE_EDIT =item $^I X<$^I> X<$INPLACE_EDIT> The current value of the inplace-edit extension. Use C<undef> to disable inplace editing. Mnemonic: value of B<-i> switch. =item $^M X<$^M> By default, running out of memory is an untrappable, fatal error. However, if suitably built, Perl can use the contents of C<$^M> as an emergency memory pool after C<die()>ing. Suppose that your Perl were compiled with C<-DPERL_EMERGENCY_SBRK> and used Perl's malloc. Then $^M = 'a' x (1 << 16); would allocate a 64K buffer for use in an emergency. See the F<INSTALL> file in the Perl distribution for information on how to add custom C compilation flags when compiling perl. To discourage casual use of this advanced feature, there is no L<English|English> long name for this variable. This variable was added in Perl 5.004. =item $OSNAME =item $^O X<$^O> X<$OSNAME> The name of the operating system under which this copy of Perl was built, as determined during the configuration process. For examples see L<perlport/PLATFORMS>. The value is identical to C<$Config{'osname'}>. See also L<Config> and the B<-V> command-line switch documented in L<perlrun>. In Windows platforms, C<$^O> is not very helpful: since it is always C<MSWin32>, it doesn't tell the difference between 95/98/ME/NT/2000/XP/CE/.NET. Use C<Win32::GetOSName()> or Win32::GetOSVersion() (see L<Win32> and L<perlport>) to distinguish between the variants. This variable was added in Perl 5.003. =item %SIG X<%SIG> The hash C<%SIG> contains signal handlers for signals. For example: sub handler { # 1st argument is signal name my($sig) = @_; print "Caught a SIG$sig--shutting down\n"; close(LOG); exit(0); } $SIG{'INT'} = \&handler; $SIG{'QUIT'} = \&handler; ... $SIG{'INT'} = 'DEFAULT'; # restore default action $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT Using a value of C<'IGNORE'> usually has the effect of ignoring the signal, except for the C<CHLD> signal. See L<perlipc> for more about this special case. Here are some other examples: $SIG{"PIPE"} = "Plumber"; # assumes main::Plumber (not # recommended) $SIG{"PIPE"} = \&Plumber; # just fine; assume current # Plumber $SIG{"PIPE"} = *Plumber; # somewhat esoteric $SIG{"PIPE"} = Plumber(); # oops, what did Plumber() # return?? Be sure not to use a bareword as the name of a signal handler, lest you inadvertently call it. If your system has the C<sigaction()> function then signal handlers are installed using it. This means you get reliable signal handling. The default delivery policy of signals changed in Perl 5.8.0 from immediate (also known as "unsafe") to deferred, also known as "safe signals". See L<perlipc> for more information. Certain internal hooks can be also set using the C<%SIG> hash. The routine indicated by C<$SIG{__WARN__}> is called when a warning message is about to be printed. The warning message is passed as the first argument. The presence of a C<__WARN__> hook causes the ordinary printing of warnings to C<STDERR> to be suppressed. You can use this to save warnings in a variable, or turn warnings into fatal errors, like this: local $SIG{__WARN__} = sub { die $_[0] }; eval $proggie; As the C<'IGNORE'> hook is not supported by C<__WARN__>, you can disable warnings using the empty subroutine: local $SIG{__WARN__} = sub {}; The routine indicated by C<$SIG{__DIE__}> is called when a fatal exception is about to be thrown. The error message is passed as the first argument. When a C<__DIE__> hook routine returns, the exception processing continues as it would have in the absence of the hook, unless the hook routine itself exits via a C<goto &sub>, a loop exit, or a C<die()>. The C<__DIE__> handler is explicitly disabled during the call, so that you can die from a C<__DIE__> handler. Similarly for C<__WARN__>. Due to an implementation glitch, the C<$SIG{__DIE__}> hook is called even inside an C<eval()>. Do not use this to rewrite a pending exception in C<$@>, or as a bizarre substitute for overriding C<CORE::GLOBAL::die()>. This strange action at a distance may be fixed in a future release so that C<$SIG{__DIE__}> is only called if your program is about to exit, as was the original intent. Any other use is deprecated. C<__DIE__>/C<__WARN__> handlers are very special in one respect: they may be called to report (probable) errors found by the parser. In such a case the parser may be in inconsistent state, so any attempt to evaluate Perl code from such a handler will probably result in a segfault. This means that warnings or errors that result from parsing Perl should be used with extreme caution, like this: require Carp if defined $^S; Carp::confess("Something wrong") if defined &Carp::confess; die "Something wrong, but could not load Carp to give " . "backtrace...\n\t" . "To see backtrace try starting Perl with -MCarp switch"; Here the first line will load C<Carp> I<unless> it is the parser who called the handler. The second line will print backtrace and die if C<Carp> was available. The third line will be executed only if C<Carp> was not available. Having to even think about the C<$^S> variable in your exception handlers is simply wrong. C<$SIG{__DIE__}> as currently implemented invites grievous and difficult to track down errors. Avoid it and use an C<END{}> or CORE::GLOBAL::die override instead. See L<perlfunc/die>, L<perlfunc/warn>, L<perlfunc/eval>, and L<warnings> for additional information. =item $BASETIME =item $^T X<$^T> X<$BASETIME> The time at which the program began running, in seconds since the epoch (beginning of 1970). The values returned by the B<-M>, B<-A>, and B<-C> filetests are based on this value. =item $PERL_VERSION =item $^V X<$^V> X<$PERL_VERSION> The revision, version, and subversion of the Perl interpreter, represented as a C<version> object. This variable first appeared in perl 5.6.0; earlier versions of perl will see an undefined value. Before perl 5.10.0 C<$^V> was represented as a v-string. C<$^V> can be used to determine whether the Perl interpreter executing a script is in the right range of versions. For example: warn "Hashes not randomized!\n" if !$^V or $^V lt v5.8.1 To convert C<$^V> into its string representation use C<sprintf()>'s C<"%vd"> conversion: printf "version is v%vd\n", $^V; # Perl's version See the documentation of C<use VERSION> and C<require VERSION> for a convenient way to fail if the running Perl interpreter is too old. See also C<$]> for an older representation of the Perl version. This variable was added in Perl 5.6. Mnemonic: use ^V for Version Control. =item ${^WIN32_SLOPPY_STAT} X<${^WIN32_SLOPPY_STAT}> X<sitecustomize> X<sitecustomize.pl> If this variable is set to a true value, then C<stat()> on Windows will not try to open the file. This means that the link count cannot be determined and file attributes may be out of date if additional hardlinks to the file exist. On the other hand, not opening the file is considerably faster, especially for files on network drives. This variable could be set in the F<sitecustomize.pl> file to configure the local Perl installation to use "sloppy" C<stat()> by default. See the documentation for B<-f> in L<perlrun|perlrun/"Command Switches"> for more information about site customization. This variable was added in Perl 5.10. =item $EXECUTABLE_NAME =item $^X X<$^X> X<$EXECUTABLE_NAME> The name used to execute the current copy of Perl, from C's C<argv[0]> or (where supported) F</proc/self/exe>. Depending on the host operating system, the value of C<$^X> may be a relative or absolute pathname of the perl program file, or may be the string used to invoke perl but not the pathname of the perl program file. Also, most operating systems permit invoking programs that are not in the PATH environment variable, so there is no guarantee that the value of C<$^X> is in PATH. For VMS, the value may or may not include a version number. You usually can use the value of C<$^X> to re-invoke an independent copy of the same perl that is currently running, e.g., @first_run = `$^X -le "print int rand 100 for 1..100"`; But recall that not all operating systems support forking or capturing of the output of commands, so this complex statement may not be portable. It is not safe to use the value of C<$^X> as a path name of a file, as some operating systems that have a mandatory suffix on executable files do not require use of the suffix when invoking a command. To convert the value of C<$^X> to a path name, use the following statements: # Build up a set of file names (not command names). use Config; my $this_perl = $^X; if ($^O ne 'VMS') { $this_perl .= $Config{_exe} unless $this_perl =~ m/$Config{_exe}$/i; } Because many operating systems permit anyone with read access to the Perl program file to make a copy of it, patch the copy, and then execute the copy, the security-conscious Perl programmer should take care to invoke the installed copy of perl, not the copy referenced by C<$^X>. The following statements accomplish this goal, and produce a pathname that can be invoked as a command or referenced as a file. use Config; my $secure_perl_path = $Config{perlpath}; if ($^O ne 'VMS') { $secure_perl_path .= $Config{_exe} unless $secure_perl_path =~ m/$Config{_exe}$/i; } =back =head2 Variables related to regular expressions Most of the special variables related to regular expressions are side effects. Perl sets these variables when it has a successful match, so you should check the match result before using them. For instance: if( /P(A)TT(ER)N/ ) { print "I found $1 and $2\n"; } These variables are read-only and dynamically-scoped, unless we note otherwise. The dynamic nature of the regular expression variables means that their value is limited to the block that they are in, as demonstrated by this bit of code: my $outer = 'Wallace and Grommit'; my $inner = 'Mutt and Jeff'; my $pattern = qr/(\S+) and (\S+)/; sub show_n { print "\$1 is $1; \$2 is $2\n" } { OUTER: show_n() if $outer =~ m/$pattern/; INNER: { show_n() if $inner =~ m/$pattern/; } show_n(); } The output shows that while in the C<OUTER> block, the values of C<$1> and C<$2> are from the match against C<$outer>. Inside the C<INNER> block, the values of C<$1> and C<$2> are from the match against C<$inner>, but only until the end of the block (i.e. the dynamic scope). After the C<INNER> block completes, the values of C<$1> and C<$2> return to the values for the match against C<$outer> even though we have not made another match: $1 is Wallace; $2 is Grommit $1 is Mutt; $2 is Jeff $1 is Wallace; $2 is Grommit Due to an unfortunate accident of Perl's implementation, C<use English> imposes a considerable performance penalty on all regular expression matches in a program because it uses the C<$`>, C<$&>, and C<$'>, regardless of whether they occur in the scope of C<use English>. For that reason, saying C<use English> in libraries is strongly discouraged unless you import it without the match variables: use English '-no_match_vars' The C<Devel::NYTProf> and C<Devel::FindAmpersand> modules can help you find uses of these problematic match variables in your code. Since Perl 5.10, you can use the C</p> match operator flag and the C<${^PREMATCH}>, C<${^MATCH}>, and C<${^POSTMATCH}> variables instead so you only suffer the performance penalties. =over 8 =item $<I<digits>> ($1, $2, ...) X<$1> X<$2> X<$3> Contains the subpattern from the corresponding set of capturing parentheses from the last successful pattern match, not counting patterns matched in nested blocks that have been exited already. These variables are read-only and dynamically-scoped. Mnemonic: like \digits. =item $MATCH =item $& X<$&> X<$MATCH> The string matched by the last successful pattern match (not counting any matches hidden within a BLOCK or C<eval()> enclosed by the current BLOCK). The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. To avoid this penalty, you can extract the same substring by using L</@->. Starting with Perl 5.10, you can use the C</p> match flag and the C<${^MATCH}> variable to do the same thing for particular match operations. This variable is read-only and dynamically-scoped. Mnemonic: like C<&> in some editors. =item ${^MATCH} X<${^MATCH}> This is similar to C<$&> (C<$MATCH>) except that it does not incur the performance penalty associated with that variable, and is only guaranteed to return a defined value when the pattern was compiled or executed with the C</p> modifier. This variable was added in Perl 5.10. This variable is read-only and dynamically-scoped. =item $PREMATCH =item $` X<$`> X<$PREMATCH> X<${^PREMATCH}> The string preceding whatever was matched by the last successful pattern match, not counting any matches hidden within a BLOCK or C<eval> enclosed by the current BLOCK. The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. To avoid this penalty, you can extract the same substring by using L</@->. Starting with Perl 5.10, you can use the C</p> match flag and the C<${^PREMATCH}> variable to do the same thing for particular match operations. This variable is read-only and dynamically-scoped. Mnemonic: C<`> often precedes a quoted string. =item ${^PREMATCH} X<$`> X<${^PREMATCH}> This is similar to C<$`> ($PREMATCH) except that it does not incur the performance penalty associated with that variable, and is only guaranteed to return a defined value when the pattern was compiled or executed with the C</p> modifier. This variable was added in Perl 5.10 This variable is read-only and dynamically-scoped. =item $POSTMATCH =item $' X<$'> X<$POSTMATCH> X<${^POSTMATCH}> X<@-> The string following whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or C<eval()> enclosed by the current BLOCK). Example: local $_ = 'abcdefghi'; /def/; print "$`:$&:$'\n"; # prints abc:def:ghi The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. To avoid this penalty, you can extract the same substring by using L</@->. Starting with Perl 5.10, you can use the C</p> match flag and the C<${^POSTMATCH}> variable to do the same thing for particular match operations. This variable is read-only and dynamically-scoped. Mnemonic: C<'> often follows a quoted string. =item ${^POSTMATCH} X<${^POSTMATCH}> X<$'> X<$POSTMATCH> This is similar to C<$'> (C<$POSTMATCH>) except that it does not incur the performance penalty associated with that variable, and is only guaranteed to return a defined value when the pattern was compiled or executed with the C</p> modifier. This variable was added in Perl 5.10. This variable is read-only and dynamically-scoped. =item $LAST_PAREN_MATCH =item $+ X<$+> X<$LAST_PAREN_MATCH> The text matched by the last bracket of the last successful search pattern. This is useful if you don't know which one of a set of alternative patterns matched. For example: /Version: (.*)|Revision: (.*)/ && ($rev = $+); This variable is read-only and dynamically-scoped. Mnemonic: be positive and forward looking. =item $LAST_SUBMATCH_RESULT =item $^N X<$^N> X<$LAST_SUBMATCH_RESULT> The text matched by the used group most-recently closed (i.e. the group with the rightmost closing parenthesis) of the last successful search pattern. This is primarily used inside C<(?{...})> blocks for examining text recently matched. For example, to effectively capture text to a variable (in addition to C<$1>, C<$2>, etc.), replace C<(...)> with (?:(...)(?{ $var = $^N })) By setting and then using C<$var> in this way relieves you from having to worry about exactly which numbered set of parentheses they are. This variable was added in Perl 5.8. Mnemonic: the (possibly) Nested parenthesis that most recently closed. =item @LAST_MATCH_END =item @+ X<@+> X<@LAST_MATCH_END> This array holds the offsets of the ends of the last successful submatches in the currently active dynamic scope. C<$+[0]> is the offset into the string of the end of the entire match. This is the same value as what the C<pos> function returns when called on the variable that was matched against. The I<n>th element of this array holds the offset of the I<n>th submatch, so C<$+[1]> is the offset past where C<$1> ends, C<$+[2]> the offset past where C<$2> ends, and so on. You can use C<$#+> to determine how many subgroups were in the last successful match. See the examples given for the C<@-> variable. This variable was added in Perl 5.6. =item %LAST_PAREN_MATCH =item %+ X<%+> X<%LAST_PAREN_MATCH> Similar to C<@+>, the C<%+> hash allows access to the named capture buffers, should they exist, in the last successful match in the currently active dynamic scope. For example, C<$+{foo}> is equivalent to C<$1> after the following match: 'foo' =~ /(?<foo>foo)/; The keys of the C<%+> hash list only the names of buffers that have captured (and that are thus associated to defined values). The underlying behaviour of C<%+> is provided by the L<Tie::Hash::NamedCapture> module. B<Note:> C<%-> and C<%+> are tied views into a common internal hash associated with the last successful regular expression. Therefore mixing iterative access to them via C<each> may have unpredictable results. Likewise, if the last successful match changes, then the results may be surprising. This variable was added in Perl 5.10. This variable is read-only and dynamically-scoped. =item @LAST_MATCH_START =item @- X<@-> X<@LAST_MATCH_START> C<$-[0]> is the offset of the start of the last successful match. C<$-[>I<n>C<]> is the offset of the start of the substring matched by I<n>-th subpattern, or undef if the subpattern did not match. Thus, after a match against C<$_>, C<$&> coincides with C<substr $_, $-[0], $+[0] - $-[0]>. Similarly, $I<n> coincides with C<substr $_, $-[n], $+[n] - $-[n]> if C<$-[n]> is defined, and $+ coincides with C<substr $_, $-[$#-], $+[$#-] - $-[$#-]>. One can use C<$#-> to find the last matched subgroup in the last successful match. Contrast with C<$#+>, the number of subgroups in the regular expression. Compare with C<@+>. This array holds the offsets of the beginnings of the last successful submatches in the currently active dynamic scope. C<$-[0]> is the offset into the string of the beginning of the entire match. The I<n>th element of this array holds the offset of the I<n>th submatch, so C<$-[1]> is the offset where C<$1> begins, C<$-[2]> the offset where C<$2> begins, and so on. After a match against some variable C<$var>: =over 5 =item C<$`> is the same as C<substr($var, 0, $-[0])> =item C<$&> is the same as C<substr($var, $-[0], $+[0] - $-[0])> =item C<$'> is the same as C<substr($var, $+[0])> =item C<$1> is the same as C<substr($var, $-[1], $+[1] - $-[1])> =item C<$2> is the same as C<substr($var, $-[2], $+[2] - $-[2])> =item C<$3> is the same as C<substr($var, $-[3], $+[3] - $-[3])> =back This variable was added in Perl 5.6. =item %LAST_MATCH_START =item %- X<%-> X<%LAST_MATCH_START> Similar to C<%+>, this variable allows access to the named capture groups in the last successful match in the currently active dynamic scope. To each capture group name found in the regular expression, it associates a reference to an array containing the list of values captured by all buffers with that name (should there be several of them), in the order where they appear. Here's an example: if ('1234' =~ /(?<A>1)(?<B>2)(?<A>3)(?<B>4)/) { foreach my $bufname (sort keys %-) { my $ary = $-{$bufname}; foreach my $idx (0..$#$ary) { print "\$-{$bufname}[$idx] : ", (defined($ary->[$idx]) ? "'$ary->[$idx]'" : "undef"), "\n"; } } } would print out: $-{A}[0] : '1' $-{A}[1] : '3' $-{B}[0] : '2' $-{B}[1] : '4' The keys of the C<%-> hash correspond to all buffer names found in the regular expression. The behaviour of C<%-> is implemented via the L<Tie::Hash::NamedCapture> module. B<Note:> C<%-> and C<%+> are tied views into a common internal hash associated with the last successful regular expression. Therefore mixing iterative access to them via C<each> may have unpredictable results. Likewise, if the last successful match changes, then the results may be surprising. This variable was added in Perl 5.10 This variable is read-only and dynamically-scoped. =item $LAST_REGEXP_CODE_RESULT =item $^R X<$^R> X<$LAST_REGEXP_CODE_RESULT> The result of evaluation of the last successful C<(?{ code })> regular expression assertion (see L<perlre>). May be written to. This variable was added in Perl 5.005. =item ${^RE_DEBUG_FLAGS} X<${^RE_DEBUG_FLAGS}> The current value of the regex debugging flags. Set to 0 for no debug output even when the C<re 'debug'> module is loaded. See L<re> for details. This variable was added in Perl 5.10. =item ${^RE_TRIE_MAXBUF} X<${^RE_TRIE_MAXBUF}> Controls how certain regex optimisations are applied and how much memory they utilize. This value by default is 65536 which corresponds to a 512kB temporary cache. Set this to a higher value to trade memory for speed when matching large alternations. Set it to a lower value if you want the optimisations to be as conservative of memory as possible but still occur, and set it to a negative value to prevent the optimisation and conserve the most memory. Under normal situations this variable should be of no interest to you. This variable was added in Perl 5.10. =back =head2 Variables related to filehandles Variables that depend on the currently selected filehandle may be set by calling an appropriate object method on the C<IO::Handle> object, although this is less efficient than using the regular built-in variables. (Summary lines below for this contain the word HANDLE.) First you must say use IO::Handle; after which you may use either method HANDLE EXPR or more safely, HANDLE->method(EXPR) Each method returns the old value of the C<IO::Handle> attribute. The methods each take an optional EXPR, which, if supplied, specifies the new value for the C<IO::Handle> attribute in question. If not supplied, most methods do nothing to the current value--except for C<autoflush()>, which will assume a 1 for you, just to be different. Because loading in the C<IO::Handle> class is an expensive operation, you should learn how to use the regular built-in variables. A few of these variables are considered "read-only". This means that if you try to assign to this variable, either directly or indirectly through a reference, you'll raise a run-time exception. You should be very careful when modifying the default values of most special variables described in this document. In most cases you want to localize these variables before changing them, since if you don't, the change may affect other modules which rely on the default values of the special variables that you have changed. This is one of the correct ways to read the whole file at once: open my $fh, "<", "foo" or die $!; local $/; # enable localized slurp mode my $content = <$fh>; close $fh; But the following code is quite bad: open my $fh, "<", "foo" or die $!; undef $/; # enable slurp mode my $content = <$fh>; close $fh; since some other module, may want to read data from some file in the default "line mode", so if the code we have just presented has been executed, the global value of C<$/> is now changed for any other code running inside the same Perl interpreter. Usually when a variable is localized you want to make sure that this change affects the shortest scope possible. So unless you are already inside some short C<{}> block, you should create one yourself. For example: my $content = ''; open my $fh, "<", "foo" or die $!; { local $/; $content = <$fh>; } close $fh; Here is an example of how your own code can go broken: for ( 1..3 ){ $\ = "\r\n"; nasty_break(); print "$_"; } sub nasty_break { $\ = "\f"; # do something with $_ } You probably expect this code to print the equivalent of "1\r\n2\r\n3\r\n" but instead you get: "1\f2\f3\f" Why? Because C<nasty_break()> modifies C<$\> without localizing it first. The value you set in C<nasty_break()> is still there when you return. The fix is to add C<local()> so the value doesn't leak out of C<nasty_break()>: local $\ = "\f"; It's easy to notice the problem in such a short example, but in more complicated code you are looking for trouble if you don't localize changes to the special variables. =over 8 =item $ARGV X<$ARGV> Contains the name of the current file when reading from C<< <> >>. =item @ARGV X<@ARGV> The array C<@ARGV> contains the command-line arguments intended for the script. C<$#ARGV> is generally the number of arguments minus one, because C<$ARGV[0]> is the first argument, I<not> the program's command name itself. See L</$0> for the command name. =item ARGV X<ARGV> The special filehandle that iterates over command-line filenames in C<@ARGV>. Usually written as the null filehandle in the angle operator C<< <> >>. Note that currently C<ARGV> only has its magical effect within the C<< <> >> operator; elsewhere it is just a plain filehandle corresponding to the last file opened by C<< <> >>. In particular, passing C<\*ARGV> as a parameter to a function that expects a filehandle may not cause your function to automatically read the contents of all the files in C<@ARGV>. =item ARGVOUT X<ARGVOUT> The special filehandle that points to the currently open output file when doing edit-in-place processing with B<-i>. Useful when you have to do a lot of inserting and don't want to keep modifying C<$_>. See L<perlrun> for the B<-i> switch. =item Handle->output_field_separator( EXPR ) =item $OUTPUT_FIELD_SEPARATOR =item $OFS =item $, X<$,> X<$OFS> X<$OUTPUT_FIELD_SEPARATOR> The output field separator for the print operator. If defined, this value is printed between each of print's arguments. Default is C<undef>. Mnemonic: what is printed when there is a "," in your print statement. =item HANDLE->input_line_number( EXPR ) =item $INPUT_LINE_NUMBER =item $NR =item $. X<$.> X<$NR> X<$INPUT_LINE_NUMBER> X<line number> Current line number for the last filehandle accessed. Each filehandle in Perl counts the number of lines that have been read from it. (Depending on the value of C<$/>, Perl's idea of what constitutes a line may not match yours.) When a line is read from a filehandle (via C<readline()> or C<< <> >>), or when C<tell()> or C<seek()> is called on it, C<$.> becomes an alias to the line counter for that filehandle. You can adjust the counter by assigning to C<$.>, but this will not actually move the seek pointer. I<Localizing C<$.> will not localize the filehandle's line count>. Instead, it will localize perl's notion of which filehandle C<$.> is currently aliased to. C<$.> is reset when the filehandle is closed, but B<not> when an open filehandle is reopened without an intervening C<close()>. For more details, see L<perlop/"IE<sol>O Operators">. Because C<< <> >> never does an explicit close, line numbers increase across C<ARGV> files (but see examples in L<perlfunc/eof>). You can also use C<< HANDLE->input_line_number(EXPR) >> to access the line counter for a given filehandle without having to worry about which handle you last accessed. Mnemonic: many programs use "." to mean the current line number. =item HANDLE->input_record_separator( EXPR ) =item $INPUT_RECORD_SEPARATOR =item $RS =item $/ X<$/> X<$RS> X<$INPUT_RECORD_SEPARATOR> The input record separator, newline by default. This influences Perl's idea of what a "line" is. Works like B<awk>'s RS variable, including treating empty lines as a terminator if set to the null string (an empty line cannot contain any spaces or tabs). You may set it to a multi-character string to match a multi-character terminator, or to C<undef> to read through the end of file. Setting it to C<"\n\n"> means something slightly different than setting to C<"">, if the file contains consecutive empty lines. Setting to C<""> will treat two or more consecutive empty lines as a single empty line. Setting to C<"\n\n"> will blindly assume that the next input character belongs to the next paragraph, even if it's a newline. local $/; # enable "slurp" mode local $_ = <FH>; # whole file now here s/\n[ \t]+/ /g; Remember: the value of C<$/> is a string, not a regex. B<awk> has to be better for something. :-) Setting C<$/> to a reference to an integer, scalar containing an integer, or scalar that's convertible to an integer will attempt to read records instead of lines, with the maximum record size being the referenced integer. So this: local $/ = \32768; # or \"32768", or \$var_containing_32768 open my $fh, "<", $myfile or die $!; local $_ = <$fh>; will read a record of no more than 32768 bytes from FILE. If you're not reading from a record-oriented file (or your OS doesn't have record-oriented files), then you'll likely get a full chunk of data with every read. If a record is larger than the record size you've set, you'll get the record back in pieces. Trying to set the record size to zero or less will cause reading in the (rest of the) whole file. On VMS only, record reads bypass PerlIO layers and any associated buffering,so you must not mix record and non-record reads on the same filehandle. Record mode mixes with line mode only when the same buffering layer is in use for both modes. If you perform a record read on a FILE with an encoding layer such as C<:encoding(latin1)> or C<:utf8>, you may get an invalid string as a result, may leave the FILE positioned between characters in the stream and may not be reading the number of bytes from the underlying file that you specified. This behaviour may change without warning in a future version of perl. See also L<perlport/"Newlines">. Also see L</$.>. Mnemonic: / delimits line boundaries when quoting poetry. =item Handle->output_record_separator( EXPR ) =item $OUTPUT_RECORD_SEPARATOR =item $ORS =item $\ X<$\> X<$ORS> X<$OUTPUT_RECORD_SEPARATOR> The output record separator for the print operator. If defined, this value is printed after the last of print's arguments. Default is C<undef>. Mnemonic: you set C<$\> instead of adding "\n" at the end of the print. Also, it's just like C<$/>, but it's what you get "back" from Perl. =item HANDLE->autoflush( EXPR ) =item $OUTPUT_AUTOFLUSH =item $| X<$|> X<autoflush> X<flush> X<$OUTPUT_AUTOFLUSH> If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Default is 0 (regardless of whether the channel is really buffered by the system or not; C<$|> tells you only whether you've asked Perl explicitly to flush after each write). STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe or socket, such as when you are running a Perl program under B<rsh> and want to see the output as it's happening. This has no effect on input buffering. See L<perlfunc/getc> for that. See L<perlfunc/select> on how to select the output channel. See also L<IO::Handle>. Mnemonic: when you want your pipes to be piping hot. =back =head3 Variables related to formats The special variables for formats are a subset of those for filehandles. See L<perlform> for more information about Perl's formats. =over 8 =item $ACCUMULATOR =item $^A X<$^A> X<$ACCUMULATOR> The current value of the C<write()> accumulator for C<format()> lines. A format contains C<formline()> calls that put their result into C<$^A>. After calling its format, C<write()> prints out the contents of C<$^A> and empties. So you never really see the contents of C<$^A> unless you call C<formline()> yourself and then look at it. See L<perlform> and L<perlfunc/"formline PICTURE,LIST">. =item HANDLE->format_formfeed(EXPR) =item $FORMAT_FORMFEED =item $^L X<$^L> X<$FORMAT_FORMFEED> What formats output as a form feed. The default is C<\f>. =item HANDLE->format_page_number(EXPR) =item $FORMAT_PAGE_NUMBER =item $% X<$%> X<$FORMAT_PAGE_NUMBER> The current page number of the currently selected output channel. Mnemonic: C<%> is page number in B<nroff>. =item HANDLE->format_lines_left(EXPR) =item $FORMAT_LINES_LEFT =item $- X<$-> X<$FORMAT_LINES_LEFT> The number of lines left on the page of the currently selected output channel. Mnemonic: lines_on_page - lines_printed. =item Handle->format_line_break_characters EXPR =item $FORMAT_LINE_BREAK_CHARACTERS =item $: X<$:> X<FORMAT_LINE_BREAK_CHARACTERS> The current set of characters after which a string may be broken to fill continuation fields (starting with C<^>) in a format. The default is S<" \n-">, to break on a space, newline, or a hyphen. Mnemonic: a "colon" in poetry is a part of a line. =item HANDLE->format_lines_per_page(EXPR) =item $FORMAT_LINES_PER_PAGE =item $= X<$=> X<$FORMAT_LINES_PER_PAGE> The current page length (printable lines) of the currently selected output channel. The default is 60. Mnemonic: = has horizontal lines. =item HANDLE->format_top_name(EXPR) =item $FORMAT_TOP_NAME =item $^ X<$^> X<$FORMAT_TOP_NAME> The name of the current top-of-page format for the currently selected output channel. The default is the name of the filehandle with C<_TOP> appended. For example, the default format top name for the C<STDOUT> filehandle is C<STDOUT_TOP>. Mnemonic: points to top of page. =item HANDLE->format_name(EXPR) =item $FORMAT_NAME =item $~ X<$~> X<$FORMAT_NAME> The name of the current report format for the currently selected output channel. The default format name is the same as the filehandle name. For example, the default format name for the C<STDOUT> filehandle is just C<STDOUT>. Mnemonic: brother to C<$^>. =back =head2 Error Variables X<error> X<exception> The variables C<$@>, C<$!>, C<$^E>, and C<$?> contain information about different types of error conditions that may appear during execution of a Perl program. The variables are shown ordered by the "distance" between the subsystem which reported the error and the Perl process. They correspond to errors detected by the Perl interpreter, C library, operating system, or an external program, respectively. To illustrate the differences between these variables, consider the following Perl expression, which uses a single-quoted string. After execution of this statement, perl may have set all four special error variables: eval q{ open my $pipe, "/cdrom/install |" or die $!; my @res = <$pipe>; close $pipe or die "bad pipe: $?, $!"; }; When perl executes the C<eval()> expression, it translates the C<open()>, C<< <PIPE> >>, and C<close> calls in the C run-time library and thence to the operating system kernel. perl sets C<$!> to the C library's C<errno> if one of these calls fails. C<$@> is set if the string to be C<eval>-ed did not compile (this may happen if C<open> or C<close> were imported with bad prototypes), or if Perl code executed during evaluation C<die()>d. In these cases the value of C<$@> is the compile error, or the argument to C<die> (which will interpolate C<$!> and C<$?>). (See also L<Fatal>, though.) Under a few operating systems, C<$^E> may contain a more verbose error indicator, such as in this case, "CDROM tray not closed." Systems that do not support extended error messages leave C<$^E> the same as C<$!>. Finally, C<$?> may be set to non-0 value if the external program F</cdrom/install> fails. The upper eight bits reflect specific error conditions encountered by the program (the program's C<exit()> value). The lower eight bits reflect mode of failure, like signal death and core dump information. See L<wait(2)> for details. In contrast to C<$!> and C<$^E>, which are set only if error condition is detected, the variable C<$?> is set on each C<wait> or pipe C<close>, overwriting the old value. This is more like C<$@>, which on every C<eval()> is always set on failure and cleared on success. For more details, see the individual descriptions at C<$@>, C<$!>, C<$^E>, and C<$?>. =over 8 =item ${^CHILD_ERROR_NATIVE} X<$^CHILD_ERROR_NATIVE> The native status returned by the last pipe close, backtick (C<``>) command, successful call to C<wait()> or C<waitpid()>, or from the C<system()> operator. On POSIX-like systems this value can be decoded with the WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WIFSTOPPED, WSTOPSIG and WIFCONTINUED functions provided by the L<POSIX> module. Under VMS this reflects the actual VMS exit status; i.e. it is the same as C<$?> when the pragma C<use vmsish 'status'> is in effect. This variable was added in Perl 5.8.9. =item $EXTENDED_OS_ERROR =item $^E X<$^E> X<$EXTENDED_OS_ERROR> Error information specific to the current operating system. At the moment, this differs from C<$!> under only VMS, OS/2, and Win32 (and for MacPerl). On all other platforms, C<$^E> is always just the same as C<$!>. Under VMS, C<$^E> provides the VMS status value from the last system error. This is more specific information about the last system error than that provided by C<$!>. This is particularly important when C<$!> is set to B<EVMSERR>. Under OS/2, C<$^E> is set to the error code of the last call to OS/2 API either via CRT, or directly from perl. Under Win32, C<$^E> always returns the last error information reported by the Win32 call C<GetLastError()> which describes the last error from within the Win32 API. Most Win32-specific code will report errors via C<$^E>. ANSI C and Unix-like calls set C<errno> and so most portable Perl code will report errors via C<$!>. Caveats mentioned in the description of C<$!> generally apply to C<$^E>, also. This variable was added in Perl 5.003. Mnemonic: Extra error explanation. =item $EXCEPTIONS_BEING_CAUGHT =item $^S X<$^S> X<$EXCEPTIONS_BEING_CAUGHT> Current state of the interpreter. $^S State --------- ------------------- undef Parsing module/eval true (1) Executing an eval false (0) Otherwise The first state may happen in C<$SIG{__DIE__}> and C<$SIG{__WARN__}> handlers. This variable was added in Perl 5.004. =item $WARNING =item $^W X<$^W> X<$WARNING> The current value of the warning switch, initially true if B<-w> was used, false otherwise, but directly modifiable. See also L<warnings>. Mnemonic: related to the B<-w> switch. =item ${^WARNING_BITS} X<${^WARNING_BITS}> The current set of warning checks enabled by the C<use warnings> pragma. It has the same scoping as the C<$^H> and C<%^H> variables. The exact values are considered internal to the L<warnings> pragma and may change between versions of Perl. This variable was added in Perl 5.6. =item $OS_ERROR =item $ERRNO =item $! X<$!> X<$ERRNO> X<$OS_ERROR> When referenced, C<$!> retrieves the current value of the C C<errno> integer variable. If C<$!> is assigned a numerical value, that value is stored in C<errno>. When referenced as a string, C<$!> yields the system error string corresponding to C<errno>. Many system or library calls set C<errno> if they fail, to indicate the cause of failure. They usually do B<not> set C<errno> to zero if they succeed. This means C<errno>, hence C<$!>, is meaningful only I<immediately> after a B<failure>: if (open my $fh, "<", $filename) { # Here $! is meaningless. ... } else { # ONLY here is $! meaningful. ... # Already here $! might be meaningless. } # Since here we might have either success or failure, # $! is meaningless. Here, I<meaningless> means that C<$!> may be unrelated to the outcome of the C<open()> operator. Assignment to C<$!> is similarly ephemeral. It can be used immediately before invoking the C<die()> operator, to set the exit value, or to inspect the system error string corresponding to error I<n>, or to restore C<$!> to a meaningful state. Mnemonic: What just went bang? =item %OS_ERROR =item %ERRNO =item %! X<%!> X<%OS_ERROR> X<%ERRNO> Each element of C<%!> has a true value only if C<$!> is set to that value. For example, C<$!{ENOENT}> is true if and only if the current value of C<$!> is C<ENOENT>; that is, if the most recent error was "No such file or directory" (or its moral equivalent: not all operating systems give that exact error, and certainly not all languages). To check if a particular key is meaningful on your system, use C<exists $!{the_key}>; for a list of legal keys, use C<keys %!>. See L<Errno> for more information, and also see L</$!>. This variable was added in Perl 5.005. =item $CHILD_ERROR =item $? X<$?> X<$CHILD_ERROR> The status returned by the last pipe close, backtick (C<``>) command, successful call to C<wait()> or C<waitpid()>, or from the C<system()> operator. This is just the 16-bit status word returned by the traditional Unix C<wait()> system call (or else is made up to look like it). Thus, the exit value of the subprocess is really (C<<< $? >> 8 >>>), and C<$? & 127> gives which signal, if any, the process died from, and C<$? & 128> reports whether there was a core dump. Additionally, if the C<h_errno> variable is supported in C, its value is returned via C<$?> if any C<gethost*()> function fails. If you have installed a signal handler for C<SIGCHLD>, the value of C<$?> will usually be wrong outside that handler. Inside an C<END> subroutine C<$?> contains the value that is going to be given to C<exit()>. You can modify C<$?> in an C<END> subroutine to change the exit status of your program. For example: END { $? = 1 if $? == 255; # die would make it 255 } Under VMS, the pragma C<use vmsish 'status'> makes C<$?> reflect the actual VMS exit status, instead of the default emulation of POSIX status; see L<perlvms/$?> for details. Mnemonic: similar to B<sh> and B<ksh>. =item $EVAL_ERROR =item $@ X<$@> X<$EVAL_ERROR> The Perl syntax error message from the last C<eval()> operator. If C<$@> is the null string, the last C<eval()> parsed and executed correctly (although the operations you invoked may have failed in the normal fashion). Warning messages are not collected in this variable. You can, however, set up a routine to process warnings by setting C<$SIG{__WARN__}> as described in L</%SIG>. Mnemonic: Where was the syntax error "at"? =back =head2 Variables related to the interpreter state These variables provide information about the current interpreter state. =over 8 =item $COMPILING =item $^C X<$^C> X<$COMPILING> The current value of the flag associated with the B<-c> switch. Mainly of use with B<-MO=...> to allow code to alter its behavior when being compiled, such as for example to C<AUTOLOAD> at compile time rather than normal, deferred loading. Setting C<$^C = 1> is similar to calling C<B::minus_c>. This variable was added in Perl 5.6. =item $DEBUGGING =item $^D X<$^D> X<$DEBUGGING> The current value of the debugging flags. May be read or set. Like its command-line equivalent, you can use numeric or symbolic values, eg C<$^D = 10> or C<$^D = "st">. Mnemonic: value of B<-D> switch. =item ${^ENCODING} X<${^ENCODING}> The I<object reference> to the C<Encode> object that is used to convert the source code to Unicode. Thanks to this variable your Perl script does not have to be written in UTF-8. Default is I<undef>. The direct manipulation of this variable is highly discouraged. This variable was added in Perl 5.8.2. =item ${^GLOBAL_PHASE} X<${^GLOBAL_PHASE}> The current phase of the perl interpreter. Possible values are: =over 8 =item CONSTRUCT The C<PerlInterpreter*> is being constructed via C<perl_construct>. This value is mostly there for completeness and for use via the underlying C variable C<PL_phase>. It's not really possible for Perl code to be executed unless construction of the interpreter is finished. =item START This is the global compile-time. That includes, basically, every C<BEGIN> block executed directly or indirectly from during the compile-time of the top-level program. This phase is not called "BEGIN" to avoid confusion with C<BEGIN>-blocks, as those are executed during compile-time of any compilation unit, not just the top-level program. A new, localised compile-time entered at run-time, for example by constructs as C<eval "use SomeModule"> are not global interpreter phases, and therefore aren't reflected by C<${^GLOBAL_PHASE}>. =item CHECK Execution of any C<CHECK> blocks. =item INIT Similar to "CHECK", but for C<INIT>-blocks, not C<CHECK> blocks. =item RUN The main run-time, i.e. the execution of C<PL_main_root>. =item END Execution of any C<END> blocks. =item DESTRUCT Global destruction. =back Also note that there's no value for UNITCHECK-blocks. That's because those are run for each compilation unit individually, and therefore is not a global interpreter phase. Not every program has to go through each of the possible phases, but transition from one phase to another can only happen in the order described in the above list. An example of all of the phases Perl code can see: BEGIN { print "compile-time: ${^GLOBAL_PHASE}\n" } INIT { print "init-time: ${^GLOBAL_PHASE}\n" } CHECK { print "check-time: ${^GLOBAL_PHASE}\n" } { package Print::Phase; sub new { my ($class, $time) = @_; return bless \$time, $class; } sub DESTROY { my $self = shift; print "$$self: ${^GLOBAL_PHASE}\n"; } } print "run-time: ${^GLOBAL_PHASE}\n"; my $runtime = Print::Phase->new( "lexical variables are garbage collected before END" ); END { print "end-time: ${^GLOBAL_PHASE}\n" } our $destruct = Print::Phase->new( "package variables are garbage collected after END" ); This will print out compile-time: START check-time: CHECK init-time: INIT run-time: RUN lexical variables are garbage collected before END: RUN end-time: END package variables are garbage collected after END: DESTRUCT This variable was added in Perl 5.14.0. =item $^H X<$^H> WARNING: This variable is strictly for internal use only. Its availability, behavior, and contents are subject to change without notice. This variable contains compile-time hints for the Perl interpreter. At the end of compilation of a BLOCK the value of this variable is restored to the value when the interpreter started to compile the BLOCK. When perl begins to parse any block construct that provides a lexical scope (e.g., eval body, required file, subroutine body, loop body, or conditional block), the existing value of C<$^H> is saved, but its value is left unchanged. When the compilation of the block is completed, it regains the saved value. Between the points where its value is saved and restored, code that executes within BEGIN blocks is free to change the value of C<$^H>. This behavior provides the semantic of lexical scoping, and is used in, for instance, the C<use strict> pragma. The contents should be an integer; different bits of it are used for different pragmatic flags. Here's an example: sub add_100 { $^H |= 0x100 } sub foo { BEGIN { add_100() } bar->baz($boon); } Consider what happens during execution of the BEGIN block. At this point the BEGIN block has already been compiled, but the body of C<foo()> is still being compiled. The new value of C<$^H> will therefore be visible only while the body of C<foo()> is being compiled. Substitution of C<BEGIN { add_100() }> block with: BEGIN { require strict; strict->import('vars') } demonstrates how C<use strict 'vars'> is implemented. Here's a conditional version of the same lexical pragma: BEGIN { require strict; strict->import('vars') if $condition } This variable was added in Perl 5.003. =item %^H X<%^H> The C<%^H> hash provides the same scoping semantic as C<$^H>. This makes it useful for implementation of lexically scoped pragmas. See L<perlpragma>. When putting items into C<%^H>, in order to avoid conflicting with other users of the hash there is a convention regarding which keys to use. A module should use only keys that begin with the module's name (the name of its main package) and a "/" character. For example, a module C<Foo::Bar> should use keys such as C<Foo::Bar/baz>. This variable was added in Perl 5.6. =item ${^OPEN} X<${^OPEN}> An internal variable used by PerlIO. A string in two parts, separated by a C<\0> byte, the first part describes the input layers, the second part describes the output layers. This variable was added in Perl 5.8.0. =item $PERLDB =item $^P X<$^P> X<$PERLDB> The internal variable for debugging support. The meanings of the various bits are subject to change, but currently indicate: =over 6 =item 0x01 Debug subroutine enter/exit. =item 0x02 Line-by-line debugging. Causes C<DB::DB()> subroutine to be called for each statement executed. Also causes saving source code lines (like 0x400). =item 0x04 Switch off optimizations. =item 0x08 Preserve more data for future interactive inspections. =item 0x10 Keep info about source lines on which a subroutine is defined. =item 0x20 Start with single-step on. =item 0x40 Use subroutine address instead of name when reporting. =item 0x80 Report C<goto &subroutine> as well. =item 0x100 Provide informative "file" names for evals based on the place they were compiled. =item 0x200 Provide informative names to anonymous subroutines based on the place they were compiled. =item 0x400 Save source code lines into C<@{"_<$filename"}>. =back Some bits may be relevant at compile-time only, some at run-time only. This is a new mechanism and the details may change. See also L<perldebguts>. =item ${^TAINT} X<${^TAINT}> Reflects if taint mode is on or off. 1 for on (the program was run with B<-T>), 0 for off, -1 when only taint warnings are enabled (i.e. with B<-t> or B<-TU>). This variable is read-only. This variable was added in Perl 5.8. =item ${^UNICODE} X<${^UNICODE}> Reflects certain Unicode settings of Perl. See L<perlrun> documentation for the C<-C> switch for more information about the possible values. This variable is set during Perl startup and is thereafter read-only. This variable was added in Perl 5.8.2. =item ${^UTF8CACHE} X<${^UTF8CACHE}> This variable controls the state of the internal UTF-8 offset caching code. 1 for on (the default), 0 for off, -1 to debug the caching code by checking all its results against linear scans, and panicking on any discrepancy. This variable was added in Perl 5.8.9. =item ${^UTF8LOCALE} X<${^UTF8LOCALE}> This variable indicates whether a UTF-8 locale was detected by perl at startup. This information is used by perl when it's in adjust-utf8ness-to-locale mode (as when run with the C<-CL> command-line switch); see L<perlrun> for more info on this. This variable was added in Perl 5.8.8. =back =head2 Deprecated and removed variables Deprecating a variable announces the intent of the perl maintainers to eventually remove the variable from the language. It may still be available despite its status. Using a deprecated variable triggers a warning. Once a variable is removed, its use triggers an error telling you the variable is unsupported. See L<perldiag> for details about error messages. =over 8 =item $OFMT =item $# X<$#> X<$OFMT> C<$#> was a variable that could be used to format printed numbers. After a deprecation cycle, its magic was removed in Perl 5.10 and using it now triggers a warning: C<$# is no longer supported>. This is not the sigil you use in front of an array name to get the last index, like C<$#array>. That's still how you get the last index of an array in Perl. The two have nothing to do with each other. Deprecated in Perl 5. Removed in Perl 5.10. =item $* X<$*> C<$*> was a variable that you could use to enable multiline matching. After a deprecation cycle, its magic was removed in Perl 5.10. Using it now triggers a warning: C<$* is no longer supported>. You should use the C</s> and C</m> regexp modifiers instead. Deprecated in Perl 5. Removed in Perl 5.10. =item $ARRAY_BASE =item $[ X<$[> X<$ARRAY_BASE> This variable stores the index of the first element in an array, and of the first character in a substring. The default is 0, but you could theoretically set it to 1 to make Perl behave more like B<awk> (or Fortran) when subscripting and when evaluating the index() and substr() functions. As of release 5 of Perl, assignment to C<$[> is treated as a compiler directive, and cannot influence the behavior of any other file. (That's why you can only assign compile-time constants to it.) Its use is highly discouraged. Prior to Perl 5.10, assignment to C<$[> could be seen from outer lexical scopes in the same file, unlike other compile-time directives (such as L<strict>). Using local() on it would bind its value strictly to a lexical block. Now it is always lexically scoped. As of Perl 5.16, it is implemented by the L<arybase> module. See L<arybase> for more details on its behaviour. Under C<use v5.16>, or C<no feature "array_base">, C<$[> no longer has any effect, and always contains 0. Assigning 0 to it is permitted, but any other value will produce an error. Mnemonic: [ begins subscripts. Deprecated in Perl 5.12. =item $OLD_PERL_VERSION =item $] X<$]> X<$OLD_PERL_VERSION> See L</$^V> for a more modern representation of the Perl version that allows accurate string comparisons. The version + patchlevel / 1000 of the Perl interpreter. This variable can be used to determine whether the Perl interpreter executing a script is in the right range of versions: warn "No checksumming!\n" if $] < 3.019; The floating point representation can sometimes lead to inaccurate numeric comparisons. See also the documentation of C<use VERSION> and C<require VERSION> for a convenient way to fail if the running Perl interpreter is too old. Mnemonic: Is this version of perl in the right bracket? =back =cut PK PU�\�>dK K perlaix.podnu �[��� If you read this file _as_is_, just ignore the funny characters you see. It is written in the POD format (see pod/perlpod.pod) which is specially designed to be readable as is. =head1 NAME perlaix - Perl version 5 on IBM AIX (UNIX) systems =head1 DESCRIPTION This document describes various features of IBM's UNIX operating system AIX that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs. =head2 Compiling Perl 5 on AIX For information on compilers on older versions of AIX, see L<Compiling Perl 5 on older AIX versions up to 4.3.3>. When compiling Perl, you must use an ANSI C compiler. AIX does not ship an ANSI compliant C compiler with AIX by default, but binary builds of gcc for AIX are widely available. A version of gcc is also included in the AIX Toolbox which is shipped with AIX. =head2 Supported Compilers Currently all versions of IBM's "xlc", "xlc_r", "cc", "cc_r" or "vac" ANSI/C compiler will work for building Perl if that compiler works on your system. If you plan to link Perl to any module that requires thread-support, like DBD::Oracle, it is better to use the _r version of the compiler. This will not build a threaded Perl, but a thread-enabled Perl. See also L<Threaded Perl> later on. As of writing (2010-09) only the I<IBM XL C for AIX> or I<IBM XL C/C++ for AIX> compiler is supported by IBM on AIX 5L/6.1/7.1. The following compiler versions are currently supported by IBM: IBM XL C and IBM XL C/C++ V8, V9, V10, V11 The XL C for AIX is integrated in the XL C/C++ for AIX compiler and therefore also supported. If you choose XL C/C++ V9 you need APAR IZ35785 installed otherwise the integrated SDBM_File do not compile correctly due to an optimization bug. You can circumvent this problem by adding -qipa to the optimization flags (-Doptimize='-O -qipa'). The PTF for APAR IZ35785 which solves this problem is available from IBM (April 2009 PTF for XL C/C++ Enterprise Edition for AIX, V9.0). If you choose XL C/C++ V11 you need the April 2010 PTF (or newer) installed otherwise you will not get a working Perl version. Perl can be compiled with either IBM's ANSI C compiler or with gcc. The former is recommended, as not only it can compile Perl with no difficulty, but also can take advantage of features listed later that require the use of IBM compiler-specific command-line flags. If you decide to use gcc, make sure your installation is recent and complete, and be sure to read the Perl INSTALL file for more gcc-specific details. Please report any hoops you had to jump through to the development team. =head2 Incompatibility with AIX Toolbox lib gdbm If the AIX Toolbox version of lib gdbm < 1.8.3-5 is installed on your system then Perl will not work. This library contains the header files /opt/freeware/include/gdbm/dbm.h|ndbm.h which conflict with the AIX system versions. The lib gdbm will be automatically removed from the wanted libraries if the presence of one of these two header files is detected. If you want to build Perl with GDBM support then please install at least gdbm-devel-1.8.3-5 (or higher). =head2 Perl 5 was successfully compiled and tested on: Perl | AIX Level | Compiler Level | w th | w/o th -------+---------------------+-------------------------+------+------- 5.12.2 |5.1 TL9 32 bit | XL C/C++ V7 | OK | OK 5.12.2 |5.1 TL9 64 bit | XL C/C++ V7 | OK | OK 5.12.2 |5.2 TL10 SP8 32 bit | XL C/C++ V8 | OK | OK 5.12.2 |5.2 TL10 SP8 32 bit | gcc 3.2.2 | OK | OK 5.12.2 |5.2 TL10 SP8 64 bit | XL C/C++ V8 | OK | OK 5.12.2 |5.3 TL8 SP8 32 bit | XL C/C++ V9 + IZ35785 | OK | OK 5.12.2 |5.3 TL8 SP8 32 bit | gcc 4.2.4 | OK | OK 5.12.2 |5.3 TL8 SP8 64 bit | XL C/C++ V9 + IZ35785 | OK | OK 5.12.2 |5.3 TL10 SP3 32 bit | XL C/C++ V11 + Apr 2010 | OK | OK 5.12.2 |5.3 TL10 SP3 64 bit | XL C/C++ V11 + Apr 2010 | OK | OK 5.12.2 |6.1 TL1 SP7 32 bit | XL C/C++ V10 | OK | OK 5.12.2 |6.1 TL1 SP7 64 bit | XL C/C++ V10 | OK | OK 5.13 |7.1 TL0 SP1 32 bit | XL C/C++ V11 + Jul 2010 | OK | OK 5.13 |7.1 TL0 SP1 64 bit | XL C/C++ V11 + Jul 2010 | OK | OK w th = with thread support w/o th = without thread support OK = tested Successfully tested means that all "make test" runs finish with a result of 100% OK. All tests were conducted with -Duseshrplib set. All tests were conducted on the oldest supported AIX technology level with the latest support package applied. If the tested AIX version is out of support (AIX 4.3.3, 5.1, 5.2) then the last available support level was used. =head2 Building Dynamic Extensions on AIX Starting from Perl 5.7.2 (and consequently 5.8.x / 5.10.x / 5.12.x) and AIX 4.3 or newer Perl uses the AIX native dynamic loading interface in the so called runtime linking mode instead of the emulated interface that was used in Perl releases 5.6.1 and earlier or, for AIX releases 4.2 and earlier. This change does break backward compatibility with compiled modules from earlier Perl releases. The change was made to make Perl more compliant with other applications like Apache/mod_perl which are using the AIX native interface. This change also enables the use of C++ code with static constructors and destructors in Perl extensions, which was not possible using the emulated interface. It is highly recommended to use the new interface. =head2 Using Large Files with Perl Should yield no problems. =head2 Threaded Perl Should yield no problems with AIX 5.1 / 5.2 / 5.3 / 6.1 / 7.1. IBM uses the AIX system Perl (V5.6.0 on AIX 5.1 and V5.8.2 on AIX 5.2 / 5.3 and 6.1; V5.8.8 on AIX 5.3 TL11 and AIX 6.1 TL4; V5.10.1 on AIX 7.1) for some AIX system scripts. If you switch the links in /usr/bin from the AIX system Perl (/usr/opt/perl5) to the newly build Perl then you get the same features as with the IBM AIX system Perl if the threaded options are used. The threaded Perl build works also on AIX 5.1 but the IBM Perl build (Perl v5.6.0) is not threaded on AIX 5.1. Perl 5.12 an newer is not compatible with the IBM fileset perl.libext. =head2 64-bit Perl If your AIX system is installed with 64-bit support, you can expect 64-bit configurations to work. If you want to use 64-bit Perl on AIX 6.1 you need an APAR for a libc.a bug which affects (n)dbm_XXX functions. The APAR number for this problem is IZ39077. If you need more memory (larger data segment) for your Perl programs you can set: /etc/security/limits default: (or your user) data = -1 (default is 262144 * 512 byte) With the default setting the size is limited to 128MB. The -1 removes this limit. If the "make test" fails please change your /etc/security/limits as stated above. =head2 Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (threaded/32-bit) With the following options you get a threaded Perl version which passes all make tests in threaded 32-bit mode, which is the default configuration for the Perl builds that AIX ships with. rm config.sh ./Configure \ -d \ -Dcc=cc_r \ -Duseshrplib \ -Dusethreads \ -Dprefix=/usr/opt/perl5_32 The -Dprefix option will install Perl in a directory parallel to the IBM AIX system Perl installation. =head2 Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (32-bit) With the following options you get a Perl version which passes all make tests in 32-bit mode. rm config.sh ./Configure \ -d \ -Dcc=cc_r \ -Duseshrplib \ -Dprefix=/usr/opt/perl5_32 The -Dprefix option will install Perl in a directory parallel to the IBM AIX system Perl installation. =head2 Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (threaded/64-bit) With the following options you get a threaded Perl version which passes all make tests in 64-bit mode. export OBJECT_MODE=64 / setenv OBJECT_MODE 64 (depending on your shell) rm config.sh ./Configure \ -d \ -Dcc=cc_r \ -Duseshrplib \ -Dusethreads \ -Duse64bitall \ -Dprefix=/usr/opt/perl5_64 =head2 Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (64-bit) With the following options you get a Perl version which passes all make tests in 64-bit mode. export OBJECT_MODE=64 / setenv OBJECT_MODE 64 (depending on your shell) rm config.sh ./Configure \ -d \ -Dcc=cc_r \ -Duseshrplib \ -Duse64bitall \ -Dprefix=/usr/opt/perl5_64 The -Dprefix option will install Perl in a directory parallel to the IBM AIX system Perl installation. If you choose gcc to compile 64-bit Perl then you need to add the following option: -Dcc='gcc -maix64' =head2 Compiling Perl 5 on older AIX versions up to 4.3.3 Due to the fact that AIX 4.3.3 reached end-of-service in December 31, 2003 this information is provided as is. The Perl versions prior to Perl 5.8.9 could be compiled on AIX up to 4.3.3 with the following settings (your mileage may vary): When compiling Perl, you must use an ANSI C compiler. AIX does not ship an ANSI compliant C-compiler with AIX by default, but binary builds of gcc for AIX are widely available. At the moment of writing, AIX supports two different native C compilers, for which you have to pay: B<xlC> and B<vac>. If you decide to use either of these two (which is quite a lot easier than using gcc), be sure to upgrade to the latest available patch level. Currently: xlC.C 3.1.4.10 or 3.6.6.0 or 4.0.2.2 or 5.0.2.9 or 6.0.0.3 vac.C 4.4.0.3 or 5.0.2.6 or 6.0.0.1 note that xlC has the OS version in the name as of version 4.0.2.0, so you will find xlC.C for AIX-5.0 as package xlC.aix50.rte 5.0.2.0 or 6.0.0.3 subversions are not the same "latest" on all OS versions. For example, the latest xlC-5 on aix41 is 5.0.2.9, while on aix43, it is 5.0.2.7. Perl can be compiled with either IBM's ANSI C compiler or with gcc. The former is recommended, as not only can it compile Perl with no difficulty, but also can take advantage of features listed later that require the use of IBM compiler-specific command-line flags. The IBM's compiler patch levels 5.0.0.0 and 5.0.1.0 have compiler optimization bugs that affect compiling perl.c and regcomp.c, respectively. If Perl's configuration detects those compiler patch levels, optimization is turned off for the said source code files. Upgrading to at least 5.0.2.0 is recommended. If you decide to use gcc, make sure your installation is recent and complete, and be sure to read the Perl INSTALL file for more gcc-specific details. Please report any hoops you had to jump through to the development team. =head2 OS level Before installing the patches to the IBM C-compiler you need to know the level of patching for the Operating System. IBM's command 'oslevel' will show the base, but is not always complete (in this example oslevel shows 4.3.NULL, whereas the system might run most of 4.3.THREE): # oslevel 4.3.0.0 # lslpp -l | grep 'bos.rte ' bos.rte 4.3.3.75 COMMITTED Base Operating System Runtime bos.rte 4.3.2.0 COMMITTED Base Operating System Runtime # The same might happen to AIX 5.1 or other OS levels. As a side note, Perl cannot be built without bos.adt.syscalls and bos.adt.libm installed # lslpp -l | egrep "syscalls|libm" bos.adt.libm 5.1.0.25 COMMITTED Base Application Development bos.adt.syscalls 5.1.0.36 COMMITTED System Calls Application # =head2 Building Dynamic Extensions on AIX E<lt> 5L AIX supports dynamically loadable objects as well as shared libraries. Shared libraries by convention end with the suffix .a, which is a bit misleading, as an archive can contain static as well as dynamic members. For Perl dynamically loaded objects we use the .so suffix also used on many other platforms. Note that starting from Perl 5.7.2 (and consequently 5.8.0) and AIX 4.3 or newer Perl uses the AIX native dynamic loading interface in the so called runtime linking mode instead of the emulated interface that was used in Perl releases 5.6.1 and earlier or, for AIX releases 4.2 and earlier. This change does break backward compatibility with compiled modules from earlier Perl releases. The change was made to make Perl more compliant with other applications like Apache/mod_perl which are using the AIX native interface. This change also enables the use of C++ code with static constructors and destructors in Perl extensions, which was not possible using the emulated interface. =head2 The IBM ANSI C Compiler All defaults for Configure can be used. If you've chosen to use vac 4, be sure to run 4.4.0.3. Older versions will turn up nasty later on. For vac 5 be sure to run at least 5.0.1.0, but vac 5.0.2.6 or up is highly recommended. Note that since IBM has removed vac 5.0.2.1 through 5.0.2.5 from the software depot, these versions should be considered obsolete. Here's a brief lead of how to upgrade the compiler to the latest level. Of course this is subject to changes. You can only upgrade versions from ftp-available updates if the first three digit groups are the same (in where you can skip intermediate unlike the patches in the developer snapshots of Perl), or to one version up where the "base" is available. In other words, the AIX compiler patches are cumulative. vac.C.4.4.0.1 => vac.C.4.4.0.3 is OK (vac.C.4.4.0.2 not needed) xlC.C.3.1.3.3 => xlC.C.3.1.4.10 is NOT OK (xlC.C.3.1.4.0 is not available) # ftp ftp.software.ibm.com Connected to service.boulder.ibm.com. : welcome message ... Name (ftp.software.ibm.com:merijn): anonymous 331 Guest login ok, send your complete e-mail address as password. Password: ... accepted login stuff ftp> cd /aix/fixes/v4/ ftp> dir other other.ll output to local-file: other.ll? y 200 PORT command successful. 150 Opening ASCII mode data connection for /bin/ls. 226 Transfer complete. ftp> dir xlc xlc.ll output to local-file: xlc.ll? y 200 PORT command successful. 150 Opening ASCII mode data connection for /bin/ls. 226 Transfer complete. ftp> bye ... goodbye messages # ls -l *.ll -rw-rw-rw- 1 merijn system 1169432 Nov 2 17:29 other.ll -rw-rw-rw- 1 merijn system 29170 Nov 2 17:29 xlc.ll On AIX 4.2 using xlC, we continue: # lslpp -l | fgrep 'xlC.C ' xlC.C 3.1.4.9 COMMITTED C for AIX Compiler xlC.C 3.1.4.0 COMMITTED C for AIX Compiler # grep 'xlC.C.3.1.4.*.bff' xlc.ll -rw-r--r-- 1 45776101 1 6286336 Jul 22 1996 xlC.C.3.1.4.1.bff -rw-rw-r-- 1 45776101 1 6173696 Aug 24 1998 xlC.C.3.1.4.10.bff -rw-r--r-- 1 45776101 1 6319104 Aug 14 1996 xlC.C.3.1.4.2.bff -rw-r--r-- 1 45776101 1 6316032 Oct 21 1996 xlC.C.3.1.4.3.bff -rw-r--r-- 1 45776101 1 6315008 Dec 20 1996 xlC.C.3.1.4.4.bff -rw-rw-r-- 1 45776101 1 6178816 Mar 28 1997 xlC.C.3.1.4.5.bff -rw-rw-r-- 1 45776101 1 6188032 May 22 1997 xlC.C.3.1.4.6.bff -rw-rw-r-- 1 45776101 1 6191104 Sep 5 1997 xlC.C.3.1.4.7.bff -rw-rw-r-- 1 45776101 1 6185984 Jan 13 1998 xlC.C.3.1.4.8.bff -rw-rw-r-- 1 45776101 1 6169600 May 27 1998 xlC.C.3.1.4.9.bff # wget ftp://ftp.software.ibm.com/aix/fixes/v4/xlc/xlC.C.3.1.4.10.bff # On AIX 4.3 using vac, we continue: # lslpp -l | grep 'vac.C ' vac.C 5.0.2.2 COMMITTED C for AIX Compiler vac.C 5.0.2.0 COMMITTED C for AIX Compiler # grep 'vac.C.5.0.2.*.bff' other.ll -rw-rw-r-- 1 45776101 1 13592576 Apr 16 2001 vac.C.5.0.2.0.bff -rw-rw-r-- 1 45776101 1 14133248 Apr 9 2002 vac.C.5.0.2.3.bff -rw-rw-r-- 1 45776101 1 14173184 May 20 2002 vac.C.5.0.2.4.bff -rw-rw-r-- 1 45776101 1 14192640 Nov 22 2002 vac.C.5.0.2.6.bff # wget ftp://ftp.software.ibm.com/aix/fixes/v4/other/vac.C.5.0.2.6.bff # Likewise on all other OS levels. Then execute the following command, and fill in its choices # smit install_update -> Install and Update from LATEST Available Software * INPUT device / directory for software [ vac.C.5.0.2.6.bff ] [ OK ] [ OK ] Follow the messages ... and you're done. If you like a more web-like approach, a good start point can be http://www14.software.ibm.com/webapp/download/downloadaz.jsp and click "C for AIX", and follow the instructions. =head2 The usenm option If linking miniperl cc -o miniperl ... miniperlmain.o opmini.o perl.o ... -lm -lc ... causes error like this ld: 0711-317 ERROR: Undefined symbol: .aintl ld: 0711-317 ERROR: Undefined symbol: .copysignl ld: 0711-317 ERROR: Undefined symbol: .syscall ld: 0711-317 ERROR: Undefined symbol: .eaccess ld: 0711-317 ERROR: Undefined symbol: .setresuid ld: 0711-317 ERROR: Undefined symbol: .setresgid ld: 0711-317 ERROR: Undefined symbol: .setproctitle ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information. you could retry with make realclean rm config.sh ./Configure -Dusenm ... which makes Configure to use the C<nm> tool when scanning for library symbols, which usually is not done in AIX. Related to this, you probably should not use the C<-r> option of Configure in AIX, because that affects of how the C<nm> tool is used. =head2 Using GNU's gcc for building Perl Using gcc-3.x (tested with 3.0.4, 3.1, and 3.2) now works out of the box, as do recent gcc-2.9 builds available directly from IBM as part of their Linux compatibility packages, available here: http://www.ibm.com/servers/aix/products/aixos/linux/ =head2 Using Large Files with Perl E<lt> 5L Should yield no problems. =head2 Threaded Perl E<lt> 5L Threads seem to work OK, though at the moment not all tests pass when threads are used in combination with 64-bit configurations. You may get a warning when doing a threaded build: "pp_sys.c", line 4640.39: 1506-280 (W) Function argument assignment between types "unsigned char*" and "const void*" is not allowed. The exact line number may vary, but if the warning (W) comes from a line line this hent = PerlSock_gethostbyaddr(addr, (Netdb_hlen_t) addrlen, addrtype); in the "pp_ghostent" function, you may ignore it safely. The warning is caused by the reentrant variant of gethostbyaddr() having a slightly different prototype than its non-reentrant variant, but the difference is not really significant here. =head2 64-bit Perl E<lt> 5L If your AIX is installed with 64-bit support, you can expect 64-bit configurations to work. In combination with threads some tests might still fail. =head2 AIX 4.2 and extensions using C++ with statics In AIX 4.2 Perl extensions that use C++ functions that use statics may have problems in that the statics are not getting initialized. In newer AIX releases this has been solved by linking Perl with the libC_r library, but unfortunately in AIX 4.2 the said library has an obscure bug where the various functions related to time (such as time() and gettimeofday()) return broken values, and therefore in AIX 4.2 Perl is not linked against the libC_r. =head1 AUTHORS Rainer Tammer <tammer@tammer.net> =cut PK PU�\8��� �� perlreguts.podnu �[��� =head1 NAME perlreguts - Description of the Perl regular expression engine. =head1 DESCRIPTION This document is an attempt to shine some light on the guts of the regex engine and how it works. The regex engine represents a significant chunk of the perl codebase, but is relatively poorly understood. This document is a meagre attempt at addressing this situation. It is derived from the author's experience, comments in the source code, other papers on the regex engine, feedback on the perl5-porters mail list, and no doubt other places as well. B<NOTICE!> It should be clearly understood that the behavior and structures discussed in this represents the state of the engine as the author understood it at the time of writing. It is B<NOT> an API definition, it is purely an internals guide for those who want to hack the regex engine, or understand how the regex engine works. Readers of this document are expected to understand perl's regex syntax and its usage in detail. If you want to learn about the basics of Perl's regular expressions, see L<perlre>. And if you want to replace the regex engine with your own, see L<perlreapi>. =head1 OVERVIEW =head2 A quick note on terms There is some debate as to whether to say "regexp" or "regex". In this document we will use the term "regex" unless there is a special reason not to, in which case we will explain why. When speaking about regexes we need to distinguish between their source code form and their internal form. In this document we will use the term "pattern" when we speak of their textual, source code form, and the term "program" when we speak of their internal representation. These correspond to the terms I<S-regex> and I<B-regex> that Mark Jason Dominus employs in his paper on "Rx" ([1] in L</REFERENCES>). =head2 What is a regular expression engine? A regular expression engine is a program that takes a set of constraints specified in a mini-language, and then applies those constraints to a target string, and determines whether or not the string satisfies the constraints. See L<perlre> for a full definition of the language. In less grandiose terms, the first part of the job is to turn a pattern into something the computer can efficiently use to find the matching point in the string, and the second part is performing the search itself. To do this we need to produce a program by parsing the text. We then need to execute the program to find the point in the string that matches. And we need to do the whole thing efficiently. =head2 Structure of a Regexp Program =head3 High Level Although it is a bit confusing and some people object to the terminology, it is worth taking a look at a comment that has been in F<regexp.h> for years: I<This is essentially a linear encoding of a nondeterministic finite-state machine (aka syntax charts or "railroad normal form" in parsing technology).> The term "railroad normal form" is a bit esoteric, with "syntax diagram/charts", or "railroad diagram/charts" being more common terms. Nevertheless it provides a useful mental image of a regex program: each node can be thought of as a unit of track, with a single entry and in most cases a single exit point (there are pieces of track that fork, but statistically not many), and the whole forms a layout with a single entry and single exit point. The matching process can be thought of as a car that moves along the track, with the particular route through the system being determined by the character read at each possible connector point. A car can fall off the track at any point but it may only proceed as long as it matches the track. Thus the pattern C</foo(?:\w+|\d+|\s+)bar/> can be thought of as the following chart: [start] | <foo> | +-----+-----+ | | | <\w+> <\d+> <\s+> | | | +-----+-----+ | <bar> | [end] The truth of the matter is that perl's regular expressions these days are much more complex than this kind of structure, but visualising it this way can help when trying to get your bearings, and it matches the current implementation pretty closely. To be more precise, we will say that a regex program is an encoding of a graph. Each node in the graph corresponds to part of the original regex pattern, such as a literal string or a branch, and has a pointer to the nodes representing the next component to be matched. Since "node" and "opcode" already have other meanings in the perl source, we will call the nodes in a regex program "regops". The program is represented by an array of C<regnode> structures, one or more of which represent a single regop of the program. Struct C<regnode> is the smallest struct needed, and has a field structure which is shared with all the other larger structures. The "next" pointers of all regops except C<BRANCH> implement concatenation; a "next" pointer with a C<BRANCH> on both ends of it is connecting two alternatives. [Here we have one of the subtle syntax dependencies: an individual C<BRANCH> (as opposed to a collection of them) is never concatenated with anything because of operator precedence.] The operand of some types of regop is a literal string; for others, it is a regop leading into a sub-program. In particular, the operand of a C<BRANCH> node is the first regop of the branch. B<NOTE>: As the railroad metaphor suggests, this is B<not> a tree structure: the tail of the branch connects to the thing following the set of C<BRANCH>es. It is a like a single line of railway track that splits as it goes into a station or railway yard and rejoins as it comes out the other side. =head3 Regops The base structure of a regop is defined in F<regexp.h> as follows: struct regnode { U8 flags; /* Various purposes, sometimes overridden */ U8 type; /* Opcode value as specified by regnodes.h */ U16 next_off; /* Offset in size regnode */ }; Other larger C<regnode>-like structures are defined in F<regcomp.h>. They are almost like subclasses in that they have the same fields as C<regnode>, with possibly additional fields following in the structure, and in some cases the specific meaning (and name) of some of base fields are overridden. The following is a more complete description. =over 4 =item C<regnode_1> =item C<regnode_2> C<regnode_1> structures have the same header, followed by a single four-byte argument; C<regnode_2> structures contain two two-byte arguments instead: regnode_1 U32 arg1; regnode_2 U16 arg1; U16 arg2; =item C<regnode_string> C<regnode_string> structures, used for literal strings, follow the header with a one-byte length and then the string data. Strings are padded on the end with zero bytes so that the total length of the node is a multiple of four bytes: regnode_string char string[1]; U8 str_len; /* overrides flags */ =item C<regnode_charclass> Character classes are represented by C<regnode_charclass> structures, which have a four-byte argument and then a 32-byte (256-bit) bitmap indicating which characters are included in the class. regnode_charclass U32 arg1; char bitmap[ANYOF_BITMAP_SIZE]; =item C<regnode_charclass_class> There is also a larger form of a char class structure used to represent POSIX char classes called C<regnode_charclass_class> which has an additional 4-byte (32-bit) bitmap indicating which POSIX char classes have been included. regnode_charclass_class U32 arg1; char bitmap[ANYOF_BITMAP_SIZE]; char classflags[ANYOF_CLASSBITMAP_SIZE]; =back F<regnodes.h> defines an array called C<regarglen[]> which gives the size of each opcode in units of C<size regnode> (4-byte). A macro is used to calculate the size of an C<EXACT> node based on its C<str_len> field. The regops are defined in F<regnodes.h> which is generated from F<regcomp.sym> by F<regcomp.pl>. Currently the maximum possible number of distinct regops is restricted to 256, with about a quarter already used. A set of macros makes accessing the fields easier and more consistent. These include C<OP()>, which is used to determine the type of a C<regnode>-like structure; C<NEXT_OFF()>, which is the offset to the next node (more on this later); C<ARG()>, C<ARG1()>, C<ARG2()>, C<ARG_SET()>, and equivalents for reading and setting the arguments; and C<STR_LEN()>, C<STRING()> and C<OPERAND()> for manipulating strings and regop bearing types. =head3 What regop is next? There are three distinct concepts of "next" in the regex engine, and it is important to keep them clear. =over 4 =item * There is the "next regnode" from a given regnode, a value which is rarely useful except that sometimes it matches up in terms of value with one of the others, and that sometimes the code assumes this to always be so. =item * There is the "next regop" from a given regop/regnode. This is the regop physically located after the current one, as determined by the size of the current regop. This is often useful, such as when dumping the structure we use this order to traverse. Sometimes the code assumes that the "next regnode" is the same as the "next regop", or in other words assumes that the sizeof a given regop type is always going to be one regnode large. =item * There is the "regnext" from a given regop. This is the regop which is reached by jumping forward by the value of C<NEXT_OFF()>, or in a few cases for longer jumps by the C<arg1> field of the C<regnode_1> structure. The subroutine C<regnext()> handles this transparently. This is the logical successor of the node, which in some cases, like that of the C<BRANCH> regop, has special meaning. =back =head1 Process Overview Broadly speaking, performing a match of a string against a pattern involves the following steps: =over 5 =item A. Compilation =over 5 =item 1. Parsing for size =item 2. Parsing for construction =item 3. Peep-hole optimisation and analysis =back =item B. Execution =over 5 =item 4. Start position and no-match optimisations =item 5. Program execution =back =back Where these steps occur in the actual execution of a perl program is determined by whether the pattern involves interpolating any string variables. If interpolation occurs, then compilation happens at run time. If it does not, then compilation is performed at compile time. (The C</o> modifier changes this, as does C<qr//> to a certain extent.) The engine doesn't really care that much. =head2 Compilation This code resides primarily in F<regcomp.c>, along with the header files F<regcomp.h>, F<regexp.h> and F<regnodes.h>. Compilation starts with C<pregcomp()>, which is mostly an initialisation wrapper which farms work out to two other routines for the heavy lifting: the first is C<reg()>, which is the start point for parsing; the second, C<study_chunk()>, is responsible for optimisation. Initialisation in C<pregcomp()> mostly involves the creation and data-filling of a special structure, C<RExC_state_t> (defined in F<regcomp.c>). Almost all internally-used routines in F<regcomp.h> take a pointer to one of these structures as their first argument, with the name C<pRExC_state>. This structure is used to store the compilation state and contains many fields. Likewise there are many macros which operate on this variable: anything that looks like C<RExC_xxxx> is a macro that operates on this pointer/structure. =head3 Parsing for size In this pass the input pattern is parsed in order to calculate how much space is needed for each regop we would need to emit. The size is also used to determine whether long jumps will be required in the program. This stage is controlled by the macro C<SIZE_ONLY> being set. The parse proceeds pretty much exactly as it does during the construction phase, except that most routines are short-circuited to change the size field C<RExC_size> and not do anything else. =head3 Parsing for construction Once the size of the program has been determined, the pattern is parsed again, but this time for real. Now C<SIZE_ONLY> will be false, and the actual construction can occur. C<reg()> is the start of the parse process. It is responsible for parsing an arbitrary chunk of pattern up to either the end of the string, or the first closing parenthesis it encounters in the pattern. This means it can be used to parse the top-level regex, or any section inside of a grouping parenthesis. It also handles the "special parens" that perl's regexes have. For instance when parsing C</x(?:foo)y/> C<reg()> will at one point be called to parse from the "?" symbol up to and including the ")". Additionally, C<reg()> is responsible for parsing the one or more branches from the pattern, and for "finishing them off" by correctly setting their next pointers. In order to do the parsing, it repeatedly calls out to C<regbranch()>, which is responsible for handling up to the first C<|> symbol it sees. C<regbranch()> in turn calls C<regpiece()> which handles "things" followed by a quantifier. In order to parse the "things", C<regatom()> is called. This is the lowest level routine, which parses out constant strings, character classes, and the various special symbols like C<$>. If C<regatom()> encounters a "(" character it in turn calls C<reg()>. The routine C<regtail()> is called by both C<reg()> and C<regbranch()> in order to "set the tail pointer" correctly. When executing and we get to the end of a branch, we need to go to the node following the grouping parens. When parsing, however, we don't know where the end will be until we get there, so when we do we must go back and update the offsets as appropriate. C<regtail> is used to make this easier. A subtlety of the parsing process means that a regex like C</foo/> is originally parsed into an alternation with a single branch. It is only afterwards that the optimiser converts single branch alternations into the simpler form. =head3 Parse Call Graph and a Grammar The call graph looks like this: reg() # parse a top level regex, or inside of parens regbranch() # parse a single branch of an alternation regpiece() # parse a pattern followed by a quantifier regatom() # parse a simple pattern regclass() # used to handle a class reg() # used to handle a parenthesised subpattern .... ... regtail() # finish off the branch ... regtail() # finish off the branch sequence. Tie each # branch's tail to the tail of the sequence # (NEW) In Debug mode this is # regtail_study(). A grammar form might be something like this: atom : constant | class quant : '*' | '+' | '?' | '{min,max}' _branch: piece | piece _branch | nothing branch: _branch | _branch '|' branch group : '(' branch ')' _piece: atom | group piece : _piece | _piece quant =head3 Debug Output In the 5.9.x development version of perl you can C<< use re Debug => 'PARSE' >> to see some trace information about the parse process. We will start with some simple patterns and build up to more complex patterns. So when we parse C</foo/> we see something like the following table. The left shows what is being parsed, and the number indicates where the next regop would go. The stuff on the right is the trace output of the graph. The names are chosen to be short to make it less dense on the screen. 'tsdy' is a special form of C<regtail()> which does some extra analysis. >foo< 1 reg brnc piec atom >< 4 tsdy~ EXACT <foo> (EXACT) (1) ~ attach to END (3) offset to 2 The resulting program then looks like: 1: EXACT <foo>(3) 3: END(0) As you can see, even though we parsed out a branch and a piece, it was ultimately only an atom. The final program shows us how things work. We have an C<EXACT> regop, followed by an C<END> regop. The number in parens indicates where the C<regnext> of the node goes. The C<regnext> of an C<END> regop is unused, as C<END> regops mean we have successfully matched. The number on the left indicates the position of the regop in the regnode array. Now let's try a harder pattern. We will add a quantifier, so now we have the pattern C</foo+/>. We will see that C<regbranch()> calls C<regpiece()> twice. >foo+< 1 reg brnc piec atom >o+< 3 piec atom >< 6 tail~ EXACT <fo> (1) 7 tsdy~ EXACT <fo> (EXACT) (1) ~ PLUS (END) (3) ~ attach to END (6) offset to 3 And we end up with the program: 1: EXACT <fo>(3) 3: PLUS(6) 4: EXACT <o>(0) 6: END(0) Now we have a special case. The C<EXACT> regop has a C<regnext> of 0. This is because if it matches it should try to match itself again. The C<PLUS> regop handles the actual failure of the C<EXACT> regop and acts appropriately (going to regnode 6 if the C<EXACT> matched at least once, or failing if it didn't). Now for something much more complex: C</x(?:foo*|b[a][rR])(foo|bar)$/> >x(?:foo*|b... 1 reg brnc piec atom >(?:foo*|b[... 3 piec atom >?:foo*|b[a... reg >foo*|b[a][... brnc piec atom >o*|b[a][rR... 5 piec atom >|b[a][rR])... 8 tail~ EXACT <fo> (3) >b[a][rR])(... 9 brnc 10 piec atom >[a][rR])(f... 12 piec atom >a][rR])(fo... clas >[rR])(foo|... 14 tail~ EXACT <b> (10) piec atom >rR])(foo|b... clas >)(foo|bar)... 25 tail~ EXACT <a> (12) tail~ BRANCH (3) 26 tsdy~ BRANCH (END) (9) ~ attach to TAIL (25) offset to 16 tsdy~ EXACT <fo> (EXACT) (4) ~ STAR (END) (6) ~ attach to TAIL (25) offset to 19 tsdy~ EXACT <b> (EXACT) (10) ~ EXACT <a> (EXACT) (12) ~ ANYOF[Rr] (END) (14) ~ attach to TAIL (25) offset to 11 >(foo|bar)$< tail~ EXACT <x> (1) piec atom >foo|bar)$< reg 28 brnc piec atom >|bar)$< 31 tail~ OPEN1 (26) >bar)$< brnc 32 piec atom >)$< 34 tail~ BRANCH (28) 36 tsdy~ BRANCH (END) (31) ~ attach to CLOSE1 (34) offset to 3 tsdy~ EXACT <foo> (EXACT) (29) ~ attach to CLOSE1 (34) offset to 5 tsdy~ EXACT <bar> (EXACT) (32) ~ attach to CLOSE1 (34) offset to 2 >$< tail~ BRANCH (3) ~ BRANCH (9) ~ TAIL (25) piec atom >< 37 tail~ OPEN1 (26) ~ BRANCH (28) ~ BRANCH (31) ~ CLOSE1 (34) 38 tsdy~ EXACT <x> (EXACT) (1) ~ BRANCH (END) (3) ~ BRANCH (END) (9) ~ TAIL (END) (25) ~ OPEN1 (END) (26) ~ BRANCH (END) (28) ~ BRANCH (END) (31) ~ CLOSE1 (END) (34) ~ EOL (END) (36) ~ attach to END (37) offset to 1 Resulting in the program 1: EXACT <x>(3) 3: BRANCH(9) 4: EXACT <fo>(6) 6: STAR(26) 7: EXACT <o>(0) 9: BRANCH(25) 10: EXACT <ba>(14) 12: OPTIMIZED (2 nodes) 14: ANYOF[Rr](26) 25: TAIL(26) 26: OPEN1(28) 28: TRIE-EXACT(34) [StS:1 Wds:2 Cs:6 Uq:5 #Sts:7 Mn:3 Mx:3 Stcls:bf] <foo> <bar> 30: OPTIMIZED (4 nodes) 34: CLOSE1(36) 36: EOL(37) 37: END(0) Here we can see a much more complex program, with various optimisations in play. At regnode 10 we see an example where a character class with only one character in it was turned into an C<EXACT> node. We can also see where an entire alternation was turned into a C<TRIE-EXACT> node. As a consequence, some of the regnodes have been marked as optimised away. We can see that the C<$> symbol has been converted into an C<EOL> regop, a special piece of code that looks for C<\n> or the end of the string. The next pointer for C<BRANCH>es is interesting in that it points at where execution should go if the branch fails. When executing, if the engine tries to traverse from a branch to a C<regnext> that isn't a branch then the engine will know that the entire set of branches has failed. =head3 Peep-hole Optimisation and Analysis The regular expression engine can be a weighty tool to wield. On long strings and complex patterns it can end up having to do a lot of work to find a match, and even more to decide that no match is possible. Consider a situation like the following pattern. 'ababababababababababab' =~ /(a|b)*z/ The C<(a|b)*> part can match at every char in the string, and then fail every time because there is no C<z> in the string. So obviously we can avoid using the regex engine unless there is a C<z> in the string. Likewise in a pattern like: /foo(\w+)bar/ In this case we know that the string must contain a C<foo> which must be followed by C<bar>. We can use Fast Boyer-Moore matching as implemented in C<fbm_instr()> to find the location of these strings. If they don't exist then we don't need to resort to the much more expensive regex engine. Even better, if they do exist then we can use their positions to reduce the search space that the regex engine needs to cover to determine if the entire pattern matches. There are various aspects of the pattern that can be used to facilitate optimisations along these lines: =over 5 =item * anchored fixed strings =item * floating fixed strings =item * minimum and maximum length requirements =item * start class =item * Beginning/End of line positions =back Another form of optimisation that can occur is the post-parse "peep-hole" optimisation, where inefficient constructs are replaced by more efficient constructs. The C<TAIL> regops which are used during parsing to mark the end of branches and the end of groups are examples of this. These regops are used as place-holders during construction and "always match" so they can be "optimised away" by making the things that point to the C<TAIL> point to the thing that C<TAIL> points to, thus "skipping" the node. Another optimisation that can occur is that of "C<EXACT> merging" which is where two consecutive C<EXACT> nodes are merged into a single regop. An even more aggressive form of this is that a branch sequence of the form C<EXACT BRANCH ... EXACT> can be converted into a C<TRIE-EXACT> regop. All of this occurs in the routine C<study_chunk()> which uses a special structure C<scan_data_t> to store the analysis that it has performed, and does the "peep-hole" optimisations as it goes. The code involved in C<study_chunk()> is extremely cryptic. Be careful. :-) =head2 Execution Execution of a regex generally involves two phases, the first being finding the start point in the string where we should match from, and the second being running the regop interpreter. If we can tell that there is no valid start point then we don't bother running interpreter at all. Likewise, if we know from the analysis phase that we cannot detect a short-cut to the start position, we go straight to the interpreter. The two entry points are C<re_intuit_start()> and C<pregexec()>. These routines have a somewhat incestuous relationship with overlap between their functions, and C<pregexec()> may even call C<re_intuit_start()> on its own. Nevertheless other parts of the perl source code may call into either, or both. Execution of the interpreter itself used to be recursive, but thanks to the efforts of Dave Mitchell in the 5.9.x development track, that has changed: now an internal stack is maintained on the heap and the routine is fully iterative. This can make it tricky as the code is quite conservative about what state it stores, with the result that two consecutive lines in the code can actually be running in totally different contexts due to the simulated recursion. =head3 Start position and no-match optimisations C<re_intuit_start()> is responsible for handling start points and no-match optimisations as determined by the results of the analysis done by C<study_chunk()> (and described in L<Peep-hole Optimisation and Analysis>). The basic structure of this routine is to try to find the start- and/or end-points of where the pattern could match, and to ensure that the string is long enough to match the pattern. It tries to use more efficient methods over less efficient methods and may involve considerable cross-checking of constraints to find the place in the string that matches. For instance it may try to determine that a given fixed string must be not only present but a certain number of chars before the end of the string, or whatever. It calls several other routines, such as C<fbm_instr()> which does Fast Boyer Moore matching and C<find_byclass()> which is responsible for finding the start using the first mandatory regop in the program. When the optimisation criteria have been satisfied, C<reg_try()> is called to perform the match. =head3 Program execution C<pregexec()> is the main entry point for running a regex. It contains support for initialising the regex interpreter's state, running C<re_intuit_start()> if needed, and running the interpreter on the string from various start positions as needed. When it is necessary to use the regex interpreter C<pregexec()> calls C<regtry()>. C<regtry()> is the entry point into the regex interpreter. It expects as arguments a pointer to a C<regmatch_info> structure and a pointer to a string. It returns an integer 1 for success and a 0 for failure. It is basically a set-up wrapper around C<regmatch()>. C<regmatch> is the main "recursive loop" of the interpreter. It is basically a giant switch statement that implements a state machine, where the possible states are the regops themselves, plus a number of additional intermediate and failure states. A few of the states are implemented as subroutines but the bulk are inline code. =head1 MISCELLANEOUS =head2 Unicode and Localisation Support When dealing with strings containing characters that cannot be represented using an eight-bit character set, perl uses an internal representation that is a permissive version of Unicode's UTF-8 encoding[2]. This uses single bytes to represent characters from the ASCII character set, and sequences of two or more bytes for all other characters. (See L<perlunitut> for more information about the relationship between UTF-8 and perl's encoding, utf8. The difference isn't important for this discussion.) No matter how you look at it, Unicode support is going to be a pain in a regex engine. Tricks that might be fine when you have 256 possible characters often won't scale to handle the size of the UTF-8 character set. Things you can take for granted with ASCII may not be true with Unicode. For instance, in ASCII, it is safe to assume that C<sizeof(char1) == sizeof(char2)>, but in UTF-8 it isn't. Unicode case folding is vastly more complex than the simple rules of ASCII, and even when not using Unicode but only localised single byte encodings, things can get tricky (for example, B<LATIN SMALL LETTER SHARP S> (U+00DF, E<szlig>) should match 'SS' in localised case-insensitive matching). Making things worse is that UTF-8 support was a later addition to the regex engine (as it was to perl) and this necessarily made things a lot more complicated. Obviously it is easier to design a regex engine with Unicode support in mind from the beginning than it is to retrofit it to one that wasn't. Nearly all regops that involve looking at the input string have two cases, one for UTF-8, and one not. In fact, it's often more complex than that, as the pattern may be UTF-8 as well. Care must be taken when making changes to make sure that you handle UTF-8 properly, both at compile time and at execution time, including when the string and pattern are mismatched. The following comment in F<regcomp.h> gives an example of exactly how tricky this can be: Two problematic code points in Unicode casefolding of EXACT nodes: U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS which casefold to Unicode UTF-8 U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81 U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81 This means that in case-insensitive matching (or "loose matching", as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte length of the above casefolded versions) can match a target string of length two (the byte length of UTF-8 encoded U+0390 or U+03B0). This would rather mess up the minimum length computation. What we'll do is to look for the tail four bytes, and then peek at the preceding two bytes to see whether we need to decrease the minimum length by four (six minus two). Thanks to the design of UTF-8, there cannot be false matches: A sequence of valid UTF-8 bytes cannot be a subsequence of another valid sequence of UTF-8 bytes. =head2 Base Structures The C<regexp> structure described in L<perlreapi> is common to all regex engines. Two of its fields that are intended for the private use of the regex engine that compiled the pattern. These are the C<intflags> and pprivate members. The C<pprivate> is a void pointer to an arbitrary structure whose use and management is the responsibility of the compiling engine. perl will never modify either of these values. In the case of the stock engine the structure pointed to by C<pprivate> is called C<regexp_internal>. Its C<pprivate> and C<intflags> fields contain data specific to each engine. There are two structures used to store a compiled regular expression. One, the C<regexp> structure described in L<perlreapi> is populated by the engine currently being. used and some of its fields read by perl to implement things such as the stringification of C<qr//>. The other structure is pointed to be the C<regexp> struct's C<pprivate> and is in addition to C<intflags> in the same struct considered to be the property of the regex engine which compiled the regular expression; The regexp structure contains all the data that perl needs to be aware of to properly work with the regular expression. It includes data about optimisations that perl can use to determine if the regex engine should really be used, and various other control info that is needed to properly execute patterns in various contexts such as is the pattern anchored in some way, or what flags were used during the compile, or whether the program contains special constructs that perl needs to be aware of. In addition it contains two fields that are intended for the private use of the regex engine that compiled the pattern. These are the C<intflags> and pprivate members. The C<pprivate> is a void pointer to an arbitrary structure whose use and management is the responsibility of the compiling engine. perl will never modify either of these values. As mentioned earlier, in the case of the default engines, the C<pprivate> will be a pointer to a regexp_internal structure which holds the compiled program and any additional data that is private to the regex engine implementation. =head3 Perl's C<pprivate> structure The following structure is used as the C<pprivate> struct by perl's regex engine. Since it is specific to perl it is only of curiosity value to other engine implementations. typedef struct regexp_internal { regexp_paren_ofs *swap; /* Swap copy of *startp / *endp */ U32 *offsets; /* offset annotations 20001228 MJD data about mapping the program to the string*/ regnode *regstclass; /* Optional startclass as identified or constructed by the optimiser */ struct reg_data *data; /* Additional miscellaneous data used by the program. Used to make it easier to clone and free arbitrary data that the regops need. Often the ARG field of a regop is an index into this structure */ regnode program[1]; /* Unwarranted chumminess with compiler. */ } regexp_internal; =over 5 =item C<swap> C<swap> formerly was an extra set of startp/endp stored in a C<regexp_paren_ofs> struct. This was used when the last successful match was from the same pattern as the current pattern, so that a partial match didn't overwrite the previous match's results, but it caused a problem with re-entrant code such as trying to build the UTF-8 swashes. Currently unused and left for backward compatibility with 5.10.0. =item C<offsets> Offsets holds a mapping of offset in the C<program> to offset in the C<precomp> string. This is only used by ActiveState's visual regex debugger. =item C<regstclass> Special regop that is used by C<re_intuit_start()> to check if a pattern can match at a certain position. For instance if the regex engine knows that the pattern must start with a 'Z' then it can scan the string until it finds one and then launch the regex engine from there. The routine that handles this is called C<find_by_class()>. Sometimes this field points at a regop embedded in the program, and sometimes it points at an independent synthetic regop that has been constructed by the optimiser. =item C<data> This field points at a reg_data structure, which is defined as follows struct reg_data { U32 count; U8 *what; void* data[1]; }; This structure is used for handling data structures that the regex engine needs to handle specially during a clone or free operation on the compiled product. Each element in the data array has a corresponding element in the what array. During compilation regops that need special structures stored will add an element to each array using the add_data() routine and then store the index in the regop. =item C<program> Compiled program. Inlined into the structure so the entire struct can be treated as a single blob. =back =head1 SEE ALSO L<perlreapi> L<perlre> L<perlunitut> =head1 AUTHOR by Yves Orton, 2006. With excerpts from Perl, and contributions and suggestions from Ronald J. Kimball, Dave Mitchell, Dominic Dunlop, Mark Jason Dominus, Stephen McCamant, and David Landgren. =head1 LICENCE Same terms as Perl. =head1 REFERENCES [1] L<http://perl.plover.com/Rx/paper/> [2] L<http://www.unicode.org> =cut PK PU�\�����f �f perlrebackslash.podnu �[��� =head1 NAME perlrebackslash - Perl Regular Expression Backslash Sequences and Escapes =head1 DESCRIPTION The top level documentation about Perl regular expressions is found in L<perlre>. This document describes all backslash and escape sequences. After explaining the role of the backslash, it lists all the sequences that have a special meaning in Perl regular expressions (in alphabetical order), then describes each of them. Most sequences are described in detail in different documents; the primary purpose of this document is to have a quick reference guide describing all backslash and escape sequences. =head2 The backslash In a regular expression, the backslash can perform one of two tasks: it either takes away the special meaning of the character following it (for instance, C<\|> matches a vertical bar, it's not an alternation), or it is the start of a backslash or escape sequence. The rules determining what it is are quite simple: if the character following the backslash is an ASCII punctuation (non-word) character (that is, anything that is not a letter, digit, or underscore), then the backslash just takes away any special meaning of the character following it. If the character following the backslash is an ASCII letter or an ASCII digit, then the sequence may be special; if so, it's listed below. A few letters have not been used yet, so escaping them with a backslash doesn't change them to be special. A future version of Perl may assign a special meaning to them, so if you have warnings turned on, Perl issues a warning if you use such a sequence. [1]. It is however guaranteed that backslash or escape sequences never have a punctuation character following the backslash, not now, and not in a future version of Perl 5. So it is safe to put a backslash in front of a non-word character. Note that the backslash itself is special; if you want to match a backslash, you have to escape the backslash with a backslash: C</\\/> matches a single backslash. =over 4 =item [1] There is one exception. If you use an alphanumeric character as the delimiter of your pattern (which you probably shouldn't do for readability reasons), you have to escape the delimiter if you want to match it. Perl won't warn then. See also L<perlop/Gory details of parsing quoted constructs>. =back =head2 All the sequences and escapes Those not usable within a bracketed character class (like C<[\da-z]>) are marked as C<Not in [].> \000 Octal escape sequence. See also \o{}. \1 Absolute backreference. Not in []. \a Alarm or bell. \A Beginning of string. Not in []. \b Word/non-word boundary. (Backspace in []). \B Not a word/non-word boundary. Not in []. \cX Control-X \C Single octet, even under UTF-8. Not in []. \d Character class for digits. \D Character class for non-digits. \e Escape character. \E Turn off \Q, \L and \U processing. Not in []. \f Form feed. \F Foldcase till \E. Not in []. \g{}, \g1 Named, absolute or relative backreference. Not in [] \G Pos assertion. Not in []. \h Character class for horizontal whitespace. \H Character class for non horizontal whitespace. \k{}, \k<>, \k'' Named backreference. Not in []. \K Keep the stuff left of \K. Not in []. \l Lowercase next character. Not in []. \L Lowercase till \E. Not in []. \n (Logical) newline character. \N Any character but newline. Experimental. Not in []. \N{} Named or numbered (Unicode) character or sequence. \o{} Octal escape sequence. \p{}, \pP Character with the given Unicode property. \P{}, \PP Character without the given Unicode property. \Q Quote (disable) pattern metacharacters till \E. Not in []. \r Return character. \R Generic new line. Not in []. \s Character class for whitespace. \S Character class for non whitespace. \t Tab character. \u Titlecase next character. Not in []. \U Uppercase till \E. Not in []. \v Character class for vertical whitespace. \V Character class for non vertical whitespace. \w Character class for word characters. \W Character class for non-word characters. \x{}, \x00 Hexadecimal escape sequence. \X Unicode "extended grapheme cluster". Not in []. \z End of string. Not in []. \Z End of string. Not in []. =head2 Character Escapes =head3 Fixed characters A handful of characters have a dedicated I<character escape>. The following table shows them, along with their ASCII code points (in decimal and hex), their ASCII name, the control escape on ASCII platforms and a short description. (For EBCDIC platforms, see L<perlebcdic/OPERATOR DIFFERENCES>.) Seq. Code Point ASCII Cntrl Description. Dec Hex \a 7 07 BEL \cG alarm or bell \b 8 08 BS \cH backspace [1] \e 27 1B ESC \c[ escape character \f 12 0C FF \cL form feed \n 10 0A LF \cJ line feed [2] \r 13 0D CR \cM carriage return \t 9 09 TAB \cI tab =over 4 =item [1] C<\b> is the backspace character only inside a character class. Outside a character class, C<\b> is a word/non-word boundary. =item [2] C<\n> matches a logical newline. Perl converts between C<\n> and your OS's native newline character when reading from or writing to text files. =back =head4 Example $str =~ /\t/; # Matches if $str contains a (horizontal) tab. =head3 Control characters C<\c> is used to denote a control character; the character following C<\c> determines the value of the construct. For example the value of C<\cA> is C<chr(1)>, and the value of C<\cb> is C<chr(2)>, etc. The gory details are in L<perlop/"Regexp Quote-Like Operators">. A complete list of what C<chr(1)>, etc. means for ASCII and EBCDIC platforms is in L<perlebcdic/OPERATOR DIFFERENCES>. Note that C<\c\> alone at the end of a regular expression (or doubled-quoted string) is not valid. The backslash must be followed by another character. That is, C<\c\I<X>> means C<chr(28) . 'I<X>'> for all characters I<X>. To write platform-independent code, you must use C<\N{I<NAME>}> instead, like C<\N{ESCAPE}> or C<\N{U+001B}>, see L<charnames>. Mnemonic: I<c>ontrol character. =head4 Example $str =~ /\cK/; # Matches if $str contains a vertical tab (control-K). =head3 Named or numbered characters and character sequences Unicode characters have a Unicode name and numeric code point (ordinal) value. Use the C<\N{}> construct to specify a character by either of these values. Certain sequences of characters also have names. To specify by name, the name of the character or character sequence goes between the curly braces. To specify a character by Unicode code point, use the form C<\N{U+I<code point>}>, where I<code point> is a number in hexadecimal that gives the code point that Unicode has assigned to the desired character. It is customary but not required to use leading zeros to pad the number to 4 digits. Thus C<\N{U+0041}> means C<LATIN CAPITAL LETTER A>, and you will rarely see it written without the two leading zeros. C<\N{U+0041}> means "A" even on EBCDIC machines (where the ordinal value of "A" is not 0x41). It is even possible to give your own names to characters and character sequences. For details, see L<charnames>. (There is an expanded internal form that you may see in debug output: C<\N{U+I<code point>.I<code point>...}>. The C<...> means any number of these I<code point>s separated by dots. This represents the sequence formed by the characters. This is an internal form only, subject to change, and you should not try to use it yourself.) Mnemonic: I<N>amed character. Note that a character or character sequence expressed as a named or numbered character is considered a character without special meaning by the regex engine, and will match "as is". =head4 Example $str =~ /\N{THAI CHARACTER SO SO}/; # Matches the Thai SO SO character use charnames 'Cyrillic'; # Loads Cyrillic names. $str =~ /\N{ZHE}\N{KA}/; # Match "ZHE" followed by "KA". =head3 Octal escapes There are two forms of octal escapes. Each is used to specify a character by its code point specified in octal notation. One form, available starting in Perl 5.14 looks like C<\o{...}>, where the dots represent one or more octal digits. It can be used for any Unicode character. It was introduced to avoid the potential problems with the other form, available in all Perls. That form consists of a backslash followed by three octal digits. One problem with this form is that it can look exactly like an old-style backreference (see L</Disambiguation rules between old-style octal escapes and backreferences> below.) You can avoid this by making the first of the three digits always a zero, but that makes \077 the largest code point specifiable. In some contexts, a backslash followed by two or even one octal digits may be interpreted as an octal escape, sometimes with a warning, and because of some bugs, sometimes with surprising results. Also, if you are creating a regex out of smaller snippets concatenated together, and you use fewer than three digits, the beginning of one snippet may be interpreted as adding digits to the ending of the snippet before it. See L</Absolute referencing> for more discussion and examples of the snippet problem. Note that a character expressed as an octal escape is considered a character without special meaning by the regex engine, and will match "as is". To summarize, the C<\o{}> form is always safe to use, and the other form is safe to use for code points through \077 when you use exactly three digits to specify them. Mnemonic: I<0>ctal or I<o>ctal. =head4 Examples (assuming an ASCII platform) $str = "Perl"; $str =~ /\o{120}/; # Match, "\120" is "P". $str =~ /\120/; # Same. $str =~ /\o{120}+/; # Match, "\120" is "P", it's repeated at least once $str =~ /\120+/; # Same. $str =~ /P\053/; # No match, "\053" is "+" and taken literally. /\o{23073}/ # Black foreground, white background smiling face. /\o{4801234567}/ # Raises a warning, and yields chr(4) =head4 Disambiguation rules between old-style octal escapes and backreferences Octal escapes of the C<\000> form outside of bracketed character classes potentially clash with old-style backreferences. (see L</Absolute referencing> below). They both consist of a backslash followed by numbers. So Perl has to use heuristics to determine whether it is a backreference or an octal escape. Perl uses the following rules to disambiguate: =over 4 =item 1 If the backslash is followed by a single digit, it's a backreference. =item 2 If the first digit following the backslash is a 0, it's an octal escape. =item 3 If the number following the backslash is N (in decimal), and Perl already has seen N capture groups, Perl considers this a backreference. Otherwise, it considers it an octal escape. If N has more than three digits, Perl takes only the first three for the octal escape; the rest are matched as is. my $pat = "(" x 999; $pat .= "a"; $pat .= ")" x 999; /^($pat)\1000$/; # Matches 'aa'; there are 1000 capture groups. /^$pat\1000$/; # Matches 'a@0'; there are 999 capture groups # and \1000 is seen as \100 (a '@') and a '0' =back You can force a backreference interpretation always by using the C<\g{...}> form. You can the force an octal interpretation always by using the C<\o{...}> form, or for numbers up through \077 (= 63 decimal), by using three digits, beginning with a "0". =head3 Hexadecimal escapes Like octal escapes, there are two forms of hexadecimal escapes, but both start with the same thing, C<\x>. This is followed by either exactly two hexadecimal digits forming a number, or a hexadecimal number of arbitrary length surrounded by curly braces. The hexadecimal number is the code point of the character you want to express. Note that a character expressed as one of these escapes is considered a character without special meaning by the regex engine, and will match "as is". Mnemonic: heI<x>adecimal. =head4 Examples (assuming an ASCII platform) $str = "Perl"; $str =~ /\x50/; # Match, "\x50" is "P". $str =~ /\x50+/; # Match, "\x50" is "P", it is repeated at least once $str =~ /P\x2B/; # No match, "\x2B" is "+" and taken literally. /\x{2603}\x{2602}/ # Snowman with an umbrella. # The Unicode character 2603 is a snowman, # the Unicode character 2602 is an umbrella. /\x{263B}/ # Black smiling face. /\x{263b}/ # Same, the hex digits A - F are case insensitive. =head2 Modifiers A number of backslash sequences have to do with changing the character, or characters following them. C<\l> will lowercase the character following it, while C<\u> will uppercase (or, more accurately, titlecase) the character following it. They provide functionality similar to the functions C<lcfirst> and C<ucfirst>. To uppercase or lowercase several characters, one might want to use C<\L> or C<\U>, which will lowercase/uppercase all characters following them, until either the end of the pattern or the next occurrence of C<\E>, whichever comes first. They provide functionality similar to what the functions C<lc> and C<uc> provide. C<\Q> is used to quote (disable) pattern metacharacters, up to the next C<\E> or the end of the pattern. C<\Q> adds a backslash to any character that could have special meaning to Perl. In the ASCII range, it quotes every character that isn't a letter, digit, or underscore. See L<perlfunc/quotemeta> for details on what gets quoted for non-ASCII code points. Using this ensures that any character between C<\Q> and C<\E> will be matched literally, not interpreted as a metacharacter by the regex engine. C<\F> can be used to casefold all characters following, up to the next C<\E> or the end of the pattern. It provides the functionality similar to the C<fc> function. Mnemonic: I<L>owercase, I<U>ppercase, I<F>old-case, I<Q>uotemeta, I<E>nd. =head4 Examples $sid = "sid"; $greg = "GrEg"; $miranda = "(Miranda)"; $str =~ /\u$sid/; # Matches 'Sid' $str =~ /\L$greg/; # Matches 'greg' $str =~ /\Q$miranda\E/; # Matches '(Miranda)', as if the pattern # had been written as /\(Miranda\)/ =head2 Character classes Perl regular expressions have a large range of character classes. Some of the character classes are written as a backslash sequence. We will briefly discuss those here; full details of character classes can be found in L<perlrecharclass>. C<\w> is a character class that matches any single I<word> character (letters, digits, Unicode marks, and connector punctuation (like the underscore)). C<\d> is a character class that matches any decimal digit, while the character class C<\s> matches any whitespace character. New in perl 5.10.0 are the classes C<\h> and C<\v> which match horizontal and vertical whitespace characters. The exact set of characters matched by C<\d>, C<\s>, and C<\w> varies depending on various pragma and regular expression modifiers. It is possible to restrict the match to the ASCII range by using the C</a> regular expression modifier. See L<perlrecharclass>. The uppercase variants (C<\W>, C<\D>, C<\S>, C<\H>, and C<\V>) are character classes that match, respectively, any character that isn't a word character, digit, whitespace, horizontal whitespace, or vertical whitespace. Mnemonics: I<w>ord, I<d>igit, I<s>pace, I<h>orizontal, I<v>ertical. =head3 Unicode classes C<\pP> (where C<P> is a single letter) and C<\p{Property}> are used to match a character that matches the given Unicode property; properties include things like "letter", or "thai character". Capitalizing the sequence to C<\PP> and C<\P{Property}> make the sequence match a character that doesn't match the given Unicode property. For more details, see L<perlrecharclass/Backslash sequences> and L<perlunicode/Unicode Character Properties>. Mnemonic: I<p>roperty. =head2 Referencing If capturing parenthesis are used in a regular expression, we can refer to the part of the source string that was matched, and match exactly the same thing. There are three ways of referring to such I<backreference>: absolutely, relatively, and by name. =for later add link to perlrecapture =head3 Absolute referencing Either C<\gI<N>> (starting in Perl 5.10.0), or C<\I<N>> (old-style) where I<N> is a positive (unsigned) decimal number of any length is an absolute reference to a capturing group. I<N> refers to the Nth set of parentheses, so C<\gI<N>> refers to whatever has been matched by that set of parentheses. Thus C<\g1> refers to the first capture group in the regex. The C<\gI<N>> form can be equivalently written as C<\g{I<N>}> which avoids ambiguity when building a regex by concatenating shorter strings. Otherwise if you had a regex C<qr/$a$b/>, and C<$a> contained C<"\g1">, and C<$b> contained C<"37">, you would get C</\g137/> which is probably not what you intended. In the C<\I<N>> form, I<N> must not begin with a "0", and there must be at least I<N> capturing groups, or else I<N> is considered an octal escape (but something like C<\18> is the same as C<\0018>; that is, the octal escape C<"\001"> followed by a literal digit C<"8">). Mnemonic: I<g>roup. =head4 Examples /(\w+) \g1/; # Finds a duplicated word, (e.g. "cat cat"). /(\w+) \1/; # Same thing; written old-style /(.)(.)\g2\g1/; # Match a four letter palindrome (e.g. "ABBA"). =head3 Relative referencing C<\g-I<N>> (starting in Perl 5.10.0) is used for relative addressing. (It can be written as C<\g{-I<N>>.) It refers to the I<N>th group before the C<\g{-I<N>}>. The big advantage of this form is that it makes it much easier to write patterns with references that can be interpolated in larger patterns, even if the larger pattern also contains capture groups. =head4 Examples /(A) # Group 1 ( # Group 2 (B) # Group 3 \g{-1} # Refers to group 3 (B) \g{-3} # Refers to group 1 (A) ) /x; # Matches "ABBA". my $qr = qr /(.)(.)\g{-2}\g{-1}/; # Matches 'abab', 'cdcd', etc. /$qr$qr/ # Matches 'ababcdcd'. =head3 Named referencing C<\g{I<name>}> (starting in Perl 5.10.0) can be used to back refer to a named capture group, dispensing completely with having to think about capture buffer positions. To be compatible with .Net regular expressions, C<\g{name}> may also be written as C<\k{name}>, C<< \k<name> >> or C<\k'name'>. To prevent any ambiguity, I<name> must not start with a digit nor contain a hyphen. =head4 Examples /(?<word>\w+) \g{word}/ # Finds duplicated word, (e.g. "cat cat") /(?<word>\w+) \k{word}/ # Same. /(?<word>\w+) \k<word>/ # Same. /(?<letter1>.)(?<letter2>.)\g{letter2}\g{letter1}/ # Match a four letter palindrome (e.g. "ABBA") =head2 Assertions Assertions are conditions that have to be true; they don't actually match parts of the substring. There are six assertions that are written as backslash sequences. =over 4 =item \A C<\A> only matches at the beginning of the string. If the C</m> modifier isn't used, then C</\A/> is equivalent to C</^/>. However, if the C</m> modifier is used, then C</^/> matches internal newlines, but the meaning of C</\A/> isn't changed by the C</m> modifier. C<\A> matches at the beginning of the string regardless whether the C</m> modifier is used. =item \z, \Z C<\z> and C<\Z> match at the end of the string. If the C</m> modifier isn't used, then C</\Z/> is equivalent to C</$/>; that is, it matches at the end of the string, or one before the newline at the end of the string. If the C</m> modifier is used, then C</$/> matches at internal newlines, but the meaning of C</\Z/> isn't changed by the C</m> modifier. C<\Z> matches at the end of the string (or just before a trailing newline) regardless whether the C</m> modifier is used. C<\z> is just like C<\Z>, except that it does not match before a trailing newline. C<\z> matches at the end of the string only, regardless of the modifiers used, and not just before a newline. It is how to anchor the match to the true end of the string under all conditions. =item \G C<\G> is usually used only in combination with the C</g> modifier. If the C</g> modifier is used and the match is done in scalar context, Perl remembers where in the source string the last match ended, and the next time, it will start the match from where it ended the previous time. C<\G> matches the point where the previous match on that string ended, or the beginning of that string if there was no previous match. =for later add link to perlremodifiers Mnemonic: I<G>lobal. =item \b, \B C<\b> matches at any place between a word and a non-word character; C<\B> matches at any place between characters where C<\b> doesn't match. C<\b> and C<\B> assume there's a non-word character before the beginning and after the end of the source string; so C<\b> will match at the beginning (or end) of the source string if the source string begins (or ends) with a word character. Otherwise, C<\B> will match. Do not use something like C<\b=head\d\b> and expect it to match the beginning of a line. It can't, because for there to be a boundary before the non-word "=", there must be a word character immediately previous. All boundary determinations look for word characters alone, not for non-words characters nor for string ends. It may help to understand how <\b> and <\B> work by equating them as follows: \b really means (?:(?<=\w)(?!\w)|(?<!\w)(?=\w)) \B really means (?:(?<=\w)(?=\w)|(?<!\w)(?!\w)) Mnemonic: I<b>oundary. =back =head4 Examples "cat" =~ /\Acat/; # Match. "cat" =~ /cat\Z/; # Match. "cat\n" =~ /cat\Z/; # Match. "cat\n" =~ /cat\z/; # No match. "cat" =~ /\bcat\b/; # Matches. "cats" =~ /\bcat\b/; # No match. "cat" =~ /\bcat\B/; # No match. "cats" =~ /\bcat\B/; # Match. while ("cat dog" =~ /(\w+)/g) { print $1; # Prints 'catdog' } while ("cat dog" =~ /\G(\w+)/g) { print $1; # Prints 'cat' } =head2 Misc Here we document the backslash sequences that don't fall in one of the categories above. These are: =over 4 =item \C C<\C> always matches a single octet, even if the source string is encoded in UTF-8 format, and the character to be matched is a multi-octet character. C<\C> was introduced in perl 5.6. This is very dangerous, because it violates the logical character abstraction and can cause UTF-8 sequences to become malformed. Mnemonic: oI<C>tet. =item \K This appeared in perl 5.10.0. Anything matched left of C<\K> is not included in C<$&>, and will not be replaced if the pattern is used in a substitution. This lets you write C<s/PAT1 \K PAT2/REPL/x> instead of C<s/(PAT1) PAT2/${1}REPL/x> or C<s/(?<=PAT1) PAT2/REPL/x>. Mnemonic: I<K>eep. =item \N This is an experimental feature new to perl 5.12.0. It matches any character that is B<not> a newline. It is a short-hand for writing C<[^\n]>, and is identical to the C<.> metasymbol, except under the C</s> flag, which changes the meaning of C<.>, but not C<\N>. Note that C<\N{...}> can mean a L<named or numbered character |/Named or numbered characters and character sequences>. Mnemonic: Complement of I<\n>. =item \R X<\R> C<\R> matches a I<generic newline>; that is, anything considered a linebreak sequence by Unicode. This includes all characters matched by C<\v> (vertical whitespace), and the multi character sequence C<"\x0D\x0A"> (carriage return followed by a line feed, sometimes called the network newline; it's the end of line sequence used in Microsoft text files opened in binary mode). C<\R> is equivalent to C<< (?>\x0D\x0A|\v) >>. (The reason it doesn't backtrack is that the sequence is considered inseparable. That means that "\x0D\x0A" =~ /^\R\x0A$/ # No match fails, because the C<\R> matches the entire string, and won't backtrack to match just the C<"\x0D">.) Since C<\R> can match a sequence of more than one character, it cannot be put inside a bracketed character class; C</[\R]/> is an error; use C<\v> instead. C<\R> was introduced in perl 5.10.0. Note that this does not respect any locale that might be in effect; it matches according to the platform's native character set. Mnemonic: none really. C<\R> was picked because PCRE already uses C<\R>, and more importantly because Unicode recommends such a regular expression metacharacter, and suggests C<\R> as its notation. =item \X X<\X> This matches a Unicode I<extended grapheme cluster>. C<\X> matches quite well what normal (non-Unicode-programmer) usage would consider a single character. As an example, consider a G with some sort of diacritic mark, such as an arrow. There is no such single character in Unicode, but one can be composed by using a G followed by a Unicode "COMBINING UPWARDS ARROW BELOW", and would be displayed by Unicode-aware software as if it were a single character. Mnemonic: eI<X>tended Unicode character. =back =head4 Examples "\x{256}" =~ /^\C\C$/; # Match as chr (0x256) takes 2 octets in UTF-8. $str =~ s/foo\Kbar/baz/g; # Change any 'bar' following a 'foo' to 'baz' $str =~ s/(.)\K\g1//g; # Delete duplicated characters. "\n" =~ /^\R$/; # Match, \n is a generic newline. "\r" =~ /^\R$/; # Match, \r is a generic newline. "\r\n" =~ /^\R$/; # Match, \r\n is a generic newline. "P\x{307}" =~ /^\X$/ # \X matches a P with a dot above. =cut PK PU�\aT�(� (� perldebguts.podnu �[��� =head1 NAME perldebguts - Guts of Perl debugging =head1 DESCRIPTION This is not L<perldebug>, which tells you how to use the debugger. This manpage describes low-level details concerning the debugger's internals, which range from difficult to impossible to understand for anyone who isn't incredibly intimate with Perl's guts. Caveat lector. =head1 Debugger Internals Perl has special debugging hooks at compile-time and run-time used to create debugging environments. These hooks are not to be confused with the I<perl -Dxxx> command described in L<perlrun>, which is usable only if a special Perl is built per the instructions in the F<INSTALL> podpage in the Perl source tree. For example, whenever you call Perl's built-in C<caller> function from the package C<DB>, the arguments that the corresponding stack frame was called with are copied to the C<@DB::args> array. These mechanisms are enabled by calling Perl with the B<-d> switch. Specifically, the following additional features are enabled (cf. L<perlvar/$^P>): =over 4 =item * Perl inserts the contents of C<$ENV{PERL5DB}> (or C<BEGIN {require 'perl5db.pl'}> if not present) before the first line of your program. =item * Each array C<@{"_<$filename"}> holds the lines of $filename for a file compiled by Perl. The same is also true for C<eval>ed strings that contain subroutines, or which are currently being executed. The $filename for C<eval>ed strings looks like C<(eval 34)>. Code assertions in regexes look like C<(re_eval 19)>. Values in this array are magical in numeric context: they compare equal to zero only if the line is not breakable. =item * Each hash C<%{"_<$filename"}> contains breakpoints and actions keyed by line number. Individual entries (as opposed to the whole hash) are settable. Perl only cares about Boolean true here, although the values used by F<perl5db.pl> have the form C<"$break_condition\0$action">. The same holds for evaluated strings that contain subroutines, or which are currently being executed. The $filename for C<eval>ed strings looks like C<(eval 34)> or C<(re_eval 19)>. =item * Each scalar C<${"_<$filename"}> contains C<"_<$filename">. This is also the case for evaluated strings that contain subroutines, or which are currently being executed. The $filename for C<eval>ed strings looks like C<(eval 34)> or C<(re_eval 19)>. =item * After each C<require>d file is compiled, but before it is executed, C<DB::postponed(*{"_<$filename"})> is called if the subroutine C<DB::postponed> exists. Here, the $filename is the expanded name of the C<require>d file, as found in the values of %INC. =item * After each subroutine C<subname> is compiled, the existence of C<$DB::postponed{subname}> is checked. If this key exists, C<DB::postponed(subname)> is called if the C<DB::postponed> subroutine also exists. =item * A hash C<%DB::sub> is maintained, whose keys are subroutine names and whose values have the form C<filename:startline-endline>. C<filename> has the form C<(eval 34)> for subroutines defined inside C<eval>s, or C<(re_eval 19)> for those within regex code assertions. =item * When the execution of your program reaches a point that can hold a breakpoint, the C<DB::DB()> subroutine is called if any of the variables C<$DB::trace>, C<$DB::single>, or C<$DB::signal> is true. These variables are not C<local>izable. This feature is disabled when executing inside C<DB::DB()>, including functions called from it unless C<< $^D & (1<<30) >> is true. =item * When execution of the program reaches a subroutine call, a call to C<&DB::sub>(I<args>) is made instead, with C<$DB::sub> holding the name of the called subroutine. (This doesn't happen if the subroutine was compiled in the C<DB> package.) =back Note that if C<&DB::sub> needs external data for it to work, no subroutine call is possible without it. As an example, the standard debugger's C<&DB::sub> depends on the C<$DB::deep> variable (it defines how many levels of recursion deep into the debugger you can go before a mandatory break). If C<$DB::deep> is not defined, subroutine calls are not possible, even though C<&DB::sub> exists. =head2 Writing Your Own Debugger =head3 Environment Variables The C<PERL5DB> environment variable can be used to define a debugger. For example, the minimal "working" debugger (it actually doesn't do anything) consists of one line: sub DB::DB {} It can easily be defined like this: $ PERL5DB="sub DB::DB {}" perl -d your-script Another brief debugger, slightly more useful, can be created with only the line: sub DB::DB {print ++$i; scalar <STDIN>} This debugger prints a number which increments for each statement encountered and waits for you to hit a newline before continuing to the next statement. The following debugger is actually useful: { package DB; sub DB {} sub sub {print ++$i, " $sub\n"; &$sub} } It prints the sequence number of each subroutine call and the name of the called subroutine. Note that C<&DB::sub> is being compiled into the package C<DB> through the use of the C<package> directive. When it starts, the debugger reads your rc file (F<./.perldb> or F<~/.perldb> under Unix), which can set important options. (A subroutine (C<&afterinit>) can be defined here as well; it is executed after the debugger completes its own initialization.) After the rc file is read, the debugger reads the PERLDB_OPTS environment variable and uses it to set debugger options. The contents of this variable are treated as if they were the argument of an C<o ...> debugger command (q.v. in L<perldebug/"Configurable Options">). =head3 Debugger Internal Variables In addition to the file and subroutine-related variables mentioned above, the debugger also maintains various magical internal variables. =over 4 =item * C<@DB::dbline> is an alias for C<@{"::_<current_file"}>, which holds the lines of the currently-selected file (compiled by Perl), either explicitly chosen with the debugger's C<f> command, or implicitly by flow of execution. Values in this array are magical in numeric context: they compare equal to zero only if the line is not breakable. =item * C<%DB::dbline> is an alias for C<%{"::_<current_file"}>, which contains breakpoints and actions keyed by line number in the currently-selected file, either explicitly chosen with the debugger's C<f> command, or implicitly by flow of execution. As previously noted, individual entries (as opposed to the whole hash) are settable. Perl only cares about Boolean true here, although the values used by F<perl5db.pl> have the form C<"$break_condition\0$action">. =back =head3 Debugger Customization Functions Some functions are provided to simplify customization. =over 4 =item * See L<perldebug/"Configurable Options"> for a description of options parsed by C<DB::parse_options(string)>. =item * C<DB::dump_trace(skip[,count])> skips the specified number of frames and returns a list containing information about the calling frames (all of them, if C<count> is missing). Each entry is reference to a hash with keys C<context> (either C<.>, C<$>, or C<@>), C<sub> (subroutine name, or info about C<eval>), C<args> (C<undef> or a reference to an array), C<file>, and C<line>. =item * C<DB::print_trace(FH, skip[, count[, short]])> prints formatted info about caller frames. The last two functions may be convenient as arguments to C<< < >>, C<< << >> commands. =back Note that any variables and functions that are not documented in this manpages (or in L<perldebug>) are considered for internal use only, and as such are subject to change without notice. =head1 Frame Listing Output Examples The C<frame> option can be used to control the output of frame information. For example, contrast this expression trace: $ perl -de 42 Stack dump during die enabled outside of evals. Loading DB routines from perl5db.pl patch level 0.94 Emacs support available. Enter h or 'h h' for help. main::(-e:1): 0 DB<1> sub foo { 14 } DB<2> sub bar { 3 } DB<3> t print foo() * bar() main::((eval 172):3): print foo() + bar(); main::foo((eval 168):2): main::bar((eval 170):2): 42 with this one, once the C<o>ption C<frame=2> has been set: DB<4> o f=2 frame = '2' DB<5> t print foo() * bar() 3: foo() * bar() entering main::foo 2: sub foo { 14 }; exited main::foo entering main::bar 2: sub bar { 3 }; exited main::bar 42 By way of demonstration, we present below a laborious listing resulting from setting your C<PERLDB_OPTS> environment variable to the value C<f=n N>, and running I<perl -d -V> from the command line. Examples using various values of C<n> are shown to give you a feel for the difference between settings. Long though it may be, this is not a complete listing, but only excerpts. =over 4 =item 1 entering main::BEGIN entering Config::BEGIN Package lib/Exporter.pm. Package lib/Carp.pm. Package lib/Config.pm. entering Config::TIEHASH entering Exporter::import entering Exporter::export entering Config::myconfig entering Config::FETCH entering Config::FETCH entering Config::FETCH entering Config::FETCH =item 2 entering main::BEGIN entering Config::BEGIN Package lib/Exporter.pm. Package lib/Carp.pm. exited Config::BEGIN Package lib/Config.pm. entering Config::TIEHASH exited Config::TIEHASH entering Exporter::import entering Exporter::export exited Exporter::export exited Exporter::import exited main::BEGIN entering Config::myconfig entering Config::FETCH exited Config::FETCH entering Config::FETCH exited Config::FETCH entering Config::FETCH =item 3 in $=main::BEGIN() from /dev/null:0 in $=Config::BEGIN() from lib/Config.pm:2 Package lib/Exporter.pm. Package lib/Carp.pm. Package lib/Config.pm. in $=Config::TIEHASH('Config') from lib/Config.pm:644 in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0 in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from li in @=Config::myconfig() from /dev/null:0 in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574 in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574 in $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574 in $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574 in $=Config::FETCH(ref(Config), 'osname') from lib/Config.pm:574 in $=Config::FETCH(ref(Config), 'osvers') from lib/Config.pm:574 =item 4 in $=main::BEGIN() from /dev/null:0 in $=Config::BEGIN() from lib/Config.pm:2 Package lib/Exporter.pm. Package lib/Carp.pm. out $=Config::BEGIN() from lib/Config.pm:0 Package lib/Config.pm. in $=Config::TIEHASH('Config') from lib/Config.pm:644 out $=Config::TIEHASH('Config') from lib/Config.pm:644 in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0 in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/ out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/ out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0 out $=main::BEGIN() from /dev/null:0 in @=Config::myconfig() from /dev/null:0 in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574 out $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574 in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574 out $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574 in $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574 out $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574 in $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574 =item 5 in $=main::BEGIN() from /dev/null:0 in $=Config::BEGIN() from lib/Config.pm:2 Package lib/Exporter.pm. Package lib/Carp.pm. out $=Config::BEGIN() from lib/Config.pm:0 Package lib/Config.pm. in $=Config::TIEHASH('Config') from lib/Config.pm:644 out $=Config::TIEHASH('Config') from lib/Config.pm:644 in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0 in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0 out $=main::BEGIN() from /dev/null:0 in @=Config::myconfig() from /dev/null:0 in $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574 out $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574 in $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574 out $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574 =item 6 in $=CODE(0x15eca4)() from /dev/null:0 in $=CODE(0x182528)() from lib/Config.pm:2 Package lib/Exporter.pm. out $=CODE(0x182528)() from lib/Config.pm:0 scalar context return from CODE(0x182528): undef Package lib/Config.pm. in $=Config::TIEHASH('Config') from lib/Config.pm:628 out $=Config::TIEHASH('Config') from lib/Config.pm:628 scalar context return from Config::TIEHASH: empty hash in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0 in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171 out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171 scalar context return from Exporter::export: '' out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0 scalar context return from Exporter::import: '' =back In all cases shown above, the line indentation shows the call tree. If bit 2 of C<frame> is set, a line is printed on exit from a subroutine as well. If bit 4 is set, the arguments are printed along with the caller info. If bit 8 is set, the arguments are printed even if they are tied or references. If bit 16 is set, the return value is printed, too. When a package is compiled, a line like this Package lib/Carp.pm. is printed with proper indentation. =head1 Debugging Regular Expressions There are two ways to enable debugging output for regular expressions. If your perl is compiled with C<-DDEBUGGING>, you may use the B<-Dr> flag on the command line. Otherwise, one can C<use re 'debug'>, which has effects at compile time and run time. Since Perl 5.9.5, this pragma is lexically scoped. =head2 Compile-time Output The debugging output at compile time looks like this: Compiling REx '[bc]d(ef*g)+h[ij]k$' size 45 Got 364 bytes for offset annotations. first at 1 rarest char g at 0 rarest char d at 0 1: ANYOF[bc](12) 12: EXACT <d>(14) 14: CURLYX[0] {1,32767}(28) 16: OPEN1(18) 18: EXACT <e>(20) 20: STAR(23) 21: EXACT <f>(0) 23: EXACT <g>(25) 25: CLOSE1(27) 27: WHILEM[1/1](0) 28: NOTHING(29) 29: EXACT <h>(31) 31: ANYOF[ij](42) 42: EXACT <k>(44) 44: EOL(45) 45: END(0) anchored 'de' at 1 floating 'gh' at 3..2147483647 (checking floating) stclass 'ANYOF[bc]' minlen 7 Offsets: [45] 1[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 5[1] 0[0] 12[1] 0[0] 6[1] 0[0] 7[1] 0[0] 9[1] 8[1] 0[0] 10[1] 0[0] 11[1] 0[0] 12[0] 12[0] 13[1] 0[0] 14[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 18[1] 0[0] 19[1] 20[0] Omitting $` $& $' support. The first line shows the pre-compiled form of the regex. The second shows the size of the compiled form (in arbitrary units, usually 4-byte words) and the total number of bytes allocated for the offset/length table, usually 4+C<size>*8. The next line shows the label I<id> of the first node that does a match. The anchored 'de' at 1 floating 'gh' at 3..2147483647 (checking floating) stclass 'ANYOF[bc]' minlen 7 line (split into two lines above) contains optimizer information. In the example shown, the optimizer found that the match should contain a substring C<de> at offset 1, plus substring C<gh> at some offset between 3 and infinity. Moreover, when checking for these substrings (to abandon impossible matches quickly), Perl will check for the substring C<gh> before checking for the substring C<de>. The optimizer may also use the knowledge that the match starts (at the C<first> I<id>) with a character class, and no string shorter than 7 characters can possibly match. The fields of interest which may appear in this line are =over 4 =item C<anchored> I<STRING> C<at> I<POS> =item C<floating> I<STRING> C<at> I<POS1..POS2> See above. =item C<matching floating/anchored> Which substring to check first. =item C<minlen> The minimal length of the match. =item C<stclass> I<TYPE> Type of first matching node. =item C<noscan> Don't scan for the found substrings. =item C<isall> Means that the optimizer information is all that the regular expression contains, and thus one does not need to enter the regex engine at all. =item C<GPOS> Set if the pattern contains C<\G>. =item C<plus> Set if the pattern starts with a repeated char (as in C<x+y>). =item C<implicit> Set if the pattern starts with C<.*>. =item C<with eval> Set if the pattern contain eval-groups, such as C<(?{ code })> and C<(??{ code })>. =item C<anchored(TYPE)> If the pattern may match only at a handful of places, with C<TYPE> being C<BOL>, C<MBOL>, or C<GPOS>. See the table below. =back If a substring is known to match at end-of-line only, it may be followed by C<$>, as in C<floating 'k'$>. The optimizer-specific information is used to avoid entering (a slow) regex engine on strings that will not definitely match. If the C<isall> flag is set, a call to the regex engine may be avoided even when the optimizer found an appropriate place for the match. Above the optimizer section is the list of I<nodes> of the compiled form of the regex. Each line has format C< >I<id>: I<TYPE> I<OPTIONAL-INFO> (I<next-id>) =head2 Types of Nodes Here are the possible types, with short descriptions: # TYPE arg-description [num-args] [longjump-len] DESCRIPTION # Exit points END no End of program. SUCCEED no Return from a subroutine, basically. # Anchors: BOL no Match "" at beginning of line. MBOL no Same, assuming multiline. SBOL no Same, assuming singleline. EOS no Match "" at end of string. EOL no Match "" at end of line. MEOL no Same, assuming multiline. SEOL no Same, assuming singleline. BOUND no Match "" at any word boundary using native charset semantics for non-utf8 BOUNDL no Match "" at any locale word boundary BOUNDU no Match "" at any word boundary using Unicode semantics BOUNDA no Match "" at any word boundary using ASCII semantics NBOUND no Match "" at any word non-boundary using native charset semantics for non-utf8 NBOUNDL no Match "" at any locale word non-boundary NBOUNDU no Match "" at any word non-boundary using Unicode semantics NBOUNDA no Match "" at any word non-boundary using ASCII semantics GPOS no Matches where last m//g left off. # [Special] alternatives: REG_ANY no Match any one character (except newline). SANY no Match any one character. CANY no Match any one byte. ANYOF sv Match character in (or not in) this class, single char match only ANYOFV sv Match character in (or not in) this class, can match-multiple chars ALNUM no Match any alphanumeric character using native charset semantics for non-utf8 ALNUML no Match any alphanumeric char in locale ALNUMU no Match any alphanumeric char using Unicode semantics ALNUMA no Match [A-Za-z_0-9] NALNUM no Match any non-alphanumeric character using native charset semantics for non-utf8 NALNUML no Match any non-alphanumeric char in locale NALNUMU no Match any non-alphanumeric char using Unicode semantics NALNUMA no Match [^A-Za-z_0-9] SPACE no Match any whitespace character using native charset semantics for non-utf8 SPACEL no Match any whitespace char in locale SPACEU no Match any whitespace char using Unicode semantics SPACEA no Match [ \t\n\f\r] NSPACE no Match any non-whitespace character using native charset semantics for non-utf8 NSPACEL no Match any non-whitespace char in locale NSPACEU no Match any non-whitespace char using Unicode semantics NSPACEA no Match [^ \t\n\f\r] DIGIT no Match any numeric character using native charset semantics for non-utf8 DIGITL no Match any numeric character in locale DIGITA no Match [0-9] NDIGIT no Match any non-numeric character using native charset i semantics for non-utf8 NDIGITL no Match any non-numeric character in locale NDIGITA no Match [^0-9] CLUMP no Match any extended grapheme cluster sequence # Alternation # BRANCH The set of branches constituting a single choice are hooked # together with their "next" pointers, since precedence prevents # anything being concatenated to any individual branch. The # "next" pointer of the last BRANCH in a choice points to the # thing following the whole choice. This is also where the # final "next" pointer of each individual branch points; each # branch starts with the operand node of a BRANCH node. # BRANCH node Match this alternative, or the next... # Back pointer # BACK Normal "next" pointers all implicitly point forward; BACK # exists to make loop structures possible. # not used BACK no Match "", "next" ptr points backward. # Literals EXACT str Match this string (preceded by length). EXACTF str Match this string, folded, native charset semantics for non-utf8 (prec. by length). EXACTFL str Match this string, folded in locale (w/len). EXACTFU str Match this string, folded, Unicode semantics for non-utf8 (prec. by length). EXACTFA str Match this string, folded, Unicode semantics for non-utf8, but no ASCII-range character matches outside ASCII (prec. by length),. # Do nothing types NOTHING no Match empty string. # A variant of above which delimits a group, thus stops optimizations TAIL no Match empty string. Can jump here from outside. # Loops # STAR,PLUS '?', and complex '*' and '+', are implemented as circular # BRANCH structures using BACK. Simple cases (one character # per match) are implemented with STAR and PLUS for speed # and to minimize recursive plunges. # STAR node Match this (simple) thing 0 or more times. PLUS node Match this (simple) thing 1 or more times. CURLY sv 2 Match this simple thing {n,m} times. CURLYN no 2 Capture next-after-this simple thing CURLYM no 2 Capture this medium-complex thing {n,m} times. CURLYX sv 2 Match this complex thing {n,m} times. # This terminator creates a loop structure for CURLYX WHILEM no Do curly processing and see if rest matches. # Buffer related # OPEN,CLOSE,GROUPP ...are numbered at compile time. OPEN num 1 Mark this point in input as start of #n. CLOSE num 1 Analogous to OPEN. REF num 1 Match some already matched string REFF num 1 Match already matched string, folded using native charset semantics for non-utf8 REFFL num 1 Match already matched string, folded in loc. REFFU num 1 Match already matched string, folded using unicode semantics for non-utf8 REFFA num 1 Match already matched string, folded using unicode semantics for non-utf8, no mixing ASCII, non-ASCII # Named references. Code in regcomp.c assumes that these all are after the # numbered references NREF no-sv 1 Match some already matched string NREFF no-sv 1 Match already matched string, folded using native charset semantics for non-utf8 NREFFL no-sv 1 Match already matched string, folded in loc. NREFFU num 1 Match already matched string, folded using unicode semantics for non-utf8 NREFFA num 1 Match already matched string, folded using unicode semantics for non-utf8, no mixing ASCII, non-ASCII IFMATCH off 1 2 Succeeds if the following matches. UNLESSM off 1 2 Fails if the following matches. SUSPEND off 1 1 "Independent" sub-RE. IFTHEN off 1 1 Switch, should be preceded by switcher. GROUPP num 1 Whether the group matched. # Support for long RE LONGJMP off 1 1 Jump far away. BRANCHJ off 1 1 BRANCH with long offset. # The heavy worker EVAL evl 1 Execute some Perl code. # Modifiers MINMOD no Next operator is not greedy. LOGICAL no Next opcode should set the flag only. # This is not used yet RENUM off 1 1 Group with independently numbered parens. # Trie Related # Behave the same as A|LIST|OF|WORDS would. The '..C' variants have # inline charclass data (ascii only), the 'C' store it in the structure. # NOTE: the relative order of the TRIE-like regops is significant TRIE trie 1 Match many EXACT(F[ALU]?)? at once. flags==type TRIEC charclass Same as TRIE, but with embedded charclass data # For start classes, contains an added fail table. AHOCORASICK trie 1 Aho Corasick stclass. flags==type AHOCORASICKC charclass Same as AHOCORASICK, but with embedded charclass data # Regex Subroutines GOSUB num/ofs 2L recurse to paren arg1 at (signed) ofs arg2 GOSTART no recurse to start of pattern # Special conditionals NGROUPP no-sv 1 Whether the group matched. INSUBP num 1 Whether we are in a specific recurse. DEFINEP none 1 Never execute directly. # Backtracking Verbs ENDLIKE none Used only for the type field of verbs OPFAIL none Same as (?!) ACCEPT parno 1 Accepts the current matched string. # Verbs With Arguments VERB no-sv 1 Used only for the type field of verbs PRUNE no-sv 1 Pattern fails at this startpoint if no-backtracking through this MARKPOINT no-sv 1 Push the current location for rollback by cut. SKIP no-sv 1 On failure skip forward (to the mark) before retrying COMMIT no-sv 1 Pattern fails outright if backtracking through this CUTGROUP no-sv 1 On failure go to the next alternation in the group # Control what to keep in $&. KEEPS no $& begins here. # New charclass like patterns LNBREAK none generic newline pattern VERTWS none vertical whitespace (Perl 6) NVERTWS none not vertical whitespace (Perl 6) HORIZWS none horizontal whitespace (Perl 6) NHORIZWS none not horizontal whitespace (Perl 6) FOLDCHAR codepoint 1 codepoint with tricky case folding properties. # SPECIAL REGOPS # This is not really a node, but an optimized away piece of a "long" node. # To simplify debugging output, we mark it as if it were a node OPTIMIZED off Placeholder for dump. # Special opcode with the property that no opcode in a compiled program # will ever be of this type. Thus it can be used as a flag value that # no other opcode has been seen. END is used similarly, in that an END # node cant be optimized. So END implies "unoptimizable" and PSEUDO mean # "not seen anything to optimize yet". PSEUDO off Pseudo opcode for internal use. =for unprinted-credits Next section M-J. Dominus (mjd-perl-patch+@plover.com) 20010421 Following the optimizer information is a dump of the offset/length table, here split across several lines: Offsets: [45] 1[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 5[1] 0[0] 12[1] 0[0] 6[1] 0[0] 7[1] 0[0] 9[1] 8[1] 0[0] 10[1] 0[0] 11[1] 0[0] 12[0] 12[0] 13[1] 0[0] 14[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 18[1] 0[0] 19[1] 20[0] The first line here indicates that the offset/length table contains 45 entries. Each entry is a pair of integers, denoted by C<offset[length]>. Entries are numbered starting with 1, so entry #1 here is C<1[4]> and entry #12 is C<5[1]>. C<1[4]> indicates that the node labeled C<1:> (the C<1: ANYOF[bc]>) begins at character position 1 in the pre-compiled form of the regex, and has a length of 4 characters. C<5[1]> in position 12 indicates that the node labeled C<12:> (the C<< 12: EXACT <d> >>) begins at character position 5 in the pre-compiled form of the regex, and has a length of 1 character. C<12[1]> in position 14 indicates that the node labeled C<14:> (the C<< 14: CURLYX[0] {1,32767} >>) begins at character position 12 in the pre-compiled form of the regex, and has a length of 1 character---that is, it corresponds to the C<+> symbol in the precompiled regex. C<0[0]> items indicate that there is no corresponding node. =head2 Run-time Output First of all, when doing a match, one may get no run-time output even if debugging is enabled. This means that the regex engine was never entered and that all of the job was therefore done by the optimizer. If the regex engine was entered, the output may look like this: Matching '[bc]d(ef*g)+h[ij]k$' against 'abcdefg__gh__' Setting an EVAL scope, savestack=3 2 <ab> <cdefg__gh_> | 1: ANYOF 3 <abc> <defg__gh_> | 11: EXACT <d> 4 <abcd> <efg__gh_> | 13: CURLYX {1,32767} 4 <abcd> <efg__gh_> | 26: WHILEM 0 out of 1..32767 cc=effff31c 4 <abcd> <efg__gh_> | 15: OPEN1 4 <abcd> <efg__gh_> | 17: EXACT <e> 5 <abcde> <fg__gh_> | 19: STAR EXACT <f> can match 1 times out of 32767... Setting an EVAL scope, savestack=3 6 <bcdef> <g__gh__> | 22: EXACT <g> 7 <bcdefg> <__gh__> | 24: CLOSE1 7 <bcdefg> <__gh__> | 26: WHILEM 1 out of 1..32767 cc=effff31c Setting an EVAL scope, savestack=12 7 <bcdefg> <__gh__> | 15: OPEN1 7 <bcdefg> <__gh__> | 17: EXACT <e> restoring \1 to 4(4)..7 failed, try continuation... 7 <bcdefg> <__gh__> | 27: NOTHING 7 <bcdefg> <__gh__> | 28: EXACT <h> failed... failed... The most significant information in the output is about the particular I<node> of the compiled regex that is currently being tested against the target string. The format of these lines is C< >I<STRING-OFFSET> <I<PRE-STRING>> <I<POST-STRING>> |I<ID>: I<TYPE> The I<TYPE> info is indented with respect to the backtracking level. Other incidental information appears interspersed within. =head1 Debugging Perl Memory Usage Perl is a profligate wastrel when it comes to memory use. There is a saying that to estimate memory usage of Perl, assume a reasonable algorithm for memory allocation, multiply that estimate by 10, and while you still may miss the mark, at least you won't be quite so astonished. This is not absolutely true, but may provide a good grasp of what happens. Assume that an integer cannot take less than 20 bytes of memory, a float cannot take less than 24 bytes, a string cannot take less than 32 bytes (all these examples assume 32-bit architectures, the result are quite a bit worse on 64-bit architectures). If a variable is accessed in two of three different ways (which require an integer, a float, or a string), the memory footprint may increase yet another 20 bytes. A sloppy malloc(3) implementation can inflate these numbers dramatically. On the opposite end of the scale, a declaration like sub foo; may take up to 500 bytes of memory, depending on which release of Perl you're running. Anecdotal estimates of source-to-compiled code bloat suggest an eightfold increase. This means that the compiled form of reasonable (normally commented, properly indented etc.) code will take about eight times more space in memory than the code took on disk. The B<-DL> command-line switch is obsolete since circa Perl 5.6.0 (it was available only if Perl was built with C<-DDEBUGGING>). The switch was used to track Perl's memory allocations and possible memory leaks. These days the use of malloc debugging tools like F<Purify> or F<valgrind> is suggested instead. See also L<perlhacktips/PERL_MEM_LOG>. One way to find out how much memory is being used by Perl data structures is to install the Devel::Size module from CPAN: it gives you the minimum number of bytes required to store a particular data structure. Please be mindful of the difference between the size() and total_size(). If Perl has been compiled using Perl's malloc you can analyze Perl memory usage by setting $ENV{PERL_DEBUG_MSTATS}. =head2 Using C<$ENV{PERL_DEBUG_MSTATS}> If your perl is using Perl's malloc() and was compiled with the necessary switches (this is the default), then it will print memory usage statistics after compiling your code when C<< $ENV{PERL_DEBUG_MSTATS} > 1 >>, and before termination of the program when C<< $ENV{PERL_DEBUG_MSTATS} >= 1 >>. The report format is similar to the following example: $ PERL_DEBUG_MSTATS=2 perl -e "require Carp" Memory allocation statistics after compilation: (buckets 4(4)..8188(8192) 14216 free: 130 117 28 7 9 0 2 2 1 0 0 437 61 36 0 5 60924 used: 125 137 161 55 7 8 6 16 2 0 1 74 109 304 84 20 Total sbrk(): 77824/21:119. Odd ends: pad+heads+chain+tail: 0+636+0+2048. Memory allocation statistics after execution: (buckets 4(4)..8188(8192) 30888 free: 245 78 85 13 6 2 1 3 2 0 1 315 162 39 42 11 175816 used: 265 176 1112 111 26 22 11 27 2 1 1 196 178 1066 798 39 Total sbrk(): 215040/47:145. Odd ends: pad+heads+chain+tail: 0+2192+0+6144. It is possible to ask for such a statistic at arbitrary points in your execution using the mstat() function out of the standard Devel::Peek module. Here is some explanation of that format: =over 4 =item C<buckets SMALLEST(APPROX)..GREATEST(APPROX)> Perl's malloc() uses bucketed allocations. Every request is rounded up to the closest bucket size available, and a bucket is taken from the pool of buckets of that size. The line above describes the limits of buckets currently in use. Each bucket has two sizes: memory footprint and the maximal size of user data that can fit into this bucket. Suppose in the above example that the smallest bucket were size 4. The biggest bucket would have usable size 8188, and the memory footprint would be 8192. In a Perl built for debugging, some buckets may have negative usable size. This means that these buckets cannot (and will not) be used. For larger buckets, the memory footprint may be one page greater than a power of 2. If so, the corresponding power of two is printed in the C<APPROX> field above. =item Free/Used The 1 or 2 rows of numbers following that correspond to the number of buckets of each size between C<SMALLEST> and C<GREATEST>. In the first row, the sizes (memory footprints) of buckets are powers of two--or possibly one page greater. In the second row, if present, the memory footprints of the buckets are between the memory footprints of two buckets "above". For example, suppose under the previous example, the memory footprints were free: 8 16 32 64 128 256 512 1024 2048 4096 8192 4 12 24 48 80 With a non-C<DEBUGGING> perl, the buckets starting from C<128> have a 4-byte overhead, and thus an 8192-long bucket may take up to 8188-byte allocations. =item C<Total sbrk(): SBRKed/SBRKs:CONTINUOUS> The first two fields give the total amount of memory perl sbrk(2)ed (ess-broken? :-) and number of sbrk(2)s used. The third number is what perl thinks about continuity of returned chunks. So long as this number is positive, malloc() will assume that it is probable that sbrk(2) will provide continuous memory. Memory allocated by external libraries is not counted. =item C<pad: 0> The amount of sbrk(2)ed memory needed to keep buckets aligned. =item C<heads: 2192> Although memory overhead of bigger buckets is kept inside the bucket, for smaller buckets, it is kept in separate areas. This field gives the total size of these areas. =item C<chain: 0> malloc() may want to subdivide a bigger bucket into smaller buckets. If only a part of the deceased bucket is left unsubdivided, the rest is kept as an element of a linked list. This field gives the total size of these chunks. =item C<tail: 6144> To minimize the number of sbrk(2)s, malloc() asks for more memory. This field gives the size of the yet unused part, which is sbrk(2)ed, but never touched. =back =head1 SEE ALSO L<perldebug>, L<perlguts>, L<perlrun> L<re>, and L<Devel::DProf>. PK PU�\�B�� �� perlthrtut.podnu �[��� =encoding utf8 =head1 NAME perlthrtut - Tutorial on threads in Perl =head1 DESCRIPTION This tutorial describes the use of Perl interpreter threads (sometimes referred to as I<ithreads>) that was first introduced in Perl 5.6.0. In this model, each thread runs in its own Perl interpreter, and any data sharing between threads must be explicit. The user-level interface for I<ithreads> uses the L<threads> class. B<NOTE>: There was another older Perl threading flavor called the 5.005 model that used the L<threads> class. This old model was known to have problems, is deprecated, and was removed for release 5.10. You are strongly encouraged to migrate any existing 5.005 threads code to the new model as soon as possible. You can see which (or neither) threading flavour you have by running C<perl -V> and looking at the C<Platform> section. If you have C<useithreads=define> you have ithreads, if you have C<use5005threads=define> you have 5.005 threads. If you have neither, you don't have any thread support built in. If you have both, you are in trouble. The L<threads> and L<threads::shared> modules are included in the core Perl distribution. Additionally, they are maintained as a separate modules on CPAN, so you can check there for any updates. =head1 What Is A Thread Anyway? A thread is a flow of control through a program with a single execution point. Sounds an awful lot like a process, doesn't it? Well, it should. Threads are one of the pieces of a process. Every process has at least one thread and, up until now, every process running Perl had only one thread. With 5.8, though, you can create extra threads. We're going to show you how, when, and why. =head1 Threaded Program Models There are three basic ways that you can structure a threaded program. Which model you choose depends on what you need your program to do. For many non-trivial threaded programs, you'll need to choose different models for different pieces of your program. =head2 Boss/Worker The boss/worker model usually has one I<boss> thread and one or more I<worker> threads. The boss thread gathers or generates tasks that need to be done, then parcels those tasks out to the appropriate worker thread. This model is common in GUI and server programs, where a main thread waits for some event and then passes that event to the appropriate worker threads for processing. Once the event has been passed on, the boss thread goes back to waiting for another event. The boss thread does relatively little work. While tasks aren't necessarily performed faster than with any other method, it tends to have the best user-response times. =head2 Work Crew In the work crew model, several threads are created that do essentially the same thing to different pieces of data. It closely mirrors classical parallel processing and vector processors, where a large array of processors do the exact same thing to many pieces of data. This model is particularly useful if the system running the program will distribute multiple threads across different processors. It can also be useful in ray tracing or rendering engines, where the individual threads can pass on interim results to give the user visual feedback. =head2 Pipeline The pipeline model divides up a task into a series of steps, and passes the results of one step on to the thread processing the next. Each thread does one thing to each piece of data and passes the results to the next thread in line. This model makes the most sense if you have multiple processors so two or more threads will be executing in parallel, though it can often make sense in other contexts as well. It tends to keep the individual tasks small and simple, as well as allowing some parts of the pipeline to block (on I/O or system calls, for example) while other parts keep going. If you're running different parts of the pipeline on different processors you may also take advantage of the caches on each processor. This model is also handy for a form of recursive programming where, rather than having a subroutine call itself, it instead creates another thread. Prime and Fibonacci generators both map well to this form of the pipeline model. (A version of a prime number generator is presented later on.) =head1 What kind of threads are Perl threads? If you have experience with other thread implementations, you might find that things aren't quite what you expect. It's very important to remember when dealing with Perl threads that I<Perl Threads Are Not X Threads> for all values of X. They aren't POSIX threads, or DecThreads, or Java's Green threads, or Win32 threads. There are similarities, and the broad concepts are the same, but if you start looking for implementation details you're going to be either disappointed or confused. Possibly both. This is not to say that Perl threads are completely different from everything that's ever come before. They're not. Perl's threading model owes a lot to other thread models, especially POSIX. Just as Perl is not C, though, Perl threads are not POSIX threads. So if you find yourself looking for mutexes, or thread priorities, it's time to step back a bit and think about what you want to do and how Perl can do it. However, it is important to remember that Perl threads cannot magically do things unless your operating system's threads allow it. So if your system blocks the entire process on C<sleep()>, Perl usually will, as well. B<Perl Threads Are Different.> =head1 Thread-Safe Modules The addition of threads has changed Perl's internals substantially. There are implications for people who write modules with XS code or external libraries. However, since Perl data is not shared among threads by default, Perl modules stand a high chance of being thread-safe or can be made thread-safe easily. Modules that are not tagged as thread-safe should be tested or code reviewed before being used in production code. Not all modules that you might use are thread-safe, and you should always assume a module is unsafe unless the documentation says otherwise. This includes modules that are distributed as part of the core. Threads are a relatively new feature, and even some of the standard modules aren't thread-safe. Even if a module is thread-safe, it doesn't mean that the module is optimized to work well with threads. A module could possibly be rewritten to utilize the new features in threaded Perl to increase performance in a threaded environment. If you're using a module that's not thread-safe for some reason, you can protect yourself by using it from one, and only one thread at all. If you need multiple threads to access such a module, you can use semaphores and lots of programming discipline to control access to it. Semaphores are covered in L</"Basic semaphores">. See also L</"Thread-Safety of System Libraries">. =head1 Thread Basics The L<threads> module provides the basic functions you need to write threaded programs. In the following sections, we'll cover the basics, showing you what you need to do to create a threaded program. After that, we'll go over some of the features of the L<threads> module that make threaded programming easier. =head2 Basic Thread Support Thread support is a Perl compile-time option. It's something that's turned on or off when Perl is built at your site, rather than when your programs are compiled. If your Perl wasn't compiled with thread support enabled, then any attempt to use threads will fail. Your programs can use the Config module to check whether threads are enabled. If your program can't run without them, you can say something like: use Config; $Config{useithreads} or die('Recompile Perl with threads to run this program.'); A possibly-threaded program using a possibly-threaded module might have code like this: use Config; use MyMod; BEGIN { if ($Config{useithreads}) { # We have threads require MyMod_threaded; import MyMod_threaded; } else { require MyMod_unthreaded; import MyMod_unthreaded; } } Since code that runs both with and without threads is usually pretty messy, it's best to isolate the thread-specific code in its own module. In our example above, that's what C<MyMod_threaded> is, and it's only imported if we're running on a threaded Perl. =head2 A Note about the Examples In a real situation, care should be taken that all threads are finished executing before the program exits. That care has B<not> been taken in these examples in the interest of simplicity. Running these examples I<as is> will produce error messages, usually caused by the fact that there are still threads running when the program exits. You should not be alarmed by this. =head2 Creating Threads The L<threads> module provides the tools you need to create new threads. Like any other module, you need to tell Perl that you want to use it; C<use threads;> imports all the pieces you need to create basic threads. The simplest, most straightforward way to create a thread is with C<create()>: use threads; my $thr = threads->create(\&sub1); sub sub1 { print("In the thread\n"); } The C<create()> method takes a reference to a subroutine and creates a new thread that starts executing in the referenced subroutine. Control then passes both to the subroutine and the caller. If you need to, your program can pass parameters to the subroutine as part of the thread startup. Just include the list of parameters as part of the C<threads-E<gt>create()> call, like this: use threads; my $Param3 = 'foo'; my $thr1 = threads->create(\&sub1, 'Param 1', 'Param 2', $Param3); my @ParamList = (42, 'Hello', 3.14); my $thr2 = threads->create(\&sub1, @ParamList); my $thr3 = threads->create(\&sub1, qw(Param1 Param2 Param3)); sub sub1 { my @InboundParameters = @_; print("In the thread\n"); print('Got parameters >', join('<>', @InboundParameters), "<\n"); } The last example illustrates another feature of threads. You can spawn off several threads using the same subroutine. Each thread executes the same subroutine, but in a separate thread with a separate environment and potentially separate arguments. C<new()> is a synonym for C<create()>. =head2 Waiting For A Thread To Exit Since threads are also subroutines, they can return values. To wait for a thread to exit and extract any values it might return, you can use the C<join()> method: use threads; my ($thr) = threads->create(\&sub1); my @ReturnData = $thr->join(); print('Thread returned ', join(', ', @ReturnData), "\n"); sub sub1 { return ('Fifty-six', 'foo', 2); } In the example above, the C<join()> method returns as soon as the thread ends. In addition to waiting for a thread to finish and gathering up any values that the thread might have returned, C<join()> also performs any OS cleanup necessary for the thread. That cleanup might be important, especially for long-running programs that spawn lots of threads. If you don't want the return values and don't want to wait for the thread to finish, you should call the C<detach()> method instead, as described next. NOTE: In the example above, the thread returns a list, thus necessitating that the thread creation call be made in list context (i.e., C<my ($thr)>). See L<< threads/"$thr->join()" >> and L<threads/"THREAD CONTEXT"> for more details on thread context and return values. =head2 Ignoring A Thread C<join()> does three things: it waits for a thread to exit, cleans up after it, and returns any data the thread may have produced. But what if you're not interested in the thread's return values, and you don't really care when the thread finishes? All you want is for the thread to get cleaned up after when it's done. In this case, you use the C<detach()> method. Once a thread is detached, it'll run until it's finished; then Perl will clean up after it automatically. use threads; my $thr = threads->create(\&sub1); # Spawn the thread $thr->detach(); # Now we officially don't care any more sleep(15); # Let thread run for awhile sub sub1 { $a = 0; while (1) { $a++; print("\$a is $a\n"); sleep(1); } } Once a thread is detached, it may not be joined, and any return data that it might have produced (if it was done and waiting for a join) is lost. C<detach()> can also be called as a class method to allow a thread to detach itself: use threads; my $thr = threads->create(\&sub1); sub sub1 { threads->detach(); # Do more work } =head2 Process and Thread Termination With threads one must be careful to make sure they all have a chance to run to completion, assuming that is what you want. An action that terminates a process will terminate I<all> running threads. die() and exit() have this property, and perl does an exit when the main thread exits, perhaps implicitly by falling off the end of your code, even if that's not what you want. As an example of this case, this code prints the message "Perl exited with active threads: 2 running and unjoined": use threads; my $thr1 = threads->new(\&thrsub, "test1"); my $thr2 = threads->new(\&thrsub, "test2"); sub thrsub { my ($message) = @_; sleep 1; print "thread $message\n"; } But when the following lines are added at the end: $thr1->join(); $thr2->join(); it prints two lines of output, a perhaps more useful outcome. =head1 Threads And Data Now that we've covered the basics of threads, it's time for our next topic: Data. Threading introduces a couple of complications to data access that non-threaded programs never need to worry about. =head2 Shared And Unshared Data The biggest difference between Perl I<ithreads> and the old 5.005 style threading, or for that matter, to most other threading systems out there, is that by default, no data is shared. When a new Perl thread is created, all the data associated with the current thread is copied to the new thread, and is subsequently private to that new thread! This is similar in feel to what happens when a Unix process forks, except that in this case, the data is just copied to a different part of memory within the same process rather than a real fork taking place. To make use of threading, however, one usually wants the threads to share at least some data between themselves. This is done with the L<threads::shared> module and the C<:shared> attribute: use threads; use threads::shared; my $foo :shared = 1; my $bar = 1; threads->create(sub { $foo++; $bar++; })->join(); print("$foo\n"); # Prints 2 since $foo is shared print("$bar\n"); # Prints 1 since $bar is not shared In the case of a shared array, all the array's elements are shared, and for a shared hash, all the keys and values are shared. This places restrictions on what may be assigned to shared array and hash elements: only simple values or references to shared variables are allowed - this is so that a private variable can't accidentally become shared. A bad assignment will cause the thread to die. For example: use threads; use threads::shared; my $var = 1; my $svar :shared = 2; my %hash :shared; ... create some threads ... $hash{a} = 1; # All threads see exists($hash{a}) and $hash{a} == 1 $hash{a} = $var; # okay - copy-by-value: same effect as previous $hash{a} = $svar; # okay - copy-by-value: same effect as previous $hash{a} = \$svar; # okay - a reference to a shared variable $hash{a} = \$var; # This will die delete($hash{a}); # okay - all threads will see !exists($hash{a}) Note that a shared variable guarantees that if two or more threads try to modify it at the same time, the internal state of the variable will not become corrupted. However, there are no guarantees beyond this, as explained in the next section. =head2 Thread Pitfalls: Races While threads bring a new set of useful tools, they also bring a number of pitfalls. One pitfall is the race condition: use threads; use threads::shared; my $a :shared = 1; my $thr1 = threads->create(\&sub1); my $thr2 = threads->create(\&sub2); $thr1->join(); $thr2->join(); print("$a\n"); sub sub1 { my $foo = $a; $a = $foo + 1; } sub sub2 { my $bar = $a; $a = $bar + 1; } What do you think C<$a> will be? The answer, unfortunately, is I<it depends>. Both C<sub1()> and C<sub2()> access the global variable C<$a>, once to read and once to write. Depending on factors ranging from your thread implementation's scheduling algorithm to the phase of the moon, C<$a> can be 2 or 3. Race conditions are caused by unsynchronized access to shared data. Without explicit synchronization, there's no way to be sure that nothing has happened to the shared data between the time you access it and the time you update it. Even this simple code fragment has the possibility of error: use threads; my $a :shared = 2; my $b :shared; my $c :shared; my $thr1 = threads->create(sub { $b = $a; $a = $b + 1; }); my $thr2 = threads->create(sub { $c = $a; $a = $c + 1; }); $thr1->join(); $thr2->join(); Two threads both access C<$a>. Each thread can potentially be interrupted at any point, or be executed in any order. At the end, C<$a> could be 3 or 4, and both C<$b> and C<$c> could be 2 or 3. Even C<$a += 5> or C<$a++> are not guaranteed to be atomic. Whenever your program accesses data or resources that can be accessed by other threads, you must take steps to coordinate access or risk data inconsistency and race conditions. Note that Perl will protect its internals from your race conditions, but it won't protect you from you. =head1 Synchronization and control Perl provides a number of mechanisms to coordinate the interactions between themselves and their data, to avoid race conditions and the like. Some of these are designed to resemble the common techniques used in thread libraries such as C<pthreads>; others are Perl-specific. Often, the standard techniques are clumsy and difficult to get right (such as condition waits). Where possible, it is usually easier to use Perlish techniques such as queues, which remove some of the hard work involved. =head2 Controlling access: lock() The C<lock()> function takes a shared variable and puts a lock on it. No other thread may lock the variable until the variable is unlocked by the thread holding the lock. Unlocking happens automatically when the locking thread exits the block that contains the call to the C<lock()> function. Using C<lock()> is straightforward: This example has several threads doing some calculations in parallel, and occasionally updating a running total: use threads; use threads::shared; my $total :shared = 0; sub calc { while (1) { my $result; # (... do some calculations and set $result ...) { lock($total); # Block until we obtain the lock $total += $result; } # Lock implicitly released at end of scope last if $result == 0; } } my $thr1 = threads->create(\&calc); my $thr2 = threads->create(\&calc); my $thr3 = threads->create(\&calc); $thr1->join(); $thr2->join(); $thr3->join(); print("total=$total\n"); C<lock()> blocks the thread until the variable being locked is available. When C<lock()> returns, your thread can be sure that no other thread can lock that variable until the block containing the lock exits. It's important to note that locks don't prevent access to the variable in question, only lock attempts. This is in keeping with Perl's longstanding tradition of courteous programming, and the advisory file locking that C<flock()> gives you. You may lock arrays and hashes as well as scalars. Locking an array, though, will not block subsequent locks on array elements, just lock attempts on the array itself. Locks are recursive, which means it's okay for a thread to lock a variable more than once. The lock will last until the outermost C<lock()> on the variable goes out of scope. For example: my $x :shared; doit(); sub doit { { { lock($x); # Wait for lock lock($x); # NOOP - we already have the lock { lock($x); # NOOP { lock($x); # NOOP lockit_some_more(); } } } # *** Implicit unlock here *** } } sub lockit_some_more { lock($x); # NOOP } # Nothing happens here Note that there is no C<unlock()> function - the only way to unlock a variable is to allow it to go out of scope. A lock can either be used to guard the data contained within the variable being locked, or it can be used to guard something else, like a section of code. In this latter case, the variable in question does not hold any useful data, and exists only for the purpose of being locked. In this respect, the variable behaves like the mutexes and basic semaphores of traditional thread libraries. =head2 A Thread Pitfall: Deadlocks Locks are a handy tool to synchronize access to data, and using them properly is the key to safe shared data. Unfortunately, locks aren't without their dangers, especially when multiple locks are involved. Consider the following code: use threads; my $a :shared = 4; my $b :shared = 'foo'; my $thr1 = threads->create(sub { lock($a); sleep(20); lock($b); }); my $thr2 = threads->create(sub { lock($b); sleep(20); lock($a); }); This program will probably hang until you kill it. The only way it won't hang is if one of the two threads acquires both locks first. A guaranteed-to-hang version is more complicated, but the principle is the same. The first thread will grab a lock on C<$a>, then, after a pause during which the second thread has probably had time to do some work, try to grab a lock on C<$b>. Meanwhile, the second thread grabs a lock on C<$b>, then later tries to grab a lock on C<$a>. The second lock attempt for both threads will block, each waiting for the other to release its lock. This condition is called a deadlock, and it occurs whenever two or more threads are trying to get locks on resources that the others own. Each thread will block, waiting for the other to release a lock on a resource. That never happens, though, since the thread with the resource is itself waiting for a lock to be released. There are a number of ways to handle this sort of problem. The best way is to always have all threads acquire locks in the exact same order. If, for example, you lock variables C<$a>, C<$b>, and C<$c>, always lock C<$a> before C<$b>, and C<$b> before C<$c>. It's also best to hold on to locks for as short a period of time to minimize the risks of deadlock. The other synchronization primitives described below can suffer from similar problems. =head2 Queues: Passing Data Around A queue is a special thread-safe object that lets you put data in one end and take it out the other without having to worry about synchronization issues. They're pretty straightforward, and look like this: use threads; use Thread::Queue; my $DataQueue = Thread::Queue->new(); my $thr = threads->create(sub { while (my $DataElement = $DataQueue->dequeue()) { print("Popped $DataElement off the queue\n"); } }); $DataQueue->enqueue(12); $DataQueue->enqueue("A", "B", "C"); sleep(10); $DataQueue->enqueue(undef); $thr->join(); You create the queue with C<Thread::Queue-E<gt>new()>. Then you can add lists of scalars onto the end with C<enqueue()>, and pop scalars off the front of it with C<dequeue()>. A queue has no fixed size, and can grow as needed to hold everything pushed on to it. If a queue is empty, C<dequeue()> blocks until another thread enqueues something. This makes queues ideal for event loops and other communications between threads. =head2 Semaphores: Synchronizing Data Access Semaphores are a kind of generic locking mechanism. In their most basic form, they behave very much like lockable scalars, except that they can't hold data, and that they must be explicitly unlocked. In their advanced form, they act like a kind of counter, and can allow multiple threads to have the I<lock> at any one time. =head2 Basic semaphores Semaphores have two methods, C<down()> and C<up()>: C<down()> decrements the resource count, while C<up()> increments it. Calls to C<down()> will block if the semaphore's current count would decrement below zero. This program gives a quick demonstration: use threads; use Thread::Semaphore; my $semaphore = Thread::Semaphore->new(); my $GlobalVariable :shared = 0; $thr1 = threads->create(\&sample_sub, 1); $thr2 = threads->create(\&sample_sub, 2); $thr3 = threads->create(\&sample_sub, 3); sub sample_sub { my $SubNumber = shift(@_); my $TryCount = 10; my $LocalCopy; sleep(1); while ($TryCount--) { $semaphore->down(); $LocalCopy = $GlobalVariable; print("$TryCount tries left for sub $SubNumber (\$GlobalVariable is $GlobalVariable)\n"); sleep(2); $LocalCopy++; $GlobalVariable = $LocalCopy; $semaphore->up(); } } $thr1->join(); $thr2->join(); $thr3->join(); The three invocations of the subroutine all operate in sync. The semaphore, though, makes sure that only one thread is accessing the global variable at once. =head2 Advanced Semaphores By default, semaphores behave like locks, letting only one thread C<down()> them at a time. However, there are other uses for semaphores. Each semaphore has a counter attached to it. By default, semaphores are created with the counter set to one, C<down()> decrements the counter by one, and C<up()> increments by one. However, we can override any or all of these defaults simply by passing in different values: use threads; use Thread::Semaphore; my $semaphore = Thread::Semaphore->new(5); # Creates a semaphore with the counter set to five my $thr1 = threads->create(\&sub1); my $thr2 = threads->create(\&sub1); sub sub1 { $semaphore->down(5); # Decrements the counter by five # Do stuff here $semaphore->up(5); # Increment the counter by five } $thr1->detach(); $thr2->detach(); If C<down()> attempts to decrement the counter below zero, it blocks until the counter is large enough. Note that while a semaphore can be created with a starting count of zero, any C<up()> or C<down()> always changes the counter by at least one, and so C<< $semaphore->down(0) >> is the same as C<< $semaphore->down(1) >>. The question, of course, is why would you do something like this? Why create a semaphore with a starting count that's not one, or why decrement or increment it by more than one? The answer is resource availability. Many resources that you want to manage access for can be safely used by more than one thread at once. For example, let's take a GUI driven program. It has a semaphore that it uses to synchronize access to the display, so only one thread is ever drawing at once. Handy, but of course you don't want any thread to start drawing until things are properly set up. In this case, you can create a semaphore with a counter set to zero, and up it when things are ready for drawing. Semaphores with counters greater than one are also useful for establishing quotas. Say, for example, that you have a number of threads that can do I/O at once. You don't want all the threads reading or writing at once though, since that can potentially swamp your I/O channels, or deplete your process's quota of filehandles. You can use a semaphore initialized to the number of concurrent I/O requests (or open files) that you want at any one time, and have your threads quietly block and unblock themselves. Larger increments or decrements are handy in those cases where a thread needs to check out or return a number of resources at once. =head2 Waiting for a Condition The functions C<cond_wait()> and C<cond_signal()> can be used in conjunction with locks to notify co-operating threads that a resource has become available. They are very similar in use to the functions found in C<pthreads>. However for most purposes, queues are simpler to use and more intuitive. See L<threads::shared> for more details. =head2 Giving up control There are times when you may find it useful to have a thread explicitly give up the CPU to another thread. You may be doing something processor-intensive and want to make sure that the user-interface thread gets called frequently. Regardless, there are times that you might want a thread to give up the processor. Perl's threading package provides the C<yield()> function that does this. C<yield()> is pretty straightforward, and works like this: use threads; sub loop { my $thread = shift; my $foo = 50; while($foo--) { print("In thread $thread\n"); } threads->yield(); $foo = 50; while($foo--) { print("In thread $thread\n"); } } my $thr1 = threads->create(\&loop, 'first'); my $thr2 = threads->create(\&loop, 'second'); my $thr3 = threads->create(\&loop, 'third'); It is important to remember that C<yield()> is only a hint to give up the CPU, it depends on your hardware, OS and threading libraries what actually happens. B<On many operating systems, yield() is a no-op.> Therefore it is important to note that one should not build the scheduling of the threads around C<yield()> calls. It might work on your platform but it won't work on another platform. =head1 General Thread Utility Routines We've covered the workhorse parts of Perl's threading package, and with these tools you should be well on your way to writing threaded code and packages. There are a few useful little pieces that didn't really fit in anyplace else. =head2 What Thread Am I In? The C<threads-E<gt>self()> class method provides your program with a way to get an object representing the thread it's currently in. You can use this object in the same way as the ones returned from thread creation. =head2 Thread IDs C<tid()> is a thread object method that returns the thread ID of the thread the object represents. Thread IDs are integers, with the main thread in a program being 0. Currently Perl assigns a unique TID to every thread ever created in your program, assigning the first thread to be created a TID of 1, and increasing the TID by 1 for each new thread that's created. When used as a class method, C<threads-E<gt>tid()> can be used by a thread to get its own TID. =head2 Are These Threads The Same? The C<equal()> method takes two thread objects and returns true if the objects represent the same thread, and false if they don't. Thread objects also have an overloaded C<==> comparison so that you can do comparison on them as you would with normal objects. =head2 What Threads Are Running? C<threads-E<gt>list()> returns a list of thread objects, one for each thread that's currently running and not detached. Handy for a number of things, including cleaning up at the end of your program (from the main Perl thread, of course): # Loop through all the threads foreach my $thr (threads->list()) { $thr->join(); } If some threads have not finished running when the main Perl thread ends, Perl will warn you about it and die, since it is impossible for Perl to clean up itself while other threads are running. NOTE: The main Perl thread (thread 0) is in a I<detached> state, and so does not appear in the list returned by C<threads-E<gt>list()>. =head1 A Complete Example Confused yet? It's time for an example program to show some of the things we've covered. This program finds prime numbers using threads. 1 #!/usr/bin/perl 2 # prime-pthread, courtesy of Tom Christiansen 3 4 use strict; 5 use warnings; 6 7 use threads; 8 use Thread::Queue; 9 10 sub check_num { 11 my ($upstream, $cur_prime) = @_; 12 my $kid; 13 my $downstream = Thread::Queue->new(); 14 while (my $num = $upstream->dequeue()) { 15 next unless ($num % $cur_prime); 16 if ($kid) { 17 $downstream->enqueue($num); 18 } else { 19 print("Found prime: $num\n"); 20 $kid = threads->create(\&check_num, $downstream, $num); 21 if (! $kid) { 22 warn("Sorry. Ran out of threads.\n"); 23 last; 24 } 25 } 26 } 27 if ($kid) { 28 $downstream->enqueue(undef); 29 $kid->join(); 30 } 31 } 32 33 my $stream = Thread::Queue->new(3..1000, undef); 34 check_num($stream, 2); This program uses the pipeline model to generate prime numbers. Each thread in the pipeline has an input queue that feeds numbers to be checked, a prime number that it's responsible for, and an output queue into which it funnels numbers that have failed the check. If the thread has a number that's failed its check and there's no child thread, then the thread must have found a new prime number. In that case, a new child thread is created for that prime and stuck on the end of the pipeline. This probably sounds a bit more confusing than it really is, so let's go through this program piece by piece and see what it does. (For those of you who might be trying to remember exactly what a prime number is, it's a number that's only evenly divisible by itself and 1.) The bulk of the work is done by the C<check_num()> subroutine, which takes a reference to its input queue and a prime number that it's responsible for. After pulling in the input queue and the prime that the subroutine is checking (line 11), we create a new queue (line 13) and reserve a scalar for the thread that we're likely to create later (line 12). The while loop from line 14 to line 26 grabs a scalar off the input queue and checks against the prime this thread is responsible for. Line 15 checks to see if there's a remainder when we divide the number to be checked by our prime. If there is one, the number must not be evenly divisible by our prime, so we need to either pass it on to the next thread if we've created one (line 17) or create a new thread if we haven't. The new thread creation is line 20. We pass on to it a reference to the queue we've created, and the prime number we've found. In lines 21 through 24, we check to make sure that our new thread got created, and if not, we stop checking any remaining numbers in the queue. Finally, once the loop terminates (because we got a 0 or C<undef> in the queue, which serves as a note to terminate), we pass on the notice to our child, and wait for it to exit if we've created a child (lines 27 and 30). Meanwhile, back in the main thread, we first create a queue (line 33) and queue up all the numbers from 3 to 1000 for checking, plus a termination notice. Then all we have to do to get the ball rolling is pass the queue and the first prime to the C<check_num()> subroutine (line 34). That's how it works. It's pretty simple; as with many Perl programs, the explanation is much longer than the program. =head1 Different implementations of threads Some background on thread implementations from the operating system viewpoint. There are three basic categories of threads: user-mode threads, kernel threads, and multiprocessor kernel threads. User-mode threads are threads that live entirely within a program and its libraries. In this model, the OS knows nothing about threads. As far as it's concerned, your process is just a process. This is the easiest way to implement threads, and the way most OSes start. The big disadvantage is that, since the OS knows nothing about threads, if one thread blocks they all do. Typical blocking activities include most system calls, most I/O, and things like C<sleep()>. Kernel threads are the next step in thread evolution. The OS knows about kernel threads, and makes allowances for them. The main difference between a kernel thread and a user-mode thread is blocking. With kernel threads, things that block a single thread don't block other threads. This is not the case with user-mode threads, where the kernel blocks at the process level and not the thread level. This is a big step forward, and can give a threaded program quite a performance boost over non-threaded programs. Threads that block performing I/O, for example, won't block threads that are doing other things. Each process still has only one thread running at once, though, regardless of how many CPUs a system might have. Since kernel threading can interrupt a thread at any time, they will uncover some of the implicit locking assumptions you may make in your program. For example, something as simple as C<$a = $a + 2> can behave unpredictably with kernel threads if C<$a> is visible to other threads, as another thread may have changed C<$a> between the time it was fetched on the right hand side and the time the new value is stored. Multiprocessor kernel threads are the final step in thread support. With multiprocessor kernel threads on a machine with multiple CPUs, the OS may schedule two or more threads to run simultaneously on different CPUs. This can give a serious performance boost to your threaded program, since more than one thread will be executing at the same time. As a tradeoff, though, any of those nagging synchronization issues that might not have shown with basic kernel threads will appear with a vengeance. In addition to the different levels of OS involvement in threads, different OSes (and different thread implementations for a particular OS) allocate CPU cycles to threads in different ways. Cooperative multitasking systems have running threads give up control if one of two things happen. If a thread calls a yield function, it gives up control. It also gives up control if the thread does something that would cause it to block, such as perform I/O. In a cooperative multitasking implementation, one thread can starve all the others for CPU time if it so chooses. Preemptive multitasking systems interrupt threads at regular intervals while the system decides which thread should run next. In a preemptive multitasking system, one thread usually won't monopolize the CPU. On some systems, there can be cooperative and preemptive threads running simultaneously. (Threads running with realtime priorities often behave cooperatively, for example, while threads running at normal priorities behave preemptively.) Most modern operating systems support preemptive multitasking nowadays. =head1 Performance considerations The main thing to bear in mind when comparing Perl's I<ithreads> to other threading models is the fact that for each new thread created, a complete copy of all the variables and data of the parent thread has to be taken. Thus, thread creation can be quite expensive, both in terms of memory usage and time spent in creation. The ideal way to reduce these costs is to have a relatively short number of long-lived threads, all created fairly early on (before the base thread has accumulated too much data). Of course, this may not always be possible, so compromises have to be made. However, after a thread has been created, its performance and extra memory usage should be little different than ordinary code. Also note that under the current implementation, shared variables use a little more memory and are a little slower than ordinary variables. =head1 Process-scope Changes Note that while threads themselves are separate execution threads and Perl data is thread-private unless explicitly shared, the threads can affect process-scope state, affecting all the threads. The most common example of this is changing the current working directory using C<chdir()>. One thread calls C<chdir()>, and the working directory of all the threads changes. Even more drastic example of a process-scope change is C<chroot()>: the root directory of all the threads changes, and no thread can undo it (as opposed to C<chdir()>). Further examples of process-scope changes include C<umask()> and changing uids and gids. Thinking of mixing C<fork()> and threads? Please lie down and wait until the feeling passes. Be aware that the semantics of C<fork()> vary between platforms. For example, some Unix systems copy all the current threads into the child process, while others only copy the thread that called C<fork()>. You have been warned! Similarly, mixing signals and threads may be problematic. Implementations are platform-dependent, and even the POSIX semantics may not be what you expect (and Perl doesn't even give you the full POSIX API). For example, there is no way to guarantee that a signal sent to a multi-threaded Perl application will get intercepted by any particular thread. (However, a recently added feature does provide the capability to send signals between threads. See L<threads/THREAD SIGNALLING> for more details.) =head1 Thread-Safety of System Libraries Whether various library calls are thread-safe is outside the control of Perl. Calls often suffering from not being thread-safe include: C<localtime()>, C<gmtime()>, functions fetching user, group and network information (such as C<getgrent()>, C<gethostent()>, C<getnetent()> and so on), C<readdir()>, C<rand()>, and C<srand()>. In general, calls that depend on some global external state. If the system Perl is compiled in has thread-safe variants of such calls, they will be used. Beyond that, Perl is at the mercy of the thread-safety or -unsafety of the calls. Please consult your C library call documentation. On some platforms the thread-safe library interfaces may fail if the result buffer is too small (for example the user group databases may be rather large, and the reentrant interfaces may have to carry around a full snapshot of those databases). Perl will start with a small buffer, but keep retrying and growing the result buffer until the result fits. If this limitless growing sounds bad for security or memory consumption reasons you can recompile Perl with C<PERL_REENTRANT_MAXSIZE> defined to the maximum number of bytes you will allow. =head1 Conclusion A complete thread tutorial could fill a book (and has, many times), but with what we've covered in this introduction, you should be well on your way to becoming a threaded Perl expert. =head1 SEE ALSO Annotated POD for L<threads>: L<http://annocpan.org/?mode=search&field=Module&name=threads> Latest version of L<threads> on CPAN: L<http://search.cpan.org/search?module=threads> Annotated POD for L<threads::shared>: L<http://annocpan.org/?mode=search&field=Module&name=threads%3A%3Ashared> Latest version of L<threads::shared> on CPAN: L<http://search.cpan.org/search?module=threads%3A%3Ashared> Perl threads mailing list: L<http://lists.perl.org/list/ithreads.html> =head1 Bibliography Here's a short bibliography courtesy of Jürgen Christoffel: =head2 Introductory Texts Birrell, Andrew D. An Introduction to Programming with Threads. Digital Equipment Corporation, 1989, DEC-SRC Research Report #35 online as ftp://ftp.dec.com/pub/DEC/SRC/research-reports/SRC-035.pdf (highly recommended) Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A Guide to Concurrency, Communication, and Multithreading. Prentice-Hall, 1996. Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written introduction to threads). Nelson, Greg (editor). Systems Programming with Modula-3. Prentice Hall, 1991, ISBN 0-13-590464-1. Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell. Pthreads Programming. O'Reilly & Associates, 1996, ISBN 156592-115-1 (covers POSIX threads). =head2 OS-Related References Boykin, Joseph, David Kirschen, Alan Langerman, and Susan LoVerso. Programming under Mach. Addison-Wesley, 1994, ISBN 0-201-52739-1. Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall, 1995, ISBN 0-13-219908-4 (great textbook). Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts, 4th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4 =head2 Other References Arnold, Ken and James Gosling. The Java Programming Language, 2nd ed. Addison-Wesley, 1998, ISBN 0-201-31006-6. comp.programming.threads FAQ, L<http://www.serpentine.com/~bos/threads-faq/> Le Sergent, T. and B. Berthomieu. "Incremental MultiThreaded Garbage Collection on Virtually Shared Memory Architectures" in Memory Management: Proc. of the International Workshop IWMM 92, St. Malo, France, September 1992, Yves Bekkers and Jacques Cohen, eds. Springer, 1992, ISBN 3540-55940-X (real-life thread applications). Artur Bergman, "Where Wizards Fear To Tread", June 11, 2002, L<http://www.perl.com/pub/a/2002/06/11/threads.html> =head1 Acknowledgements Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua Pritikin, and Alan Burlison, for their help in reality-checking and polishing this article. Big thanks to Tom Christiansen for his rewrite of the prime number generator. =head1 AUTHOR Dan Sugalski E<lt>dan@sidhe.org<gt> Slightly modified by Arthur Bergman to fit the new thread model/module. Reworked slightly by Jörg Walter E<lt>jwalt@cpan.org<gt> to be more concise about thread-safety of Perl code. Rearranged slightly by Elizabeth Mattijsen E<lt>liz@dijkmat.nl<gt> to put less emphasis on yield(). =head1 Copyrights The original version of this article originally appeared in The Perl Journal #10, and is copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and The Perl Journal. This document may be distributed under the same terms as Perl itself. =cut PK PU�\�21� � a2p.podnu �[��� =head1 NAME a2p - Awk to Perl translator =head1 SYNOPSIS B<a2p> [I<options>] [I<filename>] =head1 DESCRIPTION I<A2p> takes an awk script specified on the command line (or from standard input) and produces a comparable I<perl> script on the standard output. =head2 OPTIONS Options include: =over 5 =item B<-DE<lt>numberE<gt>> sets debugging flags. =item B<-FE<lt>characterE<gt>> tells a2p that this awk script is always invoked with this B<-F> switch. =item B<-nE<lt>fieldlistE<gt>> specifies the names of the input fields if input does not have to be split into an array. If you were translating an awk script that processes the password file, you might say: a2p -7 -nlogin.password.uid.gid.gcos.shell.home Any delimiter can be used to separate the field names. =item B<-E<lt>numberE<gt>> causes a2p to assume that input will always have that many fields. =item B<-o> tells a2p to use old awk behavior. The only current differences are: =over 5 =item * Old awk always has a line loop, even if there are no line actions, whereas new awk does not. =item * In old awk, sprintf is extremely greedy about its arguments. For example, given the statement print sprintf(some_args), extra_args; old awk considers I<extra_args> to be arguments to C<sprintf>; new awk considers them arguments to C<print>. =back =back =head2 "Considerations" A2p cannot do as good a job translating as a human would, but it usually does pretty well. There are some areas where you may want to examine the perl script produced and tweak it some. Here are some of them, in no particular order. There is an awk idiom of putting int() around a string expression to force numeric interpretation, even though the argument is always integer anyway. This is generally unneeded in perl, but a2p can't tell if the argument is always going to be integer, so it leaves it in. You may wish to remove it. Perl differentiates numeric comparison from string comparison. Awk has one operator for both that decides at run time which comparison to do. A2p does not try to do a complete job of awk emulation at this point. Instead it guesses which one you want. It's almost always right, but it can be spoofed. All such guesses are marked with the comment "C<#???>". You should go through and check them. You might want to run at least once with the B<-w> switch to perl, which will warn you if you use == where you should have used eq. Perl does not attempt to emulate the behavior of awk in which nonexistent array elements spring into existence simply by being referenced. If somehow you are relying on this mechanism to create null entries for a subsequent for...in, they won't be there in perl. If a2p makes a split line that assigns to a list of variables that looks like (Fld1, Fld2, Fld3...) you may want to rerun a2p using the B<-n> option mentioned above. This will let you name the fields throughout the script. If it splits to an array instead, the script is probably referring to the number of fields somewhere. The exit statement in awk doesn't necessarily exit; it goes to the END block if there is one. Awk scripts that do contortions within the END block to bypass the block under such circumstances can be simplified by removing the conditional in the END block and just exiting directly from the perl script. Perl has two kinds of array, numerically-indexed and associative. Perl associative arrays are called "hashes". Awk arrays are usually translated to hashes, but if you happen to know that the index is always going to be numeric you could change the {...} to [...]. Iteration over a hash is done using the keys() function, but iteration over an array is NOT. You might need to modify any loop that iterates over such an array. Awk starts by assuming OFMT has the value %.6g. Perl starts by assuming its equivalent, $#, to have the value %.20g. You'll want to set $# explicitly if you use the default value of OFMT. Near the top of the line loop will be the split operation that is implicit in the awk script. There are times when you can move this down past some conditionals that test the entire record so that the split is not done as often. For aesthetic reasons you may wish to change index variables from being 1-based (awk style) to 0-based (Perl style). Be sure to change all operations the variable is involved in to match. Cute comments that say "# Here is a workaround because awk is dumb" are passed through unmodified. Awk scripts are often embedded in a shell script that pipes stuff into and out of awk. Often the shell script wrapper can be incorporated into the perl script, since perl can start up pipes into and out of itself, and can do other things that awk can't do by itself. Scripts that refer to the special variables RSTART and RLENGTH can often be simplified by referring to the variables $`, $& and $', as long as they are within the scope of the pattern match that sets them. The produced perl script may have subroutines defined to deal with awk's semantics regarding getline and print. Since a2p usually picks correctness over efficiency. it is almost always possible to rewrite such code to be more efficient by discarding the semantic sugar. For efficiency, you may wish to remove the keyword from any return statement that is the last statement executed in a subroutine. A2p catches the most common case, but doesn't analyze embedded blocks for subtler cases. ARGV[0] translates to $ARGV0, but ARGV[n] translates to $ARGV[$n-1]. A loop that tries to iterate over ARGV[0] won't find it. =head1 ENVIRONMENT A2p uses no environment variables. =head1 AUTHOR Larry Wall E<lt>F<larry@wall.org>E<gt> =head1 FILES =head1 SEE ALSO perl The perl compiler/interpreter s2p sed to perl translator =head1 DIAGNOSTICS =head1 BUGS It would be possible to emulate awk's behavior in selecting string versus numeric operations at run time by inspection of the operands, but it would be gross and inefficient. Besides, a2p almost always guesses right. Storage for the awk syntax tree is currently static, and can run out. PK PU�\wݸ՟'