Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) What's new for perl5.005The Perl Artistic License (Berikutnya)
History-Changes

What's new for perl5.004

Daftar Isi

NAME

perl5004delta - what's new for perl5.004

DESCRIPTION

This document describes differences between the 5.003 release (asdocumented in Programming Perl, second edition--the Camel Book) andthis one.

Supported Environments

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.

Core Changes

Most importantly, many bugs were fixed, including several securityproblems. See the Changes file in the distribution for details.

List assignment to %ENV works

%ENV = () and %ENV = @list now work as expected (except on VMSwhere it generates a fatal error).

Change to "Can't locate Foo.pm in @INC" error

The error "Can't locate Foo.pm in @INC" now lists the contents of @INCfor easier debugging.

Compilation option: Binary compatibility with 5.003

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.

$PERL5OPT environment variable

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].

Limitations on -M, -m, and -T options

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:

  1. #!/usr/bin/perl -T -w

will probably work for an executable script invoked as scriptname,while:

  1. #!/usr/bin/perl -w -T

will probably fail under the same conditions. (Non-Unix systems willprobably not follow this rule.) But perl scriptname is guaranteedto fail, since then there is no chance of -T being found on thecommand line before it is found on the #! line.

More precise warnings

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.

Deprecated: Inherited AUTOLOAD for non-methods

Before 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 inherited AUTOLOAD.

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 inheriting AUTOLOAD for non-methods from a base class namedBaseClass, execute *AUTOLOAD = \&BaseClass::AUTOLOAD during startup.

Previously deprecated %OVERLOAD is no longer usable

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.

Subroutine arguments created only when they're modified

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:

  1. undef @a; undef %a;
  2. sub show { print $_[0] };
  3. sub change { $_[0]++ };
  4. show($a[2]);
  5. change($a{b});

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).

Group vector changeable with $)

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 the getgroups() 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).

Fixed parsing of $$<digit>, &$<digit>, etc.

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.

Fixed localization of $<digit>, $&, etc.

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.

No resetting of $. on implicit close

The documentation for Perl 5.0 has always stated that $. is notreset when an already-open file handle is reopened with no interveningcall to close. Due to a bug, perl versions 5.000 through 5.003did reset $. under that circumstance; Perl 5.004 does not.

wantarray may return undef

The wantarray 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.

eval EXPR determines value of EXPR in scalar context

Perl (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:

  1. @a = qw(time now is time);
  2. print eval @a;
  3. print '|', scalar eval @a;

used to print something like "timenowis881399109|4", but now (and in perl4)prints "4|4".

Changes to tainting checks

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:

  • No glob() or <*>

    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.

  • No spawning if tainted $CDPATH, $ENV, $BASH_ENV

    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.

  • No spawning if tainted $TERM doesn't look like a terminal name

    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).

New Opcode module and revised Safe module

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.

Embedding improvements

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.

Internal change: FileHandle class based on IO::* classes

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}.

Internal change: PerlIO abstraction interface

It is now possible to build Perl with AT&T's sfio IO packageinstead of stdio. See perlapio for more details, andthe INSTALL file for how to use it.

New and changed syntax

  • $coderef->(PARAMS)

    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).

New and changed builtin constants

  • __PACKAGE__

    The current package name at compile time, or the undefined value ifthere is no current package (due to a package; directive). Like__FILE__ and __LINE__, __PACKAGE__ does not interpolateinto strings.

New and changed builtin variables

  • $^E

    Extended error message on some platforms. (Also known as$EXTENDED_OS_ERROR if you use English).

  • $^H

    The current set of syntax checks enabled by use strict. See thedocumentation of strict for more details. Not actually new, butnewly documented.Because it is intended for internal use by Perl core components,there is no use English long name for this variable.

  • $^M

    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

    1. $^M = 'a' x (1<<16);

    would allocate a 64K buffer for use when in emergency.See the INSTALL file for information on how to enable this option.As a disincentive to casual use of this advanced feature,there is no use English long name for this variable.

New and changed builtin functions

  • delete on slices

    This now works. (e.g. delete @ENV{'PATH', 'MANPATH'})

  • flock

    is now supported on more platforms, prefers fcntl to lockf whenemulating, and always flushes before (un)locking.

  • printf and sprintf

    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:

    1. %ia synonym for %d
    2. %pa pointer (the address of the Perl value, in hexadecimal)
    3. %nspecial: *stores* the number of characters output so far
    4. into the next variable in the parameter list

    The new flags that go between the % and the conversion are:

    1. #prefix octal with "0", hex with "0x"
    2. hinterpret integer as C type "short" or "unsigned short"
    3. 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.

    See sprintf for a complete list of conversion and flags.

  • keys as an lvalue

    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

    1. keys %hash = 200;

    then %hash will have at least 200 buckets allocated for it. Thesebuckets will be retained even if you do %hash = (); use undef%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).

  • my() in Control Structures

    You can now use my() (with or without the parentheses) in the controlexpressions of control structures such as:

    1. while (defined(my $line = <>)) {
    2. $line = lc $line;
    3. } continue {
    4. print $line;
    5. }
    6. if ((my $answer = <STDIN>) =~ /^y(es)?$/i) {
    7. user_agrees();
    8. } elsif ($answer =~ /^n(o)?$/i) {
    9. user_disagrees();
    10. } else {
    11. chomp $answer;
    12. die "`$answer' is neither `yes' nor `no'";
    13. }

    Also, you can declare a foreach loop control variable as lexical bypreceding it with the word "my". For example, in:

    1. foreach my $i (1, 2, 3) {
    2. some_function();
    3. }

    $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.

  • pack() and unpack()

    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.)

  • sysseek()

    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.

  • use VERSION

    If the first argument to use 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. Because use occurs at compile time, this check happensimmediately during the compilation process, unlike require VERSION,which waits until runtime for the check. This is often useful if youneed to check the current Perl version before useing library moduleswhich have changed in incompatible ways from older versions of Perl.(We try not to do this more than we have to.)

  • use Module VERSION LIST

    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.

  • prototype(FUNCTION)

    Returns the prototype of a function as a string (or undef 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.)

  • srand

    The default seed for srand, which used to be time, 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, calling rand without first calling srandwould yield the same sequence of random numbers on most or all machines.Now, when perl sees that you're calling rand and haven't yet calledsrand, it calls srand 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.

  • $_ as Default

    Functions documented in the Camel to default to $_ now infact do, and all those that do are so documented in perlfunc.

  • m//gc does not reset search position on failure

    The m//g match iteration construct has always reset its targetstring's search position (which is visible through the pos operator)when a match fails; as a result, the next m//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. See perlopand perlre.

  • m//x ignores whitespace before ?*+{}

    The m//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.

  • nested sub{} closures work now

    Prior to the 5.004 release, nested anonymous functions didn't workright. They do now.

  • formats work right on changing lexicals

    Just like anonymous functions that contain lexical variablesthat change (like a lexical index variable for a foreach loop),formats now work properly. For example, this silently failedbefore (printed only zeros), but is fine now:

    1. my $i;
    2. foreach $i ( 1 .. 10 ) {
    3. write;
    4. }
    5. format =
    6. my i is @#
    7. $i
    8. .

    However, it still fails (without a warning) if the foreach is within asubroutine:

    1. my $i;
    2. sub foo {
    3. foreach $i ( 1 .. 10 ) {
    4. write;
    5. }
    6. }
    7. foo;
    8. format =
    9. my i is @#
    10. $i
    11. .

New builtin methods

The UNIVERSAL package automatically contains the following methods thatare inherited by all other classes:

  • isa(CLASS)

    isa returns true if its object is blessed into a subclass of CLASS

    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:

    1. use UNIVERSAL qw(isa);
    2. if(isa($ref, 'ARRAY')) {
    3. ...
    4. }
  • can(METHOD)

    can checks to see if its object has a method called METHOD,if it does then a reference to the sub is returned; if it does not thenundef is returned.

  • VERSION( [NEED] )

    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 of use.

    1. use A 1.2 qw(some imported subs);
    2. # implies:
    3. 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 to use UNIVERSAL in order to make these methodsavailable to your program. This is necessary only if you wish tohave isa available as a plain subroutine in the current package.

TIEHANDLE now supported

See perltie for other kinds of tie()s.

  • TIEHANDLE classname, LIST

    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.

    1. sub TIEHANDLE {
    2. print "<shout>\n";
    3. my $i;
    4. return bless \$i, shift;
    5. }
  • PRINT this, LIST

    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.

    1. sub PRINT {
    2. $r = shift;
    3. $$r++;
    4. return print join( $, => map {uc} @_), $\;
    5. }
  • PRINTF this, LIST

    This method will be triggered every time the tied handle is printed towith the printf() function.Beyond its self reference it also expects the format and list that waspassed to the printf function.

    1. sub PRINTF {
    2. shift;
    3. my $fmt = shift;
    4. print sprintf($fmt, @_)."\n";
    5. }
  • READ this LIST

    This method will be called when the handle is read from via the reador sysread functions.

    1. sub READ {
    2. $r = shift;
    3. my($buf,$len,$offset) = @_;
    4. print "READ called, \$buf=$buf, \$len=$len, \$offset=$offset";
    5. }
  • READLINE this

    This method will be called when the handle is read from. The methodshould return undef when there is no more data.

    1. sub READLINE {
    2. $r = shift;
    3. return "PRINT called $$r times\n"
    4. }
  • GETC this

    This method will be called when the getc function is called.

    1. sub GETC { print "Don't GETC, Get Perl"; return "a"; }
  • DESTROY this

    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.

    1. sub DESTROY {
    2. print "</shout>\n";
    3. }

Malloc enhancements

If perl is compiled with the malloc included with the perl distribution(that is, if perl -V:d_mymalloc is 'define') then you can printmemory statistics at runtime by running Perl thusly:

  1. 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().)

  • -DPERL_EMERGENCY_SBRK

    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.

  • -DPACK_MALLOC

    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. If PACK_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 in alignbytes) 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).

  • -DTWO_POT_OPTIMIZE

    Similarly to PACK_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.

Miscellaneous efficiency enhancements

Functions that have an empty prototype and that do nothing but returna fixed value are now inlined (e.g. sub PI () { 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 More Operating Systems

Support for the following operating systems is new in Perl 5.004.

Win32

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 like ExtUtils::MakeMaker and h2xs, so that many extensionsavailable on the Comprehensive Perl Archive Network (CPAN) can now bereadily built under Windows NT. See http://www.perl.com/ for moreinformation on CPAN and README.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. See README.cygwin32 in theperl distribution for more details on this port and how to obtain theCygwin32 toolkit.

Plan 9

See README.plan9 in the perl distribution.

QNX

See README.qnx in the perl distribution.

AmigaOS

See README.amigaos in the perl distribution.

Pragmata

Six new pragmatic modules exist:

  • use autouse MODULE => qw(sub1 sub2 sub3)

    Defers require MODULE until someone calls one of the specifiedsubroutines (which must be exported by MODULE). This pragma should beused with caution, and only when necessary.

  • use blib
  • use blib 'dir'

    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.

  • use constant NAME => VALUE

    Provides a convenient interface for creating compile-time constants,See Constant Functions in perlsub.

  • use locale

    Tells the compiler to enable (or disable) the use of POSIX locales forbuiltin operations.

    When use locale 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(but not in print). LC_NUMERIC is always used in write, sincelexical scoping of formats is problematic at best.

    Each use locale or no locale 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().

    See perllocale for more information.

  • use ops

    Disable unsafe opcodes, or any named opcodes, when compiling Perl code.

  • use vmsish

    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 makes exit take a genuine VMS status value instead ofassuming that exit 1 is an error; and 'time', which makes all timesrelative to the local time zone, in the VMS tradition.

Modules

Required Updates

Though Perl 5.004 is compatible with almost all modules that workwith Perl 5.003, there are a few exceptions:

  1. Module Required Version for Perl 5.004
  2. ------ -------------------------------
  3. Filter Filter-1.12
  4. LWP libwww-perl-5.08
  5. 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.

Installation directories

The installperl 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.

Module information summary

Brand new modules, arranged by topic rather than strictlyalphabetically:

  1. CGI.pm Web server interface ("Common Gateway Interface")
  2. CGI/Apache.pm Support for Apache's Perl module
  3. CGI/Carp.pm Log server errors with helpful context
  4. CGI/Fast.pm Support for FastCGI (persistent server process)
  5. CGI/Push.pm Support for server push
  6. CGI/Switch.pm Simple interface for multiple server types
  7. CPAN Interface to Comprehensive Perl Archive Network
  8. CPAN::FirstTime Utility for creating CPAN configuration file
  9. CPAN::Nox Runs CPAN while avoiding compiled extensions
  10. IO.pm Top-level interface to IO::* classes
  11. IO/File.pm IO::File extension Perl module
  12. IO/Handle.pm IO::Handle extension Perl module
  13. IO/Pipe.pm IO::Pipe extension Perl module
  14. IO/Seekable.pm IO::Seekable extension Perl module
  15. IO/Select.pm IO::Select extension Perl module
  16. IO/Socket.pm IO::Socket extension Perl module
  17. Opcode.pm Disable named opcodes when compiling Perl code
  18. ExtUtils/Embed.pm Utilities for embedding Perl in C programs
  19. ExtUtils/testlib.pm Fixes up @INC to use just-built extension
  20. FindBin.pm Find path of currently executing program
  21. Class/Struct.pm Declare struct-like datatypes as Perl classes
  22. File/stat.pm By-name interface to Perl's builtin stat
  23. Net/hostent.pm By-name interface to Perl's builtin gethost*
  24. Net/netent.pm By-name interface to Perl's builtin getnet*
  25. Net/protoent.pm By-name interface to Perl's builtin getproto*
  26. Net/servent.pm By-name interface to Perl's builtin getserv*
  27. Time/gmtime.pm By-name interface to Perl's builtin gmtime
  28. Time/localtime.pm By-name interface to Perl's builtin localtime
  29. Time/tm.pm Internal object for Time::{gm,local}time
  30. User/grent.pm By-name interface to Perl's builtin getgr*
  31. User/pwent.pm By-name interface to Perl's builtin getpw*
  32. Tie/RefHash.pm Base class for tied hashes with references as keys
  33. UNIVERSAL.pm Base class for *ALL* classes

Fcntl

New constants in the existing Fcntl modules are now supported,provided that your operating system happens to support them:

  1. F_GETOWN F_SETOWN
  2. O_ASYNC O_DEFER O_DSYNC O_FSYNC O_SYNC
  3. O_EXLOCK O_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():

  1. LOCK_SH LOCK_EX LOCK_NB LOCK_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. use Fcntl ':flock').

IO

The IO module provides a simple mechanism to load all the IO modules at onego. Currently this includes:

  1. IO::Handle
  2. IO::Seekable
  3. IO::File
  4. IO::Pipe
  5. IO::Socket

For more information on any of these modules, please see itsrespective documentation.

Math::Complex

The Math::Complex module has been totally rewritten, and now supportsmore operations. These are overloaded:

  1. + - * / ** <=> neg ~ abs sqrt exp log sin cos atan2 "" (stringify)

And these functions are now exported:

  1. pi i Re Im arg
  2. log10 logn ln cbrt root
  3. tan
  4. csc sec cot
  5. asin acos atan
  6. acsc asec acot
  7. sinh cosh tanh
  8. csch sech coth
  9. asinh acosh atanh
  10. acsch asech acoth
  11. cplx cplxe

Math::Trig

This new module provides a simpler interface to parts of Math::Complex forthose who need trigonometric functions only for real numbers.

DB_File

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.

Net::Ping

Major rewrite - support added for both udp echo and real icmp pings.

Object-oriented overrides for builtin operators

Many of the Perl builtins returning lists now haveobject-oriented overrides. These are:

  1. File::stat
  2. Net::hostent
  3. Net::netent
  4. Net::protoent
  5. Net::servent
  6. Time::gmtime
  7. Time::localtime
  8. User::grent
  9. User::pwent

For example, you can now say

  1. use File::stat;
  2. use User::pwent;
  3. $his = (stat($filename)->st_uid == pwent($whoever)->pw_uid);

Utility Changes

pod2html

  • Sends converted HTML to standard output

    The pod2html 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's pod2html did.Use the --outfile=FILENAME option to write to a file.

xsubpp

  • void XSUBs now default to returning nothing

    Due to a documentation/implementation bug in previous versions ofPerl, XSUBs with a return type of void 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 returning void, 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 of SV *.

    For backward compatibility, xsubpp tries to guess whether avoid XSUB is really void or if it wants to return an SV *.It does so by examining the text of the XSUB: if xsubpp findswhat looks like an assignment to ST(0), it assumes that theXSUB's return type is really SV *.

C Language API Changes

  • gv_fetchmethod and perl_call_sv

    The gv_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 to perl_call_sv.Instead, you should use the GvCV macro on the GV to extract its CV,and pass the CV to perl_call_sv.

    The most likely symptom of passing the result of gv_fetchmethod toperl_call_sv is Perl's producing an "Undefined subroutine called"error on the second call to a given method (since there is no cacheon the first call).

  • perl_eval_pv

    A 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 and perlcall for details and examples.

  • Extended API for manipulating hashes

    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 as SV*s, so that tied 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 use SV* keys. Theseadditions also make it feasible to manipulate HE*s (hash entries),which can be more efficient. See perlguts for details.

Documentation Changes

Many of the base and library pods were updated. Thesenew pods are included in section 1:

  • perldelta

    This document.

  • perlfaq

    Frequently asked questions.

  • perllocale

    Locale support (internationalization and localization).

  • perltoot

    Tutorial on Perl OO programming.

  • perlapio

    Perl internal IO abstraction interface.

  • perlmodlib

    Perl module library and recommended practice for module creation.Extracted from perlmod (which is much smaller as a result).

  • perldebug

    Although not new, this has been massively updated.

  • perlsec

    Although not new, this has been massively updated.

New Diagnostics

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):

  1. (W) A warning (optional).
  2. (D) A deprecation (optional).
  3. (S) A severe warning (mandatory).
  4. (F) A fatal error (trappable).
  5. (P) An internal error you should never see (trappable).
  6. (X) A very fatal error (nontrappable).
  7. (A) An alien error message (not generated by Perl).
  • "my" variable %s masks earlier declaration in same scope

    (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.

  • %s argument is not a HASH element or slice

    (F) The argument to delete() must be either a hash element, such as

    1. $foo{$bar}
    2. $ref->[12]->{"susie"}

    or a hash slice, such as

    1. @foo{$bar, $baz, $xyzzy}
    2. @{$ref->[12]}{"susie", "queue"}
  • Allocation too large: %lx

    (X) You can't allocate more than 64K on an MS-DOS machine.

  • Allocation too large

    (F) You can't allocate more than 2^31+"small amount" bytes.

  • Applying %s to %s will act on scalar(%s)

    (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 and map for alternatives.

  • Attempt to free nonexistent shared string

    (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.

  • Attempt to use reference as lvalue in substr

    (W) You supplied a reference as the first argument to substr() usedas an lvalue, which is pretty strange. Perhaps you forgot todereference it first. See substr.

  • Bareword "%s" refers to nonexistent package

    (W) You used a qualified bareword of the form Foo::, butthe compiler saw no other uses of that namespace before that point.Perhaps you need to predeclare a package?

  • Can't redefine active sort subroutine %s

    (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 write sort { &func } @x instead of sort func @x.

  • Can't use bareword ("%s") as %s ref while "strict refs" in use

    (F) Only hard references are allowed by "strict refs". Symbolic referencesare disallowed. See perlref.

  • Cannot resolve method `%s' overloading `%s' in package `%s'

    (P) Internal error trying to resolve overloading specified by a methodname (as opposed to a subroutine reference).

  • Constant subroutine %s redefined

    (S) You redefined a subroutine which had previously been eligible forinlining. See Constant Functions in perlsub for commentary andworkarounds.

  • Constant subroutine %s undefined

    (S) You undefined a subroutine which had previously been eligible forinlining. See Constant Functions in perlsub for commentary andworkarounds.

  • Copy method did not return a reference

    (F) The method which overloads "=" is buggy. See Copy Constructor in overload.

  • Died

    (F) You passed die() an empty string (the equivalent of die "") oryou called it with no args and both $@ and $_ were empty.

  • Exiting pseudo-block via %s

    (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. See sort.

  • Identifier too long

    (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.

  • Illegal character %s (carriage return)

    (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;).

  • Illegal switch in PERL5OPT: %s

    (X) The PERL5OPT environment variable may only be used to set thefollowing switches: -[DIMUdmw].

  • Integer overflow in hex number

    (S) The literal hex number you have specified is too big for yourarchitecture. On a 32-bit architecture the largest hex literal is0xFFFFFFFF.

  • Integer overflow in octal number

    (S) The literal octal number you have specified is too big for yourarchitecture. On a 32-bit architecture the largest octal literal is037777777777.

  • internal error: glob failed

    (P) Something went wrong with the external program(s) used for globand <*.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 that d_csh should be 'undef') so that Perl willthink csh is missing. In either case, after editing config.sh, run./Configure -S and rebuild Perl.

  • Invalid conversion in %s: "%s"

    (W) Perl does not understand the given format conversion.See sprintf.

  • Invalid type in pack: '%s'

    (F) The given character is not a valid pack type. See pack.

  • Invalid type in unpack: '%s'

    (F) The given character is not a valid unpack type. See unpack.

  • Name "%s::%s" used only once: possible typo

    (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 (the use vars pragma isprovided for just this purpose).

  • Null picture in formline

    (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. See perlform.

  • Offset outside string

    (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 that sysread()ing past the bufferwill extend the buffer and zero pad the new area.

  • Out of memory!

    (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 trappable once.

  • Out of memory during request for %s

    (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.

  • panic: frexp

    (P) The library function frexp() failed, making printf("%f") impossible.

  • Possible attempt to put comments in qw() list

    (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:

    1. @list = qw(
    2. a # a comment
    3. b # another comment
    4. );

    when you should have written this:

    1. @list = qw(
    2. a
    3. b
    4. );

    If you really want comments, build your list theold-fashioned way, with quotes and commas:

    1. @list = (
    2. 'a', # a comment
    3. 'b', # another comment
    4. );
  • Possible attempt to separate words with commas

    (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:

    1. 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:

    1. qw! a b c !;
  • Scalar value @%s{%s} better written as $%s{%s}

    (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.

  • Stub found while resolving method `%s' overloading `%s' in %s

    (P) Overloading resolution over @ISA tree may be broken by importing stubs.Stubs should never be implicitly created, but explicit calls to canmay break this.

  • Too late for "-T" option

    (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.

  • untie attempted while %d inner references still exist

    (W) A copy of the object returned from tie (or tied) was stillvalid when untie was called.

  • Unrecognized character %s

    (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.

  • Unsupported function fork

    (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 to perl_, perl__, and so on.

  • Use of "$$<digit>" to mean "${$}<digit>" is deprecated

    (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.

  • Value of %s can be "0"; test with defined()

    (W) In a conditional expression, you used <HANDLE>, <*> (glob), each(),or readdir() 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 the defined operator.

  • Variable "%s" may be unavailable

    (W) An inner (nested) anonymous subroutine is inside a namedsubroutine, and outside that is another subroutine; and the anonymous(innermost) subroutine is referencing a lexical variable defined inthe outermost subroutine. For example:

    1. sub outermost { my $a; sub middle { sub { $a } } }

    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 the sub {} syntax. Perl has specificsupport for shared variables in nested anonymous subroutines; a namedsubroutine in between interferes with this feature.

  • Variable "%s" will not stay shared

    (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 subroutineswill never share the given variable.

    This problem can usually be solved by making the inner subroutineanonymous, using the sub {} syntax. When inner anonymous subs thatreference variables in outer subroutines are called or referenced,they are automatically rebound to the current values of suchvariables.

  • Warning: something's wrong

    (W) You passed warn() an empty string (the equivalent of warn "") oryou called it with no args and $_ was empty.

  • Ill-formed logical name |%s| in prime_env_iter

    (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.

  • Got an error from DosAllocMem

    (P) An error peculiar to OS/2. Most probably you're using an obsoleteversion of Perl, and this should not happen anyway.

  • Malformed PERLLIB_PREFIX

    (F) An error peculiar to OS/2. PERLLIB_PREFIX should be of the form

    1. prefix1;prefix2

    or

    1. prefix1 prefix2

    with nonempty prefix1 and prefix2. If prefix1 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" in README.os2.

  • PERL_SH_DIR too long

    (F) An error peculiar to OS/2. PERL_SH_DIR is the directory to find thesh-shell in. See "PERL_SH_DIR" in README.os2.

  • Process terminated by SIG%s

    (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"in README.os2.

BUGS

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 at http://www.perl.com/perl/ , the PerlHome Page.

If you believe you have an unreported bug, please run the perlbugprogram included with your release. Make sure you trim your bug downto a tiny but sufficient test case. Your bug report, along with theoutput of perl -V, will be sent off to <[email protected]> to beanalysed by the Perl porting team.

SEE ALSO

The Changes file for exhaustive details on what changed.

The INSTALL file for how to build Perl. This file has beensignificantly updated for 5.004, so even veteran users shouldlook through it.

The README file for general stuff.

The Copying file for copyright information.

HISTORY

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

Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) What's new for perl5.005The Perl Artistic License (Berikutnya)