
perl5004delta - what's new for perl5.004
This document describes differences between the 5.003 release (asdocumented inProgramming Perl, second edition--the Camel Book) andthis one.
Perl5.004 builds out of the box on Unix, Plan 9, LynxOS, VMS, OS/2,QNX, AmigaOS, and Windows NT. Perl runs on Windows 95 as well, but itcannot be built there, for lack of a reasonable command interpreter.
Most importantly, many bugs were fixed, including several securityproblems. See theChanges file in the distribution for details.
%ENV =() and%ENV =@list now work as expected (except on VMSwhere it generates a fatal error).
The error "Can't locate Foo.pm in @INC" now lists the contents of @INCfor easier debugging.
There is a new Configure question that asks if you want to maintainbinary compatibility with Perl 5.003. If you choose binarycompatibility, you do not have to recompile your extensions, but youmight have symbol conflicts if you embed Perl in another application,just as in the 5.003 release. By default, binary compatibilityis preserved at the expense of symbol table pollution.
You may now put Perl options in the $PERL5OPT environment variable.Unless Perl is running with taint checks, it will interpret thisvariable as if its contents had appeared on a "#!perl" line at thebeginning of your script, except that hyphens are optional. PERL5OPTmay only be used to set the following switches:-[DIMUdmw].
The-M and-m options are no longer allowed on the#! line ofa script. If a script needs a module, it should invoke it with theuse pragma.
The-T option is also forbidden on the#! line of a script,unless it was present on the Perl command line. Due to the way#!works, this usually means that-T must be in the first argument.Thus:
- #!/usr/bin/perl -T -w
will probably work for an executable script invoked asscriptname,while:
- #!/usr/bin/perl -w -T
will probably fail under the same conditions. (Non-Unix systems willprobably not follow this rule.) Butperlscriptname is guaranteedto fail, since then there is no chance of-T being found on thecommand line before it is found on the#! line.
If you removed the-w option from your Perl 5.003 scripts because itmade Perl too verbose, we recommend that you try putting it back whenyou upgrade to Perl 5.004. Each new perl version tends to remove someundesirable warnings, while adding new warnings that may catch bugs inyour scripts.
AUTOLOAD for non-methodsBefore Perl 5.004,AUTOLOAD functions were looked up as methods(using the@ISA hierarchy), even when the function to be autoloadedwas called as a plain function (e.g.Foo::bar()), not a method(e.g.Foo->bar() or$obj->bar()).
Perl 5.005 will use method lookup only for methods'AUTOLOADs.However, there is a significant base of existing code that may be usingthe old behavior. So, as an interim step, Perl 5.004 issues an optionalwarning when a non-method uses an inheritedAUTOLOAD.
The simple rule is: Inheritance will not work when autoloadingnon-methods. The simple fix for old code is: In any module that used todepend on inheritingAUTOLOAD for non-methods from a base class namedBaseClass, execute*AUTOLOAD = \&BaseClass::AUTOLOAD during startup.
Using %OVERLOAD to define overloading was deprecated in 5.003.Overloading is now defined using the overload pragma. %OVERLOAD isstill used internally but should not be used by Perl scripts. Seeoverload for more details.
In Perl 5.004, nonexistent array and hash elements used as subroutineparameters are brought into existence only if they are actuallyassigned to (via@_).
Earlier versions of Perl vary in their handling of such arguments.Perl versions 5.002 and 5.003 always brought them into existence.Perl versions 5.000 and 5.001 brought them into existence only ifthey were not the first argument (which was almost certainly a bug).Earlier versions of Perl never brought them into existence.
For example, given this code:
After this code executes in Perl 5.004, $a{b} exists but $a[2] doesnot. In Perl 5.002 and 5.003, both $a{b} and $a[2] would have existed(but $a[2]'s value would have been undefined).
$)The$) special variable has always (well, in Perl 5, at least)reflected not only the current effective group, but also the group listas returned by thegetgroups() C function (if there is one).However, until this release, there has not been a way to call thesetgroups() C function from Perl.
In Perl 5.004, assigning to$) is exactly symmetrical with examiningit: The first number in its string value is used as the effective gid;if there are any numbers after the first one, they are passed to thesetgroups() C function (if there is one).
Perl versions before 5.004 misinterpreted any type marker followed by"$" and a digit. For example, "$$0" was incorrectly taken to mean"${$}0" instead of "${$0}". This bug is (mostly) fixed in Perl 5.004.
However, the developers of Perl 5.004 could not fix this bug completely,because at least two widely-used modules depend on the old meaning of"$$0" in a string. So Perl 5.004 still interprets "$$<digit>" in theold (broken) way inside strings; but it generates this message as awarning. And in Perl 5.005, this special treatment will cease.
Perl versions before 5.004 did not always properly localize theregex-related special variables. Perl 5.004 does localize them, asthe documentation has always said it should. This may result in $1,$2, etc. no longer being set where existing programs use them.
The documentation for Perl 5.0 has always stated that$. isnotreset when an already-open file handle is reopened with no interveningcall toclose. Due to a bug, perl versions 5.000 through 5.003did reset$. under that circumstance; Perl 5.004 does not.
wantarray may return undefThewantarray operator returns true if a subroutine is expected toreturn a list, and false otherwise. In Perl 5.004,wantarray canalso return the undefined value if a subroutine's return value willnot be used at all, which allows subroutines to avoid a time-consumingcalculation of a return value if it isn't going to be used.
evalEXPR determines value of EXPR in scalar contextPerl (version 5) used to determine the value of EXPR inconsistently,sometimes incorrectly using the surrounding context for the determination.Now, the value of EXPR (before being parsed by eval) is always determined ina scalar context. Once parsed, it is executed as before, by providingthe context that the scope surrounding the eval provided. This changemakes the behavior Perl4 compatible, besides fixing bugs resulting fromthe inconsistent behavior. This program:
used to print something like "timenowis881399109|4", but now (and in perl4)prints "4|4".
A bug in previous versions may have failed to detect some insecureconditions when taint checks are turned on. (Taint checks are usedin setuid or setgid scripts, or when explicitly turned on with the-T invocation option.) Although it's unlikely, this may cause apreviously-working script to now fail, which should be construedas a blessing since that indicates a potentially-serious securityhole was just plugged.
The new restrictions when tainting include:
These operators may spawn the C shell (csh), which cannot be madesafe. This restriction will be lifted in a future version of Perlwhen globbing is implemented without the use of an external program.
These environment variables may alter the behavior of spawned programs(especially shells) in ways that subvert security. So now they aretreated as dangerous, in the manner of $IFS and $PATH.
Some termcap libraries do unsafe things with $TERM. However, it would beunnecessarily harsh to treat all $TERM values as unsafe, since only shellmetacharacters can cause trouble in $TERM. So a tainted $TERM isconsidered to be safe if it contains only alphanumerics, underscores,dashes, and colons, and unsafe if it contains other characters (includingwhitespace).
A new Opcode module supports the creation, manipulation andapplication of opcode masks. The revised Safe module has a new APIand is implemented using the new Opcode module. Please read the newOpcode and Safe documentation.
In older versions of Perl it was not possible to create more than onePerl interpreter instance inside a single process without leaking like asieve and/or crashing. The bugs that caused this behavior have all beenfixed. However, you still must take care when embedding Perl in a Cprogram. See the updated perlembed manpage for tips on how to manageyour interpreters.
File handles are now stored internally as type IO::Handle. TheFileHandle module is still supported for backwards compatibility, butit is now merely a front end to the IO::* modules, specificallyIO::Handle, IO::Seekable, and IO::File. We suggest, but do notrequire, that you use the IO::* modules in new code.
In harmony with this change,*GLOB{FILEHANDLE} is now just abackward-compatible synonym for*GLOB{IO}.
It is now possible to build Perl with AT&T's sfio IO packageinstead of stdio. Seeperlapio for more details, andtheINSTALL file for how to use it.
A subroutine reference may now be suffixed with an arrow and a(possibly empty) parameter list. This syntax denotes a call of thereferenced subroutine, with the given parameters (if any).
This new syntax follows the pattern of$hashref->{FOO} and$aryref->[$foo]: You may now write&$subref($foo) as$subref->($foo). All these arrow terms may be chained;thus,&{$table->{FOO}}($bar) may now be written$table->{FOO}->($bar).
The current package name at compile time, or the undefined value ifthere is no current package (due to apackage; directive). Like__FILE__ and__LINE__,__PACKAGE__ doesnot interpolateinto strings.
Extended error message on some platforms. (Also known as$EXTENDED_OS_ERROR if youuseEnglish).
The current set of syntax checks enabled byusestrict. See thedocumentation ofstrict for more details. Not actually new, butnewly documented.Because it is intended for internal use by Perl core components,there is nouseEnglish long name for this variable.
By default, running out of memory it is not trappable. However, ifcompiled for this, Perl may use the contents of$^M as an emergencypool after die()ing with this message. Suppose that your Perl werecompiled with -DPERL_EMERGENCY_SBRK and used Perl's malloc. Then
- $^M ='a' x(1<<16);
would allocate a 64K buffer for use when in emergency.See theINSTALL file for information on how to enable this option.As a disincentive to casual use of this advanced feature,there is nouseEnglish long name for this variable.
This now works. (e.g.delete@ENV{'PATH','MANPATH'})
is now supported on more platforms, prefers fcntl to lockf whenemulating, and always flushes before (un)locking.
Perl now implements these functions itself; it doesn't use the Clibrary function sprintf() any more, except for floating-pointnumbers, and even then only known flags are allowed. As a result, itis now possible to know which conversions and flags will work, andwhat they will do.
The new conversions in Perl's sprintf() are:
- %ia synonym for %d
- %pa pointer (the address of the Perl value, in hexadecimal)
- %nspecial: *stores* the number of characters output so far
- into the next variable in the parameter list
The new flags that go between the% and the conversion are:
- #prefix octal with "0", hex with "0x"
- hinterpret integer as C type "short" or "unsigned short"
- Vinterpret integer as Perl's standard integer type
Also, where a number would appear in the flags, an asterisk ("*") maybe used instead, in which case Perl uses the next item in theparameter list as the given number (that is, as the field width orprecision). If a field width obtained through "*" is negative, it hasthe same effect as the '-' flag: left-justification.
Seesprintf for a complete list of conversion and flags.
As an lvalue,keys allows you to increase the number of hash bucketsallocated for the given hash. This can gain you a measure of efficiency ifyou know the hash is going to get big. (This is similar to pre-extendingan array by assigning a larger number to $#array.) If you say
- keys%hash =200;
then%hash will have at least 200 buckets allocated for it. Thesebuckets will be retained even if you do%hash =(); useundef%hash if you want to free the storage while%hash is still in scope.You can't shrink the number of buckets allocated for the hash usingkeys in this way (but you needn't worry about doing this by accident,as trying has no effect).
You can now use my() (with or without the parentheses) in the controlexpressions of control structures such as:
Also, you can declare a foreach loop control variable as lexical bypreceding it with the word "my". For example, in:
- foreachmy$i(1,2,3){
- some_function();
- }
$i is a lexical variable, and the scope of $i extends to the end ofthe loop, but not beyond it.
Note that you still cannot use my() on global punctuation variablessuch as $_ and the like.
A new format 'w' represents a BER compressed integer (as defined inASN.1). Its format is a sequence of one or more bytes, each of whichprovides seven bits of the total value, with the most significantfirst. Bit eight of each byte is set, except for the last byte, inwhich bit eight is clear.
If 'p' or 'P' are given undef as values, they now generate a NULLpointer.
Both pack() and unpack() now fail when their templates contain invalidtypes. (Invalid types used to be ignored.)
The new sysseek() operator is a variant of seek() that sets and gets thefile's system read/write position, using the lseek(2) system call. It isthe only reliable way to seek before using sysread() or syswrite(). Itsreturn value is the new position, or the undefined value on failure.
If the first argument touse is a number, it is treated as a versionnumber instead of a module name. If the version of the Perl interpreteris less than VERSION, then an error message is printed and Perl exitsimmediately. Becauseuse occurs at compile time, this check happensimmediately during the compilation process, unlikerequireVERSION,which waits until runtime for the check. This is often useful if youneed to check the current Perl version beforeuseing library moduleswhich have changed in incompatible ways from older versions of Perl.(We try not to do this more than we have to.)
If the VERSION argument is present between Module and LIST, then theuse will call the VERSION method in class Module with the givenversion as an argument. The default VERSION method, inherited fromthe UNIVERSAL class, croaks if the given version is larger than thevalue of the variable $Module::VERSION. (Note that there is not acomma after VERSION!)
This version-checking mechanism is similar to the one currently usedin the Exporter module, but it is faster and can be used with modulesthat don't use the Exporter. It is the recommended method for newcode.
Returns the prototype of a function as a string (orundef if thefunction has no prototype). FUNCTION is a reference to or the name of thefunction whose prototype you want to retrieve.(Not actually new; just never documented before.)
The default seed forsrand, which used to betime, has been changed.Now it's a heady mix of difficult-to-predict system-dependent values,which should be sufficient for most everyday purposes.
Previous to version 5.004, callingrand without first callingsrandwould yield the same sequence of random numbers on most or all machines.Now, when perl sees that you're callingrand and haven't yet calledsrand, it callssrand with the default seed. You should still callsrand manually if your code might ever be run on a pre-5.004 system,of course, or if you want a seed other than the default.
Functions documented in the Camel to default to $_ now infact do, and all those that do are so documented inperlfunc.
m//gc does not reset search position on failureThem//g match iteration construct has always reset its targetstring's search position (which is visible through thepos operator)when a match fails; as a result, the nextm//g match after a failurestarts again at the beginning of the string. With Perl 5.004, thisreset may be disabled by adding the "c" (for "continue") modifier,i.e.m//gc. This feature, in conjunction with the\G zero-widthassertion, makes it possible to chain matches together. Seeperlopandperlre.
m//x ignores whitespace before ?*+{}Them//x construct has always been intended to ignore all unescapedwhitespace. However, before Perl 5.004, whitespace had the effect ofescaping repeat modifiers like "*" or "?"; for example,/a *b/x was(mis)interpreted as/a\*b/x. This bug has been fixed in 5.004.
sub{} closures work nowPrior to the 5.004 release, nested anonymous functions didn't workright. They do now.
Just like anonymous functions that contain lexical variablesthat change (like a lexical index variable for aforeach loop),formats now work properly. For example, this silently failedbefore (printed only zeros), but is fine now:
- my $i;
- foreach $i ( 1 .. 10 ) {
- write;
- }
- format =
- my i is @#
- $i
- .
However, it still fails (without a warning) if the foreach is within asubroutine:
- my $i;
- sub foo {
- foreach $i ( 1 .. 10 ) {
- write;
- }
- }
- foo;
- format =
- my i is @#
- $i
- .
TheUNIVERSAL package automatically contains the following methods thatare inherited by all other classes:
isa returnstrue if its object is blessed into a subclass ofCLASS
isa is also exportable and can be called as a sub with two arguments. Thisallows the ability to check what a reference points to. Example:
- useUNIVERSALqw(isa);
- if(isa($ref,'ARRAY')){
- ...
- }
can checks to see if its object has a method calledMETHOD,if it does then a reference to the sub is returned; if it does not thenundef is returned.
VERSION returns the version number of the class (package). If theNEED argument is given then it will check that the current version (asdefined by the $VERSION variable in the given package) not less thanNEED; it will die if this is not the case. This method is normallycalled as a class method. This method is called automatically by theVERSION form ofuse.
- useA1.2qw(some imported subs);
- # implies:
- A->VERSION(1.2);
NOTE:can directly uses Perl's internal code for method lookup, andisa uses a very similar method and caching strategy. This may causestrange effects if the Perl code dynamically changes @ISA in any package.
You may add other methods to the UNIVERSAL class via Perl or XS code.You do not need touseUNIVERSAL in order to make these methodsavailable to your program. This is necessary only if you wish tohaveisa available as a plain subroutine in the current package.
Seeperltie for other kinds of tie()s.
This is the constructor for the class. That means it is expected toreturn an object of some sort. The reference can be used tohold some internal information.
This method will be triggered every time the tied handle is printed to.Beyond its self reference it also expects the list that was passed tothe print function.
This method will be triggered every time the tied handle is printed towith theprintf() function.Beyond its self reference it also expects the format and list that waspassed to the printf function.
This method will be called when the handle is read from via thereadorsysread functions.
This method will be called when the handle is read from. The methodshould return undef when there is no more data.
This method will be called when thegetc function is called.
As with the other types of ties, this method will be called when thetied handle is about to be destroyed. This is useful for debugging andpossibly for cleaning up.
- subDESTROY{
- print"</shout>\n";
- }
If perl is compiled with the malloc included with the perl distribution(that is, ifperl -V:d_mymalloc is 'define') then you can printmemory statistics at runtime by running Perl thusly:
- env PERL_DEBUG_MSTATS=2 perl your_script_here
The value of 2 means to print statistics after compilation and onexit; with a value of 1, the statistics are printed only on exit.(If you want the statistics at an arbitrary time, you'll need toinstall the optional module Devel::Peek.)
Three new compilation flags are recognized by malloc.c. (They have noeffect if perl is compiled with system malloc().)
If this macro is defined, running out of memory need not be a fatalerror: a memory pool can allocated by assigning to the specialvariable$^M. See$^M.
Perl memory allocation is by bucket with sizes close to powers of two.Because of these malloc overhead may be big, especially for data ofsize exactly a power of two. IfPACK_MALLOC is defined, perl usesa slightly different algorithm for small allocations (up to 64 byteslong), which makes it possible to have overhead down to 1 byte forallocations which are powers of two (and appear quite often).
Expected memory savings (with 8-byte alignment inalignbytes) isabout 20% for typical Perl usage. Expected slowdown due to additionalmalloc overhead is in fractions of a percent (hard to measure, becauseof the effect of saved memory on speed).
Similarly toPACK_MALLOC, this macro improves allocations of datawith size close to a power of two; but this works for big allocations(starting with 16K by default). Such allocations are typical for bighashes and special-purpose scripts, especially image processing.
On recent systems, the fact that perl requires 2M from system for 1Mallocation will not affect speed of execution, since the tail of sucha chunk is not going to be touched (and thus will not require realmemory). However, it may result in a premature out-of-memory error.So if you will be manipulating very large blocks with sizes close topowers of two, it would be wise to define this macro.
Expected saving of memory is 0-100% (100% in applications whichrequire most memory in such 2**n chunks); expected slowdown isnegligible.
Functions that have an empty prototype and that do nothing but returna fixed value are now inlined (e.g.subPI (){3.14159}).
Each unique hash key is only allocated once, no matter how many hasheshave an entry with that key. So even if you have 100 copies of thesame hash, the hash keys never have to be reallocated.
Support for the following operating systems is new in Perl 5.004.
Perl 5.004 now includes support for building a "native" perl underWindows NT, using the Microsoft Visual C++ compiler (versions 2.0and above) or the Borland C++ compiler (versions 5.02 and above).The resulting perl can be used under Windows 95 (if itis installed in the same directory locations as it got installedin Windows NT). This port includes support for perl extensionbuilding tools likeMakeMaker andh2xs, so that many extensionsavailable on the Comprehensive Perl Archive Network (CPAN) can now bereadily built under Windows NT. Seehttp://www.perl.com/ for moreinformation on CPAN andREADME.win32 in the perl distribution for moredetails on how to get started with building this port.
There is also support for building perl under the Cygwin32 environment.Cygwin32 is a set of GNU tools that make it possible to compile and runmany Unix programs under Windows NT by providing a mostly Unix-like interface for compilation and execution. SeeREADME.cygwin32 in theperl distribution for more details on this port and how to obtain theCygwin32 toolkit.
SeeREADME.plan9 in the perl distribution.
SeeREADME.qnx in the perl distribution.
SeeREADME.amigaos in the perl distribution.
Six new pragmatic modules exist:
DefersrequireMODULE until someone calls one of the specifiedsubroutines (which must be exported by MODULE). This pragma should beused with caution, and only when necessary.
Looks for MakeMaker-like'blib' directory structure starting indir (or current directory) and working back up to five levels ofparent directories.
Intended for use on command line with-M option as a way of testingarbitrary scripts against an uninstalled version of a package.
Provides a convenient interface for creating compile-time constants,SeeConstant Functions in perlsub.
Tells the compiler to enable (or disable) the use of POSIX locales forbuiltin operations.
Whenuselocale is in effect, the current LC_CTYPE locale is usedfor regular expressions and case mapping; LC_COLLATE for stringordering; and LC_NUMERIC for numeric formatting in printf and sprintf(butnot in print). LC_NUMERIC is always used in write, sincelexical scoping of formats is problematic at best.
Eachuselocale ornolocale affects statements to the end ofthe enclosing BLOCK or, if not inside a BLOCK, to the end of thecurrent file. Locales can be switched and queried withPOSIX::setlocale().
Seeperllocale for more information.
Disable unsafe opcodes, or any named opcodes, when compiling Perl code.
Enable VMS-specific language features. Currently, there are threeVMS-specific features available: 'status', which makes$? andsystem return genuine VMS status values instead of emulating POSIX;'exit', which makesexit take a genuine VMS status value instead ofassuming thatexit1 is an error; and 'time', which makes all timesrelative to the local time zone, in the VMS tradition.
Though Perl 5.004 is compatible with almost all modules that workwith Perl 5.003, there are a few exceptions:
- Module Required Version for Perl 5.004
- ------ -------------------------------
- Filter Filter-1.12
- LWP libwww-perl-5.08
- Tk Tk400.202 (-w makes noise)
Also, the majordomo mailing list program, version 1.94.1, doesn't workwith Perl 5.004 (nor with perl 4), because it executes an invalidregular expression. This bug is fixed in majordomo version 1.94.2.
Theinstallperl script now places the Perl source files forextensions in the architecture-specific library directory, which iswhere the shared libraries for extensions have always been. Thischange is intended to allow administrators to keep the Perl 5.004library directory unchanged from a previous version, without runningthe risk of binary incompatibility between extensions' Perl source andshared libraries.
Brand new modules, arranged by topic rather than strictlyalphabetically:
- CGI.pm Web server interface ("Common Gateway Interface")
- CGI/Apache.pm Support for Apache's Perl module
- CGI/Carp.pm Log server errors with helpful context
- CGI/Fast.pm Support for FastCGI (persistent server process)
- CGI/Push.pm Support for server push
- CGI/Switch.pm Simple interface for multiple server types
- CPAN Interface to Comprehensive Perl Archive Network
- CPAN::FirstTime Utility for creating CPAN configuration file
- CPAN::Nox Runs CPAN while avoiding compiled extensions
- IO.pm Top-level interface to IO::* classes
- IO/File.pm IO::File extension Perl module
- IO/Handle.pm IO::Handle extension Perl module
- IO/Pipe.pm IO::Pipe extension Perl module
- IO/Seekable.pm IO::Seekable extension Perl module
- IO/Select.pm IO::Select extension Perl module
- IO/Socket.pm IO::Socket extension Perl module
- Opcode.pm Disable named opcodes when compiling Perl code
- ExtUtils/Embed.pm Utilities for embedding Perl in C programs
- ExtUtils/testlib.pm Fixes up @INC to use just-built extension
- FindBin.pm Find path of currently executing program
- Class/Struct.pm Declare struct-like datatypes as Perl classes
- File/stat.pm By-name interface to Perl's builtin stat
- Net/hostent.pm By-name interface to Perl's builtin gethost*
- Net/netent.pm By-name interface to Perl's builtin getnet*
- Net/protoent.pm By-name interface to Perl's builtin getproto*
- Net/servent.pm By-name interface to Perl's builtin getserv*
- Time/gmtime.pm By-name interface to Perl's builtin gmtime
- Time/localtime.pm By-name interface to Perl's builtin localtime
- Time/tm.pm Internal object for Time::{gm,local}time
- User/grent.pm By-name interface to Perl's builtin getgr*
- User/pwent.pm By-name interface to Perl's builtin getpw*
- Tie/RefHash.pm Base class for tied hashes with references as keys
- UNIVERSAL.pm Base class for *ALL* classes
New constants in the existing Fcntl modules are now supported,provided that your operating system happens to support them:
- F_GETOWNF_SETOWN
- O_ASYNCO_DEFERO_DSYNCO_FSYNCO_SYNC
- O_EXLOCKO_SHLOCK
These constants are intended for use with the Perl operators sysopen()and fcntl() and the basic database modules like SDBM_File. For theexact meaning of these and other Fcntl constants please refer to youroperating system's documentation for fcntl() and open().
In addition, the Fcntl module now provides these constants for usewith the Perl operator flock():
- LOCK_SHLOCK_EXLOCK_NBLOCK_UN
These constants are defined in all environments (because where there isno flock() system call, Perl emulates it). However, for historicalreasons, these constants are not exported unless they are explicitlyrequested with the ":flock" tag (e.g.useFcntl':flock').
The IO module provides a simple mechanism to load all the IO modules at onego. Currently this includes:
- IO::Handle
- IO::Seekable
- IO::File
- IO::Pipe
- IO::Socket
For more information on any of these modules, please see itsrespective documentation.
The Math::Complex module has been totally rewritten, and now supportsmore operations. These are overloaded:
- + - * / ** <=> neg ~ abs sqrt exp log sin cos atan2 "" (stringify)
And these functions are now exported:
- piiReImarg
- log10lognlncbrtroot
- tan
- cscseccot
- asinacosatan
- acscasecacot
- sinhcoshtanh
- cschsechcoth
- asinhacoshatanh
- acschasechacoth
- cplxcplxe
This new module provides a simpler interface to parts of Math::Complex forthose who need trigonometric functions only for real numbers.
There have been quite a few changes made to DB_File. Here are a few ofthe highlights:
Fixed a handful of bugs.
By public demand, added support for the standard hash function exists().
Made it compatible with Berkeley DB 1.86.
Made negative subscripts work with RECNO interface.
Changed the default flags from O_RDWR to O_CREAT|O_RDWR and the defaultmode from 0640 to 0666.
Made DB_File automatically import the open() constants (O_RDWR,O_CREAT etc.) from Fcntl, if available.
Updated documentation.
Refer to the HISTORY section in DB_File.pm for a complete list ofchanges. Everything after DB_File 1.01 has been added since 5.003.
Major rewrite - support added for both udp echo and real icmp pings.
Many of the Perl builtins returning lists now haveobject-oriented overrides. These are:
- File::stat
- Net::hostent
- Net::netent
- Net::protoent
- Net::servent
- Time::gmtime
- Time::localtime
- User::grent
- User::pwent
For example, you can now say
Thepod2html utility included with Perl 5.004 is entirely new.By default, it sends the converted HTML to its standard output,instead of writing it to a file like Perl 5.003'spod2html did.Use the--outfile=FILENAME option to write to a file.
void XSUBs now default to returning nothingDue to a documentation/implementation bug in previous versions ofPerl, XSUBs with a return type ofvoid have actually beenreturning one value. Usually that value was the GV for the XSUB,but sometimes it was some already freed or reused value, which wouldsometimes lead to program failure.
In Perl 5.004, if an XSUB is declared as returningvoid, itactually returns no value, i.e. an empty list (though there is abackward-compatibility exception; see below). If your XSUB reallydoes return an SV, you should give it a return type ofSV *.
For backward compatibility,xsubpp tries to guess whether avoid XSUB is reallyvoid or if it wants to return anSV *.It does so by examining the text of the XSUB: ifxsubpp findswhat looks like an assignment toST(0), it assumes that theXSUB's return type is reallySV *.
gv_fetchmethod andperl_call_svThegv_fetchmethod function finds a method for an object, just likein Perl 5.003. The GV it returns may be a method cache entry.However, in Perl 5.004, method cache entries are not visible to users;therefore, they can no longer be passed directly toperl_call_sv.Instead, you should use theGvCV macro on the GV to extract its CV,and pass the CV toperl_call_sv.
The most likely symptom of passing the result ofgv_fetchmethod toperl_call_sv is Perl's producing an "Undefined subroutine called"error on thesecond call to a given method (since there is no cacheon the first call).
perl_eval_pvA new function handy for eval'ing strings of Perl code inside C code.This function returns the value from the eval statement, which canbe used instead of fetching globals from the symbol table. Seeperlguts,perlembed andperlcall for details and examples.
Internal handling of hash keys has changed. The old hashtable API isstill fully supported, and will likely remain so. The additions to theAPI allow passing keys asSV*s, so thattied hashes can be givenreal scalars as keys rather than plain strings (nontied hashes stillcan only use strings as keys). New extensions must use the new hashaccess functions and macros if they wish to useSV* keys. Theseadditions also make it feasible to manipulateHE*s (hash entries),which can be more efficient. Seeperlguts for details.
Many of the base and library pods were updated. Thesenew pods are included in section 1:
This document.
Frequently asked questions.
Locale support (internationalization and localization).
Tutorial on Perl OO programming.
Perl internal IO abstraction interface.
Perl module library and recommended practice for module creation.Extracted fromperlmod (which is much smaller as a result).
Although not new, this has been massively updated.
Although not new, this has been massively updated.
Several new conditions will trigger warnings that weresilent before. Some only affect certain platforms.The following new warnings and errors outline these.These messages are classified as follows (listed inincreasing order of desperation):
- (W) A warning (optional).
- (D) A deprecation (optional).
- (S) A severe warning (mandatory).
- (F) A fatal error (trappable).
- (P) An internal error you should never see (trappable).
- (X) A very fatal error (nontrappable).
- (A) An alien error message (not generated by Perl).
(W) A lexical variable has been redeclared in the same scope, effectivelyeliminating all access to the previous instance. This is almost alwaysa typographical error. Note that the earlier variable will still existuntil the end of the scope or until all closure referents to it aredestroyed.
(F) The argument to delete() must be either a hash element, such as
- $foo{$bar}
- $ref->[12]->{"susie"}
or a hash slice, such as
- @foo{$bar, $baz, $xyzzy}
- @{$ref->[12]}{"susie", "queue"}
(X) You can't allocate more than 64K on an MS-DOS machine.
(F) You can't allocate more than 2^31+"small amount" bytes.
(W) The pattern match (//), substitution (s///), and transliteration (tr///)operators work on scalar values. If you apply one of them to an arrayor a hash, it will convert the array or hash to a scalar value (thelength of an array or the population info of a hash) and then work onthat scalar value. This is probably not what you meant to do. Seegrep andmap for alternatives.
(P) Perl maintains a reference counted internal table of strings tooptimize the storage and access of hash keys and other strings. Thisindicates someone tried to decrement the reference count of a stringthat can no longer be found in the table.
(W) You supplied a reference as the first argument to substr() usedas an lvalue, which is pretty strange. Perhaps you forgot todereference it first. Seesubstr.
(W) You used a qualified bareword of the formFoo::, butthe compiler saw no other uses of that namespace before that point.Perhaps you need to predeclare a package?
(F) Perl optimizes the internal handling of sort subroutines and keepspointers into them. You tried to redefine one such sort subroutine when itwas currently active, which is not allowed. If you really want to dothis, you should writesort{&func}@x instead ofsortfunc@x.
(F) Only hard references are allowed by "strict refs". Symbolic referencesare disallowed. Seeperlref.
(P) Internal error trying to resolve overloading specified by a methodname (as opposed to a subroutine reference).
(S) You redefined a subroutine which had previously been eligible forinlining. SeeConstant Functions in perlsub for commentary andworkarounds.
(S) You undefined a subroutine which had previously been eligible forinlining. SeeConstant Functions in perlsub for commentary andworkarounds.
(F) The method which overloads "=" is buggy. SeeCopy Constructor in overload.
(F) You passed die() an empty string (the equivalent ofdie"") oryou called it with no args and both$@ and$_ were empty.
(W) You are exiting a rather special block construct (like a sort block orsubroutine) by unconventional means, such as a goto, or a loop controlstatement. Seesort.
(F) Perl limits identifiers (names for variables, functions, etc.) to252 characters for simple names, somewhat more for compound names (like$A::B). You've exceeded Perl's limits. Future versions of Perl arelikely to eliminate these arbitrary limitations.
(F) A carriage return character was found in the input. This is anerror, and not a warning, because carriage return characters can breakmulti-line strings, including here documents (e.g.,print <<EOF;).
(X) The PERL5OPT environment variable may only be used to set thefollowing switches:-[DIMUdmw].
(S) The literal hex number you have specified is too big for yourarchitecture. On a 32-bit architecture the largest hex literal is0xFFFFFFFF.
(S) The literal octal number you have specified is too big for yourarchitecture. On a 32-bit architecture the largest octal literal is037777777777.
(P) Something went wrong with the external program(s) used forgloband<*.c>. This may mean that your csh (C shell) isbroken. If so, you should change all of the csh-related variables inconfig.sh: If you have tcsh, make the variables refer to it as if itwere csh (e.g.full_csh='/usr/bin/tcsh'); otherwise, make them allempty (except thatd_csh should be'undef') so that Perl willthink csh is missing. In either case, after editing config.sh, run./Configure -S and rebuild Perl.
(W) Perl does not understand the given format conversion.Seesprintf.
(F) The given character is not a valid pack type. Seepack.
(F) The given character is not a valid unpack type. Seeunpack.
(W) Typographical errors often show up as unique variable names.If you had a good reason for having a unique name, then just mentionit again somehow to suppress the message (theusevars pragma isprovided for just this purpose).
(F) The first argument to formline must be a valid format picturespecification. It was found to be empty, which probably means yousupplied it an uninitialized value. Seeperlform.
(F) You tried to do a read/write/send/recv operation with an offsetpointing outside the buffer. This is difficult to imagine.The sole exception to this is thatsysread()ing past the bufferwill extend the buffer and zero pad the new area.
(X|F) The malloc() function returned 0, indicating there was insufficientremaining memory (or virtual memory) to satisfy the request.
The request was judged to be small, so the possibility to trap itdepends on the way Perl was compiled. By default it is not trappable.However, if compiled for this, Perl may use the contents of$^M asan emergency pool after die()ing with this message. In this case theerror is trappableonce.
(F) The malloc() function returned 0, indicating there was insufficientremaining memory (or virtual memory) to satisfy the request. However,the request was judged large enough (compile-time default is 64K), soa possibility to shut down by trapping this error is granted.
(P) The library function frexp() failed, making printf("%f") impossible.
(W) qw() lists contain items separated by whitespace; as with literalstrings, comment characters are not ignored, but are instead treatedas literal data. (You may have used different delimiters than theparentheses shown here; braces are also frequently used.)
You probably wrote something like this:
- @list =qw(
- a # a comment
- b # another comment
- );
when you should have written this:
- @list =qw(
- a
- b
- );
If you really want comments, build your list theold-fashioned way, with quotes and commas:
- @list =(
- 'a',# a comment
- 'b',# another comment
- );
(W) qw() lists contain items separated by whitespace; therefore commasaren't needed to separate the items. (You may have used differentdelimiters than the parentheses shown here; braces are also frequentlyused.)
You probably wrote something like this:
- qw! a, b, c !;
which puts literal commas into some of the list items. Write it withoutcommas if you don't want them to appear in your data:
- qw! a b c !;
(W) You've used a hash slice (indicated by @) to select a single element ofa hash. Generally it's better to ask for a scalar value (indicated by $).The difference is that$foo{&bar} always behaves like a scalar, both whenassigning to it and when evaluating its argument, while@foo{&bar} behaveslike a list when you assign to it, and provides a list context to itssubscript, which can do weird things if you're expecting only one subscript.
(P) Overloading resolution over @ISA tree may be broken by importing stubs.Stubs should never be implicitly created, but explicit calls tocanmay break this.
(X) The #! line (or local equivalent) in a Perl script contains the-T option, but Perl was not invoked with-T in its argumentlist. This is an error because, by the time Perl discovers a-T ina script, it's too late to properly taint everything from theenvironment. So Perl gives up.
(W) A copy of the object returned fromtie (ortied) was stillvalid whenuntie was called.
(F) The Perl parser has no idea what to do with the specified characterin your Perl script (or eval). Perhaps you tried to run a compressedscript, a binary program, or a directory as a Perl program.
(F) Your version of executable does not support forking.
Note that under some systems, like OS/2, there may be different flavors ofPerl executables, some of which may support fork, some not. Try changingthe name you call Perl by toperl_,perl__, and so on.
(D) Perl versions before 5.004 misinterpreted any type marker followedby "$" and a digit. For example, "$$0" was incorrectly taken to mean"${$}0" instead of "${$0}". This bug is (mostly) fixed in Perl 5.004.
However, the developers of Perl 5.004 could not fix this bug completely,because at least two widely-used modules depend on the old meaning of"$$0" in a string. So Perl 5.004 still interprets "$$<digit>" in theold (broken) way inside strings; but it generates this message as awarning. And in Perl 5.005, this special treatment will cease.
(W) In a conditional expression, you used <HANDLE>, <*> (glob),each(),orreaddir() as a boolean value. Each of these constructs can return avalue of "0"; that would make the conditional expression false, which isprobably not what you intended. When using these constructs in conditionalexpressions, test their values with thedefined operator.
(W) An inner (nested)anonymous subroutine is inside anamedsubroutine, and outside that is another subroutine; and the anonymous(innermost) subroutine is referencing a lexical variable defined inthe outermost subroutine. For example:
If the anonymous subroutine is called or referenced (directly orindirectly) from the outermost subroutine, it will share the variableas you would expect. But if the anonymous subroutine is called orreferenced when the outermost subroutine is not active, it will seethe value of the shared variable as it was before and during the*first* call to the outermost subroutine, which is probably not whatyou want.
In these circumstances, it is usually best to make the middlesubroutine anonymous, using thesub{} syntax. Perl has specificsupport for shared variables in nested anonymous subroutines; a namedsubroutine in between interferes with this feature.
(W) An inner (nested)named subroutine is referencing a lexicalvariable defined in an outer subroutine.
When the inner subroutine is called, it will probably see the value ofthe outer subroutine's variable as it was before and during the*first* call to the outer subroutine; in this case, after the firstcall to the outer subroutine is complete, the inner and outersubroutines will no longer share a common value for the variable. Inother words, the variable will no longer be shared.
Furthermore, if the outer subroutine is anonymous and references alexical variable outside itself, then the outer and inner subroutineswillnever share the given variable.
This problem can usually be solved by making the inner subroutineanonymous, using thesub{} syntax. When inner anonymous subs thatreference variables in outer subroutines are called or referenced,they are automatically rebound to the current values of suchvariables.
(W) You passed warn() an empty string (the equivalent ofwarn"") oryou called it with no args and$_ was empty.
(W) A warning peculiar to VMS. A logical name was encountered when preparingto iterate over %ENV which violates the syntactic rules governing logicalnames. Since it cannot be translated normally, it is skipped, and will notappear in %ENV. This may be a benign occurrence, as some software packagesmight directly modify logical name tables and introduce nonstandard names,or it may indicate that a logical name table has been corrupted.
(P) An error peculiar to OS/2. Most probably you're using an obsoleteversion of Perl, and this should not happen anyway.
(F) An error peculiar to OS/2. PERLLIB_PREFIX should be of the form
- prefix1;prefix2
or
- prefix1prefix2
with nonempty prefix1 and prefix2. Ifprefix1 is indeed a prefixof a builtin library search path, prefix2 is substituted. The errormay appear if components are not found, or are too long. See"PERLLIB_PREFIX" inREADME.os2.
(F) An error peculiar to OS/2. PERL_SH_DIR is the directory to find thesh-shell in. See "PERL_SH_DIR" inREADME.os2.
(W) This is a standard message issued by OS/2 applications, while *nixapplications die in silence. It is considered a feature of the OS/2port. One can easily disable this by appropriate sighandlers, seeSignals in perlipc. See also "Process terminated by SIGTERM/SIGINT"inREADME.os2.
If you find what you think is a bug, you might check the headers ofrecently posted articles in the comp.lang.perl.misc newsgroup.There may also be information athttp://www.perl.com/perl/ , the PerlHome Page.
If you believe you have an unreported bug, please run theperlbugprogram included with your release. Make sure you trim your bug downto a tiny but sufficient test case. Your bug report, along with theoutput ofperl -V, will be sent off to <perlbug@perl.com> to beanalysed by the Perl porting team.
TheChanges file for exhaustive details on what changed.
TheINSTALL file for how to build Perl. This file has beensignificantly updated for 5.004, so even veteran users shouldlook through it.
TheREADME file for general stuff.
TheCopying file for copyright information.
Constructed by Tom Christiansen, grabbing material with permissionfrom innumerable contributors, with kibitzing by more than a few Perlporters.
Last update: Wed May 14 11:14:09 EDT 1997