perl5100delta
[↑] НАЗВАНИЕ
perl5100delta - Отличия версии 5.10 от 5.8
[↑] ОПИСАНИЕ
В этом документе описываются различия между версиями perl 5.8 и perl 5.10.
Многие изменения произошедшие после релиза 5.8 задокументированы в подверсиях 5.8.X (страницы perl5.8[1-8]?delta) и поэтому они здесь не приводятся.
[↑] Улучшения в ядре
[↑] Прагма feature
Прагма feature
используется для включения
нового синтаксиса, что нарушает обратную совместимость со старшими версиями perl. Эта прагма является
лексической как strict
или warnings
.
В настоящее время следующие новые функции доступны: switch
(оператор-переключатель), say
( добавлена встроенная функция say
), и
state
( добавлено ключевое слово state
для объявления "статических"
переменных). Эти функции описаны в соответствующих разделах этого документа.
Прагма feature
также косвенно загружается когда вы используете конструкцию
use VERSION
бОльшую или равную версии 5.9.5. Подробней об этом документе
feature.
[↑] Новый параметр запуска программы из командной строки -E
Параметр -E эквивалентен *-e*, но неявно включает поддержку новых
функций ( как если бы вы написали так: use feature ":5.10"
).
[↑] Оператор определимости
Реализован новый оператор //
- оператор определимости(defined-or).
Следующее выражение:
$a // $b
просто эквивалентно
defined $a ? $a : $b
и выражение
$c //= $d;
может быть использовано вместо
$c = $d unless defined $c;
Оператор //
имеет такой же приоритет и ассоциативность как и оператор ||.
Специальное внимание было уделено тому, чтобы этот оператор делал то, что
вы имеете в виду не ломая старого кода, но некоторые
крайние случаи, связаные с пустым регулярным выражением теперь могут
анализироваться по-разному. Подробнее об этом на странице perlop
[↑] Переключатель и оператор сопоставления
Теперь есть оператор переключения(switch statement). Он доступен
когда в силе эффект use feature 'switch'
. Эта функция включает в себя
три новых ключевых слова, given
, when
, и default
:
given ($foo) { when (/^abc/) { $abc = 1; } when (/^def/) { $def = 1; } when (/^xyz/) { $xyz = 1; } default { $nothing = 1; } }
На странице "Switch statements" RU_LINK "Оператор переключения" in perlsyn
имеется подробное описание о том, как Perl сопоставляет оператору переключения
переменную напротив условия when
Этот вид сопоставления назван умным сопоставлением(smart match) и он также
может использоваться вне оператора переключения, через новый оператор ~~
.
Подробности в разделе "Smart matching in detail" RU_LINK "Умное сопоставление в деталях" in perlsyn.
Эта возможность была предоставлена Робином Хьюстоне.
[↑] Регулярные выражения
- Рекурсивные шаблоны
Теперь можно писать рекурсивные структуры без использования конструкции
(??{}). Этот новый способ более эффективен и во многих случаях легче читается.Каждый захват скобок может теперь рассматриваться как независимый шаблон, который может быть введен с использованием синтаксиса
(?PARNO)( гдеPARNO- положение для "номера круглых скобок"). Например, следующий шаблон будет сопоставлять вложенные сбалансированные угловые скобки./ ^ # начало строки ( # начало первого буфера захвата < # соответствует открывающей угловой скобке (?: # соответствие одному из: (?> # не захватывать в буфер все что находится внутри этой группы [^<>]+ # один или несколько любых символов кроме угловых скобок ) # конец блока без захвата | # ... или ... (?1) # вернуться к началу первого буфера захвата )* # 0 или более раз. > # соответствует закрывающей угловой скобке ) # конец первого буфера захвата $ # конец строки /x
Пользователи PCRE должны отметить, что рекурсивная функция регулярных выражений в Perl позволяет возвращаться в рекурсивный шаблон, в то время как PCRE рекурсия носит "притяжательный" характер.
- Именованные захватывающие скобки
Теперь в шаблоне можно именовать захватывающие скобки и обращаться к их содержимому по имени. Синтаксис именования
(?<NAME>....). Это позволяет ссылаться к именованным буферам используя синтаксис\k<NAME>. В шаблоне, новые магические хэши%+и%-могут быть использованы для доступа к содержимому буфера захвата.Таким образом, чтобы заменить все дублирующие символы одной копией, можно написать
s/(?<letter>.)\k<letter>/$+{letter}/gТолько буферы с определенным содежимым будут "видимы" в хэше
%+, так это возможно сделать примерно следующим образомforeach my $name (keys %+) { print "content of buffer '$name' is $+{$name}\n"; }
Хэш
%-является более полным, посколько он будет содержать массив ссылок захватывающих значений из всех захватывающих скобок с подобным именем, если их несколько.%+и%-реализованы как связанные хэши через новый модульTie::Hash::NamedCapture.Пользователи, использующие регулярную машину .NET найдут, что perl реализация буферов в что числовое упорядочивание буферов является последовательным, и не "названный первым, который тогда назван". Таким образом шаблон
/(A)(?<B>B)(C)(?<D>D)/$1 будет содержать 'A', $2 будет содержать 'B', $3 будет содержать 'C' и $4 будет 'D', что .NET программист будет ожидать. Это продуманная функция :) (Yves Orton)
- Сверхжадные квантификаторы
Perl теперь поддерживает "сверхжадные квантификаторы"(possessive quantifier) которые захватывают максимальное соответствие и никогда не возвращаются назад. Таким образом они могут быть использованы для контроля отката назад(control backtraking). Сверхжадный квантификатор синтаксически может использоваться там же где и нежадный модификатор(non-greedy)
?, только вместо него ставится модификатор+. В результате получаются примерно такие конструкции?+,*+,++,{min,max}+. - Глаголы Backtracking контроля
Машина регулярных выражений поддерживает ряд глаголов специального назначения для контроля отката назад(backtrack control): (*THEN), (*PRUNE), (*MARK), (*SKIP), (*COMMIT), (*FAIL) и (*ACCEPT). За подробностями обращайтесь к странице perlre. (Yves Orton)
- Относительные обратные ссылки (Relative backreferences)
Новые синтаксические конструкции
\g{N}или\gNгде "N" десятичное число позволяет безопасную форму обозначений ссылок на найденный текст а также позволяет относительные ссылки на найденный текст. Это должно сделать легче генерацию и вставку шаблонов, которые содержат ссылки на найденный текст. Смотрите ""Capture buffers" RU_LINK Буферы захвата" in perlre. (Yves Orton) - Метазнак
\KФункциональность модуля Regexp::Keep Джеффа Пинуана(Jeff Pinyan) была встроена в ядро. В регулярных выражениях вы можете теперь использовать специальный метасимвол
\Kкак способ исользовать что-нибудь наподобие конструкции плавающего позитивного заглядывания назадs/(foo)bar/$1/gчто может быть преобразовано в
s/foo\Kbar//gкоторый является гораздо более эффективным. (Yves Orton)
- Вертикальный, горизонтальный пробел и разрыв строки
Регулярные выражения теперь распознают escape последовательности
\vи\hкоторые соответствуют символам вертикального и горизонтального пробела.\vи\hлогично противоположны первым двум метасимволам.\rсоответствует общему символу разрыва строки, то есть символу вертикального пробела плюс последовательность символов"\x0D\x0A".
[↑]say()
Новая встроенная функция say() может использоваться только если объявлено
use feature 'say'
. Функция подобна функции print(), но она дополнительно
после выведенной строки добавляет символ перевода строки (\n).
Смотрите раздел "say" in perlfunc. (Robin Houston)
[↑] Лексический $_
Переменную по умолчанию $_
теперь может быть локализована, объявляя
ее также как обычно объявляются переменные с лексической
областью видимости.
my $_;
Все операции, связанные с переменной по умолчанию $_
теперь используют
вместо глобальной ее лексическую версию, если она существует.
Если $_
объявлена как лексическая переменная, тогда внутри
блока функций map
и grep
будут также использованы лексически
локализованные $_
, с областью видимости охватывающего ее блока.
В области видимости, где $_
была локализована лексически, вы все равно
можете обратиться к глобальной версии $_
обращаясь к ней через $::_
или
просто переопределив лексическую декларацию глобальной our $_
.
[↑] Прототип _
A new prototype character has been added. _
is equivalent to $
but
defaults to $_
if the corresponding argument isn't supplied. (both $
and _
denote a scalar). Due to the optional nature of the argument, you
can only use it at the end of a prototype, or before a semicolon.
Это влечет некоторые последствия несовместимости: функция prototype()
была скорректирована для возврата _
для некоторых встроеных в
соответствующих случаях ( для примера, prototype('CORE::rmdir')
).
(Rafael Garcia-Suarez)
[↑] Блоки UNITCHECK
Введена еще одна специальная подпрограмма - UNITCHECK
в дополнение
к существующим BEGIN
, CHECK
, INIT
и END
.
CHECK
и INIT
блоки, которые используются для некоторых специальных
целей, всегда выполняются при переходе между компиляцией и выполнением
основной программы, и потому бесполезны всякий раз, когда код подгружается
во время исполнения. С другой стороны, UNITCHECK
блоки выполнены
сразу после сегмента программы, который определен им был скомпилирован.
На странице perlmod об этом рассказывается подробнее (Alex Gough)
[↑] Новая прагма mro
Добавлена новая прагма, mro
( для порядка разрешения метода(Method
Resolution Order )). Это позволяет переключаться на базовый класс
(per-class basis), алгоритм, который perl использует для поиска унаследованных
методов в иерархии множественного наследования. По умолчанию MRO не
изменен ( Поиск в глубину (DFS, Depth First Search ). Другой MRO
имеется в наличии: C3 алгоритм. Смотрите mro для получения более
подробной информации (Brandon Black)
Отметим, что в связи с изменениями в осуществлении поиска иерархии класса, код,
который используется для присвоения *ISA
неопределенного значения скорее
всего будет прерван. Во всяком случае, присвоение неопределенного значения
*ISA
имел побочный эффект удаления магического массива @ISA а это не должно
было происходить. Также, кэш *::ISA::CACHE::
больше не существует, чтобы
заставить сбросить кэш @ISA, теперь нужно использовать mro
API, или же
просто осуществить присвоение массиву @ISA (например @ISA = @ISA
).
[↑] В системе Windows readdir() может возвращать "короткое имя"
Функция readdir() может возвращать "короткое имя" когда полное имя содержит символы, не принадлежащие кодовой таблице ANSI (ANSI codepage). Аналогично Cwd::cwd() может возвращать короткое имя директории, а glob() может возвращать короткие имена файлов и директорий. В файловой системе NTFS эти короткие имена всегда могут быть представлены в кодовой таблице ANSI. Это не будет верно для всех остальных драйверов файловых систем (file system drivers); например файловая система FAT хранит короткие имена в кодовой таблице OEM, так некоторые файлы на томах FAT остаются недоступными через ANSI API.
Кроме того, $^X, @INC, и $ENV{PATH} обрабатываются препроцессором при запуске, чтобы проверить все пути на валидность в кодовой таблице ANSI (если это возможно)
Функция Win32::GetLongPathName() теперь возвращает UTF-8 закодированное корректное имя файла вместо использования замены символов для того, чтобы подогнать имя к кодовой таблице ANSI. Новая функция Win32::GetLongPathName() может быть использована для преобразования полного имени файла в короткое, только если полное имя не пожет быть представлено в кодовой таблице ANSI.
Многие другие функции в модуле win32
были усовершенствованы для
обработки UTF-8 закодированных аргументов. Более подробно об этом в
Win32.
[↑] readpipe() теперь можно переопределить
Встроенная функция readpipe() теперь может быть переопределена. Это позволяет
переопределить ее аналог - оператор qx//
(также известный, как оператор
``
). Кроме того, теперь по умолчанию исползуется $_
, если не
предоставлено никаких аргументов.(Rafael Garcia-Suarez)
[↑] Аргумент по умолчанию для readline()
Теперь readline() по умолчанию использует *ARGV
если ему не перадано
аргументов. (Rafael Garcia-Suarez)
[↑] Переменные класса 'state'
Введен новый класс переменных. Переменные состояния (state variables)
подобны лексическим переменным, но декларированные ключевым словом state
вместо my
. Они видны только в своей лексической области, но их значения
стойкие: в отличие от лексических переменных, они не становятся неопределенными
при выходе из их области видимости, но сохраняют свое прежнее значение.
(Rafael Garcia-Suarez, Nicholas Clark)
Для использования 'state' переменных, нужно предварительно объявить:
use feature 'state';
or by using the -e
command-line switch in one-liners.
See "Persistent variables via state()" in perlsub.
[↑] Операторы тестирования стека
В качестве новой формы синтаксического сахара теперь доступны операторы
тестирования стека. Вы можете теперь писать f -w -x $file
в ряд,
что тоже самое -x $file && -w _ && -f _
. Подробнее в "-X" in perlfunc
[↑]UNIVERSAL::DOES()
В классе UNIVERSAL
появился новый метод DOES()
. Он был добавлен для
решения семантической проблемы с методом isa()
. isa()
проверяет
наследование, тогда как DOES()
разработан для его замещения, что
позволяет авторам модулей использовать другие типы отношений
между классами (в добавок к наследованию). (chromatic)
Подробнее об этом в разделе ""$obj->DOES( ROLE )" RU_LINK Метод "$obj->DOES( ROLE )" в классе UNIVERSAL" in UNIVERSAL.
[↑] Форматы
Форматы улучшены несколькими способами. Новый тип поля - ^* может быть
использован для каждой строки текста переменной ширины. Нулевые символы
в строке шаблона обрабатываются корректно. Совместное использование @#
и ~~
вместе будет приводить к возникновению ошибки времени компиляции, так как
указанные форматы полей несовместимы. Расширен документ perlform, исправлены
различные недоработки.
[↑] Модификаторы pack() и unpack()
Два новых модификатора порядка байтов, >-(тупоконечный(big-endian) модификатор) и
< - ("остроконечный"(little-endian) модификатор), которые могут быть использованы
в шаблонах pack()
и unpack()
для принудительного определения
порядка байтов. См. "pack" in perlfunc и perlpacktut.
[↑]no VERSION
Теперь можно использовать NO
с указанием номера версии perl,
что будет означать, что можно использовать старшие версии perl.
[↑] chdir
, chmod
и chown
для дескрипторов файлов
chdir
, chmod
и chown
можно использовать с дескрипторами
файлов так же как и с именами файлов, если система поддерживает соответственно
fchdir
, fchmod
и fchown
. Эта возможность включена благодаря патчу, предоставленному
Gigle Aas.
[↑] Группы процессов в ОС
$(
и $)
теперь возвращают группы процессов в том порядке, в котором их
возвращает операционная система. Эта стало возможным благодаря Gigle Aas.
[↑] Рекурсия в sort()
Вы теперь можете использовать рекурсивный вызов подпрограмм в функции sort(), благодаря Robin Houston.
[↑] Исключения в свертывании констант
Процедура свертывания констант теперь завернута в обработчике исключений, и если свертывание констант вызывает исключительную ситуацию (например в результате попытки деления на ноль), perl сохраняет текущий опкод , а не прерывает всю программу. (Nicholas Clark, Dave Mitchell)
[↑] Фильтры исходного кода в @INC
Это реализовано для совершенствования механизма подпрограмм-обработчиков
в @INC
, добавлением фильтра исходного кода в начале открытого дескриптора
возвращаемого обработчиком.
[↑] Новые внутренние переменные
${^RE_DEBUG_FLAGS}Эта переменная контролирует, чтобы флаги отладки были в силе для машины регулярных выражений во время исполнения при использовании
use re "debug". См. re.${^CHILD_ERROR_NATIVE}This variable gives the native status returned by the last pipe close, backtick command, successful call to wait() or waitpid(), or from the system() operator. See perlrun for details. (Contributed by Gisle Aas.)
${^RE_TRIE_MAXBUF}${^WIN32_SLOPPY_STAT}См. Функция stat в Windows .
[↑] Разное
unpack()
теперь по умолчанию распаковывает содержимое переменной $_
.
mkdir()
без агрументов по умолчанию работает с $_
.
Внутренний дамп вывода был усовершенствован, так что непечатаемые символы
такие как символ новой строки "\n"
и символ забоя(backspace) "\b"
выводятся в
в нотации \X
, вместо восьмеричного числа.
Опция -C больше не может использоваться в строке #!
. Она там
не воспринимается в любом случае, посколько стандартные потоки уже
настроены на точку исполнения perl интерпретатора. Вместо этого вы можете
использовать binmode()
чтобы получить желаемое поведение.
[↑]UCD 5.0.0
Копия Базы Символов Юникода(Unicode Character Database) которая включена в поставку perl 5, обновлена до версии 5.0.0.
[↑]MAD
MAD, расшифровывается как Miscellaneous Attribute Decoration (примерный перевод
на русский - Различные обозначения атрибутов.
MAD пока в развитии, Perl 5 к Perl 6.
Чтобы его включить, необходимо передать аргумент -Dmad
при
конфигурировании и сборке perl. Но это повлияет на скорость работы perl;
причем он проходит не все тесты из тестового набора. (Larry Wall, Nicholas Clark).
[↑] kill() в Windows
On Windows platforms, kill(-9, $pid)
now kills a process tree.
(On UNIX, this delivers the signal to all processes in the same process
group.)
[↑] Несовместимые изменения
[↑] Упаковка UTF-8 строк
Изменена семантика pack()
и unpack()
относительно данных в кодировке
UTF-8. Теперь по умолчанию строка обрабатывается посимвольно, а не побайтно, как было раньше.
Примечательно, что код, который использовал такие выражения как
pack("a*", $string для определения кодированной строки, теперь получит
неизменнную строку $string. Вы можете включить старое поведение
этих функций используя use bytes
.
Для совместимости с pack(), C0
в unpack() шаблонах указывает на то, что
данные должны быть обработаны в посимвольном режиме, т.е символ за символом, в
противоположность ему, U0
в unpack() определяет UTF-8 режим, в
котором упакованная строка обрабатывается в его UTF-8-закодированной форме
на основе побайтовой обработки строк. Это обеспечивает обратную совместимость с perl 5.8.X, а теперь
совместим так же между pack() и unpack().
Кроме того, C0
и U0
могут быть так же использованы в шаблонах pack() для
указания соответственно посимвольного и побайтного режимов.
C0
и U0
в середине шаблона формата в pack и unpack теперь переключаются на
указанный режим кодирования, соблюдая группировку круглых скобок. Ранее,
круглые скобки игнорировались.
Также добавился еще один формат для функции pack() - w
предназначен
для замены старого формата c
. c
содержит unsigned символы, закодированные
как байты в строке во внутреннем представлении. w
представляет
значения символов без знака(логичные)(анг. unsigned(logical) character),
код которых может быть больше 255. Поэтому он более
надежен при работе с данными потенциально закодированными в кодировке UTF-8
( в то время как c
упаковывает значения выходящие за пределы диапазона 0..255, не соблюдая
кодировку строки).
На практике, это значит, что форматы в pack() теперь нейтральны к кодировке,
за исключением c
.
Для надежности, формат a
в unpack() теперь удаляет все концевые пробелы Unicode.
До perl 5.9.2, формат использовался для снятия только обычных ASCII пробельных символов.
[↑] Особенности подсчета байтов/символов в unpack()
Новый шаблон символов в unpack() - "."
, возвращает количество байтов или
символов в строке(в зависимости от выбранного режима кодирования, см. выше).
[↑] Удалены переменные $*
и $#
Удалена переменная $*
, которая ранее была объявлена устаревшей в пользу
модификаторов /s и /m регулярных выражений.
Удалена переменная $#
(выходной формат для чисел).
Добавлено два серьёзных диагностических сообщения - $# is no longer supported,
$* is no longer supported,
которые срабатывают при попытке использования соответствующих переменных $#
и $*
.
[↑] Левые значения substr() больше не имеют фиксированной ширины
Левые значения возвращались в форме трех аргументов substr(), используемых для "фиксированной ширины окна"(анг."fixed length window") в исходной строке. В некоторых случаях это могло приводить к непредсказуемым результатам. Теперь ширина окна настраивается самостоятельно на длину строки ей соответствующей.
[↑] Распознавание -f _
Идентификатор _
в настоящее время воспринимается как 'голое слово' после оператора
тестирования файла. Это решает ряд вопросов ошибочного анализа кода, когда определена
глобальная подпрограмма с именем _
.
[↑]:unique
Атрибут :unique
не производит никакой операции, поспольку его реализация
имела фундаментальные недостатки и проблемы с потокобезопасностью.
[↑] Эффекты прагм в eval()
Значение времени компиляции(compile-time value) внутренней вспомогательной переменной %^H
теперь определяется и в коде, скомпилированном в eval("")
. Это делает
его полезным для выполнения лексических прагм.
В качестве побочного эффекта переменной %^H
- константы перегрузки теперь
действуют внутри eval("").
[↑]chdir FOO
Когда в функцию chdir()
передается голое слово(bareword), оно
воспринимается как дескриптор файла. В ранних релизах perl голое слово в chdir
интерпретировалось как имя каталога.(Gisle Aas)
[↑] Обработка файлов .pmc
An old feature of perl was that before require
or use
look for a
file with a .pm extension, they will first look for a similar filename
with a .pmc extension. If this file is found, it will be loaded in
place of any potentially existing file ending in a .pm extension.
Previously, .pmc files were loaded only if more recent than the matching .pm file. Starting with 5.9.4, they'll be always loaded if they exist.
[↑]$^V is now a version
object instead of a v-string
$^V can still be used with the %vd
format in printf, but any
character-level operations will now access the string representation
of the version
object and not the ordinals of a v-string.
Expressions like substr($^V, 0, 2)
or split //, $^V
no longer work and must be rewritten.
[↑] @- и @+ в регексах
The special arrays @-
and @+
are no longer interpolated in regular
expressions. (Sadahiro Tomoyuki)
[↑] $AUTOLOAD теперь может быть меченной
Если вы вызовите подпрограмму по меченной имени, и если она содержит отсылку к функции AUTOLOAD, то $AUTOLOAD будет (правильно) помечен. (Rick Delaney).
[↑] Проверка меченных данных и printf
When perl is run under taint mode, printf()
and sprintf()
will now
reject any tainted format argument. (Rafael Garcia-Suarez)
[↑] undef и обработчики сигналов
Отмена определения или удаление обработчика сигнала через undef $SIG{FOO}
теперь
эквивалентно установке его в 'DEFAULT'
. (Rafael Garcia-Suarez)
[↑] Структуры и разыменование в defined(),
use strict 'refs'
был игрорирование принимая жесткую ссылку в аргументе
в defined(), как в:
use strict 'refs'; my $x = 'foo'; if (defined $$x) {...}
This now correctly produces the run-time error Can't use string as a
SCALAR ref while "strict refs" in use.
defined @$foo
and defined %$bar
are now also subject to strict
'refs'
(that is, $foo
and $bar
shall be proper references there.)
(defined(@foo)
and defined(%bar)
are discouraged constructs anyway.)
(Nicholas Clark)
[↑] (?p{}) удалён
The regular expression construct (?p{}), which was deprecated in perl
5.8, has been removed. Use (??{})
instead. (Rafael Garcia-Suarez)
[↑] Удален псевдо-хэш
Support for pseudo-hashes has been removed from Perl 5.9. (The fields
pragma remains here, but uses an alternate implementation.)
[↑] Удален компилятор bytecode и perlcc
perlcc
, the byteloader and the supporting modules (B::C, B::CC,
B::Bytecode, etc.) are no longer distributed with the perl sources. Those
experimental tools have never worked reliably, and, due to the lack of
volunteers to keep them in line with the perl interpreter developments, it
was decided to remove them instead of shipping a broken version of those.
The last version of those modules can be found with perl 5.9.4.
However the B compiler framework stays supported in the perl core, as with the more useful modules it has permitted (among others, B::Deparse and B::Concise).
[↑] Удалён JPL
JPL (Java-Perl Lingo) был удален из архива исходного кода perl.
[↑] Рекурсивные наследования обраруживаются раньше
Perl will now immediately throw an exception if you modify any package's
@ISA
in such a way that it would cause recursive inheritance.
Previously, the exception would not occur until Perl attempted to make
use of the recursive inheritance while resolving a method or doing a
$foo->isa($bar)
lookup.
[↑] Модули и директивы(pragmata)
[↑] Обновление стандартных модулей
Even more core modules are now also available separately through the
CPAN. If you wish to update one of these modules, you don't need to
wait for a new perl release. From within the cpan shell, running the
'r' command will report on modules with upgrades available. See
perldoc CPAN
for more information.
[↑] Изменения директив
featureThe new pragma
featureis used to enable new features that might break old code. See "Thefeaturepragma" above.mroThis new pragma enables to change the algorithm used to resolve inherited methods. See "New Pragma,
mro" above.- Область видимости прагмы
sortThe
sortpragma is now lexically scoped. Its effect used to be global. - Область видимости для прагм
bignum,bigint,bigratThe three numeric pragmas
bignum,bigintandbigratare now lexically scoped. (Tels) baseThe
basepragma now warns if a class tries to inherit from itself. (Curtis "Ovid" Poe)strictandwarningsstrictandwarningswill now complain loudly if they are loaded via incorrect casing (as inuse strict;). (Johan Vromans)versionThe
versionmodule provides support for version objects.warningsThe
warningspragma doesn't loadcarpanymore. That means that code that usedcarproutines without having loaded it at compile time might need to be adjusted; typically, the following (faulty) code won't work anymore, and will require parentheses to be added after the function name:use warnings; require Carp; Carp::confess 'argh';
lesslessnow does something useful (or at least it tries to). In fact, it has been turned into a lexical pragma. So, in your modules, you can now test whether your users have requested to use less CPU, or less memory, less magic, or maybe even less fat. See less for more. (Joshua ben Jore)
[↑] Новые модули
-
encoding::warnings, by Audrey Tang, is a module to emit warnings whenever an ASCII character string containing high-bit bytes is implicitly converted into UTF-8. It's a lexical pragma since Perl 5.9.4; on older perls, its effect is global. -
Module::CoreList, by Richard Clamp, is a small handy module that tells you what versions of core modules ship with any versions of Perl 5. It comes with a command-line frontend,corelist. -
Math::BigInt::FastCalcis an XS-enabled, and thus faster, version ofMath::BigInt::Calc. -
Compress::Zlibis an interface to the zlib compression library. It comes with a bundled version of zlib, so having a working zlib is not a prerequisite to install it. It's used byArchive::Tar(see below). -
IO::Zlibis anIO::-style interface toCompress::Zlib. -
Archive::Taris a module to manipulatetararchives. -
Digest::SHAis a module used to calculate many types of SHA digests, has been included for SHA support in the CPAN module. -
ExtUtils::CBuilderandExtUtils::ParseXShave been added. -
Hash::Util::FieldHash, by Anno Siegel, has been added. This module provides support for field hashes: hashes that maintain an association of a reference with a value, in a thread-safe garbage-collected way. Such hashes are useful to implement inside-out objects. -
Module::Build, by Ken Williams, has been added. It's an alternative toExtUtils::MakeMakerto build and install perl modules. -
Module::Load, by Jos Boumans, has been added. It provides a single interface to load Perl modules and .pl files. -
Module::Loaded, by Jos Boumans, has been added. It's used to mark modules as loaded or unloaded. -
Package::Constants, by Jos Boumans, has been added. It's a simple helper to list all constants declared in a given package. -
Win32API::File, by Tye McQueen, has been added (for Windows builds). This module provides low-level access to Win32 system API calls for files/dirs. -
Locale::Maketext::Simple, needed by CPANPLUS, is a simple wrapper aroundLocale::Maketext::Lexicon. Note thatLocale::Maketext::Lexiconisn't included in the perl core; the behaviour ofLocale::Maketext::Simplegracefully degrades when the later isn't present. -
Params::Checkimplements a generic input parsing/checking mechanism. It is used by CPANPLUS. -
Term::UIsimplifies the task to ask questions at a terminal prompt. -
Object::Accessorprovides an interface to create per-object accessors. -
Module::Pluggableis a simple framework to create modules that accept pluggable sub-modules. -
Module::Load::Conditionalprovides simple ways to query and possibly load installed modules. -
Time::Pieceprovides an object oriented interface to time functions, overriding the built-ins localtime() and gmtime(). -
IPC::Cmdhelps to find and run external commands, possibly interactively. -
File::Fetchprovide a simple generic file fetching mechanism. -
Log::MessageandLog::Message::Simpleare used by the log facility ofCPANPLUS. -
Archive::Extractis a generic archive extraction mechanism for .tar (plain, gziped or bzipped) or .zip files. -
CPANPLUSprovides an API and a command-line tool to access the CPAN mirrors. -
Pod::Escapesprovides utilities that are useful in decoding Pod E<...> sequences. -
Pod::Simpleis now the backend for several of the Pod-related modules included with Perl.
[↑] Изменения в стандартных модулях
Attribute::HandlersAttribute::Handlerscan now report the caller's file and line number. (David Feldman)All interpreted attributes are now passed as array references. (Damian Conway)
B::LintB::Lintis now based onModule::Pluggable, and so can be extended with plugins. (Joshua ben Jore)bIt's now possible to access the lexical pragma hints (
%^H) by using the method B::COP::hints_hash(). It returns aB::RHEobject, which in turn can be used to get a hash reference via the method B::RHE::HASH(). (Joshua ben Jore)ThreadAs the old 5005thread threading model has been removed, in favor of the ithreads scheme, the
Threadmodule is now a compatibility wrapper, to be used in old code only. It has been removed from the default list of dynamic extensions.
[↑] Изменения в утилитах
- perl -d
The Perl debugger can now save all debugger commands for sourcing later; notably, it can now emulate stepping backwards, by restarting and rerunning all bar the last command from a saved command history.
It can also display the parent inheritance tree of a given class, with the
icommand. - ptar
ptaris a pure perl implementation oftarthat comes withArchive::Tar. - ptardiff
ptardiffis a small utility used to generate a diff between the contents of a tar archive and a directory tree. Likeptar, it comes withArchive::Tar. - shasum
shasumis a command-line utility, used to print or to check SHA digests. It comes with the newDigest::SHAmodule. - corelist
The
corelistutility is now installed with perl (see "New modules" above). - h2ph and h2xs
h2phandh2xshave been made more robust with regard to "modern" C code.h2xsimplements a new option--use-xsloaderto force use ofXSLoadereven in backwards compatible modules.The handling of authors' names that had apostrophes has been fixed.
Any enums with negative values are now skipped.
- perlivp
perlivpno longer checks for *.ph files by default. Use the new-Aoption to run all tests. - find2perl
find2perlnow assumes-printas a default action. Previously, it needed to be specified explicitly.Several bugs have been fixed in
find2perl, regarding-execand-eval. Also the options-path,-ipathand-inamehave been added. - config_data
config_datais a new utility that comes withModule::Build. It provides a command-line interface to the configuration of Perl modules that use Module::Build's framework of configurability (that is,*::ConfigDatamodules that contain local configuration information for their parent modules.) - cpanp
cpanp, the CPANPLUS shell, has been added. (cpanp-run-perl, a helper for CPANPLUS operation, has been added too, but isn't intended for direct use). - cpan2dist
cpan2distis a new utility that comes with CPANPLUS. It's a tool to create distributions (or packages) from CPAN modules. - pod2html
The output of
pod2htmlhas been enhanced to be more customizable via CSS. Some formatting problems were also corrected. (Jari Aalto)
[↑] Новая документация
The perlpragma manpage documents how to write one's own lexical pragmas in pure Perl (something that is possible starting with 5.9.4).
The new perlglossary manpage is a glossary of terms used in the Perl documentation, technical and otherwise, kindly provided by O'Reilly Media, Inc.
The perlreguts manpage, courtesy of Yves Orton, describes internals of the Perl regular expression engine.
The perlreapi manpage describes the interface to the perl interpreter used to write pluggable regular expression engines (by Ævar Arnfjörð Bjarmason).
The perlunitut manpage is an tutorial for programming with Unicode and string encodings in Perl, courtesy of Juerd Waalboer.
A new manual page, perlunifaq (the Perl Unicode FAQ), has been added (Juerd Waalboer).
The perlcommunity manpage gives a description of the Perl community on the Internet and in real life. (Edgar "Trizor" Bering)
The CORE manual page documents the CORE::
namespace. (Tels)
The long-existing feature of /(?{...})/
regexps setting $_
and pos()
is now documented.
[↑] Повышение производительности
[↑] Сортировка по месту
Sorting arrays in place (@a = sort @a
) is now optimized to avoid
making a temporary copy of the array.
Likewise, reverse sort ...
is now optimized to sort in reverse,
avoiding the generation of a temporary intermediate list.
[↑] Доступ к лексическим массивам
Access to elements of lexical arrays via a numeric constant between 0 and 255 is now faster. (This used to be only the case for global arrays.)
[↑]XS-assisted SWASHGET
Some pure-perl code that perl was using to retrieve Unicode properties and transliteration mappings has been reimplemented in XS.
[↑] Подпрограммы-константы
The interpreter internals now support a far more memory efficient form of inlineable constants. Storing a reference to a constant value in a symbol table is equivalent to a full typeglob referencing a constant subroutine, but using about 400 bytes less memory. This proxy constant subroutine is automatically upgraded to a real typeglob with subroutine if necessary. The approach taken is analogous to the existing space optimisation for subroutine stub declarations, which are stored as plain scalars in place of the full typeglob.
Several of the core modules have been converted to use this feature for
their system dependent constants - as a result use POSIX;
now takes about
200K less memory.
[↑]PERL_DONT_CREATE_GVSV
The new compilation flag PERL_DONT_CREATE_GVSV
, introduced as an option
in perl 5.8.8, is turned on by default in perl 5.9.3. It prevents perl
from creating an empty scalar with every new typeglob. See perl588delta
for details.
[↑] Слабые ссылки обходятся дешевле
Weak reference creation is now O(1) rather than O(n), courtesy of Nicholas Clark. Weak reference deletion remains O(n), but if deletion only happens at program exit, it may be skipped completely.
[↑] Улучшение производительности sort()
Salvador Fandiño provided improvements to reduce the memory usage of sort
and to speed up some cases.
[↑] Отимизация памяти
Several internal data structures (typeglobs, GVs, CVs, formats) have been restructured to use less memory. (Nicholas Clark)
[↑] Оптимизация UTF-8 кэширования
The UTF-8 caching code is now more efficient, and used more often. (Nicholas Clark)
[↑] Функция stat() в Windows
On Windows, perl's stat() function normally opens the file to determine the link count and update attributes that may have been changed through hard links. Setting ${^WIN32_SLOPPY_STAT} to a true value speeds up stat() by not performing this operation. (Jan Dubois)
[↑] Оптимизация регулярных выражений
- Engine de-recursivised
The regular expression engine is no longer recursive, meaning that patterns that used to overflow the stack will either die with useful explanations, or run to completion, which, since they were able to blow the stack before, will likely take a very long time to happen. If you were experiencing the occasional stack overflow (or segfault) and upgrade to discover that now perl apparently hangs instead, look for a degenerate regex. (Dave Mitchell)
- Single char char-classes treated as literals
Classes of a single character are now treated the same as if the character had been used as a literal, meaning that code that uses char-classes as an escaping mechanism will see a speedup. (Yves Orton)
- Оптимизация чередования литеральных строк
Alternations, where possible, are optimised into more efficient matching structures. String literal alternations are merged into a trie and are matched simultaneously. This means that instead of O(N) time for matching N alternations at a given point, the new code performs in O(1) time. A new special variable, ${^RE_TRIE_MAXBUF}, has been added to fine-tune this optimization. (Yves Orton)
Note: Much code exists that works around perl's historic poor performance on alternations. Often the tricks used to do so will disable the new optimisations. Hopefully the utility modules used for this purpose will be educated about these new optimisations.
- Оптимизация стартовой точки(start-point) по алгоритму Ахо-Корасик
When a pattern starts with a trie-able alternation and there aren't better optimisations available, the regex engine will use Aho-Corasick matching to find the start point. (Yves Orton)
[↑] Инсталляция и настройка улучшений
[↑] Настройка улучшений
-DusesitecustomizeRun-time customization of @INC can be enabled by passing the
-Dusesitecustomizeflag to Configure. When enabled, this will make perl run $sitelibexp/sitecustomize.pl before anything else. This script can then be set up to add additional entries to @INC.- Инсталляции с возможностью перемещения (Relocatable installations)
There is now Configure support for creating a relocatable perl tree. If you Configure with
-Duserelocatableinc, then the paths in @INC (and everything else in %Config) can be optionally located via the path of the perl executable.That means that, if the string
".../"is found at the start of any path, it's substituted with the directory of $^X. So, the relocation can be configured on a per-directory basis, although the default with-Duserelocatableincis that everything is relocated. The initial install is done to the original configured prefix. - strlcat() and strlcpy()
The configuration process now detects whether strlcat() and strlcpy() are available. When they are not available, perl's own version is used (from Russ Allbery's public domain implementation). Various places in the perl interpreter now use them. (Steve Peters)
d_pseudoforkandd_printf_format_nullA new configuration variable, available as
$Config{d_pseudofork}in the Config module, has been added, to distinguish real fork() support from fake pseudofork used on Windows platforms.A new configuration variable,
d_printf_format_null, has been added, to see if printf-like formats are allowed to be NULL.- Помощь по настройке
Configure -hhas been extended with the most commonly used options.
[↑] Улучшения компиляции
- Паралельная сборка
Parallel makes should work properly now, although there may still be problems if
make testis instructed to run in parallel. - Поддержка компиляторов Borland
Building with Borland's compilers on Win32 should work more smoothly. In particular Steve Hay has worked to side step many warnings emitted by their compilers and at least one C compiler internal error.
- Статическая сборка в Windows
Perl extensions on Windows now can be statically built into the Perl DLL.
Also, it's now possible to build a
perl-static.exethat doesn't depend on the Perl DLL on Win32. See the Win32 makefiles for details. (Vadim Konovalov) - Файлы ppport.h
All ppport.h files in the XS modules bundled with perl are now autogenerated at build time. (Marcus Holland-Moritz)
- C++ совместимость
Efforts have been made to make perl and the core XS modules compilable with various C++ compilers (although the situation is not perfect with some of the compilers on some of the platforms tested.)
- Поддержка Microsoft 64-битного компилятора
Support for building perl with Microsoft's 64-bit compiler has been improved. (ActiveState)
- Visual C++
Perl can now be compiled with Microsoft Visual C++ 2005 (and 2008 Beta 2).
- компоновка Win32
All win32 builds (MS-Win, WinCE) have been merged and cleaned up.
[↑] Улучшения в установке
- Дополнительные файлы к модулям
README files and changelogs for CPAN modules bundled with perl are no longer installed.
[↑] Новые или улучшенные платформы
Perl has been reported to work on Symbian OS. See perlsymbian for more information.
Many improvements have been made towards making Perl work correctly on z/OS.
Perl has been reported to work on DragonFlyBSD and MidnightBSD.
Perl has also been reported to work on NexentaOS ( http://www.gnusolaris.org/ ).
The VMS port has been improved. See perlvms.
Support for Cray XT4 Catamount/Qk has been added. See hints/catamount.sh in the source code distribution for more information.
Vendor patches have been merged for RedHat and Gentoo.
DynaLoader::dl_unload_file() now works on Windows.
[↑] Некоторые исправленные баги
- Структуры в блоках regexp-eval
strictwasn't in effect in regexp-eval blocks (/(?{...})/). - Вызов CORE::require()
CORE::require() and CORE::do() were always parsed as require() and do() when they were overridden. This is now fixed.
- Индексы срезов
You can now use a non-arrowed form for chained subscripts after a list slice, like in:
({foo => "bar"})[0]{foo}
This used to be a syntax error; a
->was required. no warnings 'category'корректно работает с -wPreviously when running with warnings enabled globally via
-w, selective disabling of specific warning categories would actually turn off all warnings. This is now fixed; nowno warnings 'io';will only turn off warnings in theioclass. Previously it would erroneously turn off all warnings.- Улучшения потоков(threads)
Several memory leaks in ithreads were closed. Also, ithreads were made less memory-intensive.
threadsis now a dual-life module, also available on CPAN. It has been expanded in many ways. A kill() method is available for thread signalling. One can get thread status, or the list of running or joinable threads.A new
threads->exit()method is used to exit from the application (this is the default for the main thread) or from the current thread only (this is the default for all other threads). On the other hand, the exit() built-in now always causes the whole application to terminate. (Jerry D. Hedden) - chr() отрицательные значения
chr() on a negative value now gives
\x{FFFD}, the Unicode replacement character, unless when thebytespragma is in effect, where the low eight bits of the value are used. - PERL5SHELL и проверка меченных данных
On Windows, the PERL5SHELL environment variable is now checked for taintedness. (Rafael Garcia-Suarez)
- Использование *FILE{IO}
stat()and-xfiletests now treat *FILE{IO} filehandles like *FILE filehandles. (Steve Peters) - Перегрузка и пересоздание объектов(reblessing)
Overloading now works when references are reblessed into another class. Internally, this has been implemented by moving the flag for "overloading" from the reference to the referent, which logically is where it should always have been. (Nicholas Clark)
- Перегрузка и UTF-8
A few bugs related to UTF-8 handling with objects that have stringification overloaded have been fixed. (Nicholas Clark)
- Решена проблема с утечкой памяти в eval
Traditionally,
eval 'syntax error'has leaked badly. Many (but not all) of these leaks have now been eliminated or reduced. (Dave Mitchell) - Случайные устройства в Windows
In previous versions, perl would read the file /dev/urandom if it existed when seeding its random number generator. That file is unlikely to exist on Windows, and if it did would probably not contain appropriate data, so perl no longer tries to read it on Windows. (Alex Davies)
- PERLIO_DEBUG
The
PERLIO_DEBUGenvironment variable no longer has any effect for setuid scripts and for scripts run with -T.Moreover, with a thread-enabled perl, using
PERLIO_DEBUGcould lead to an internal buffer overflow. This has been fixed. - PerlIO::scalar и скаляры только для чтения
PerlIO::scalar will now prevent writing to read-only scalars. Moreover, seek() is now supported with PerlIO::scalar-based filehandles, the underlying string being zero-filled as needed. (Rafael, Jarkko Hietaniemi)
- study() и UTF-8
study() never worked for UTF-8 strings, but could lead to false results. It's now a no-op on UTF-8 data. (Yves Orton)
- Критические сигналы
The signals SIGILL, SIGBUS and SIGSEGV are now always delivered in an "unsafe" manner (contrary to other signals, that are deferred until the perl interpreter reaches a reasonably stable state; see "Deferred Signals (Safe Signals)" in perlipc). (Rafael)
- @INC-hook fix
When a module or a file is loaded through an @INC-hook, and when this hook has set a filename entry in %INC, __FILE__ is now set for this module accordingly to the contents of that %INC entry. (Rafael)
-Tswitch fixThe
-wand-Tswitches can now be used together without messing up which categories of warnings are activated. (Rafael)- Duping UTF-8 filehandles
Duping a filehandle which has the
:utf8PerlIO layer set will now properly carry that layer on the duped filehandle. (Rafael) - Локализация элементов хэша
Localizing a hash element whose key was given as a variable didn't work correctly if the variable was changed while the local() was in effect (as in
local $h{$x}; ++$x). (Bo Lindbergh)
[↑] Изменения в диагностике
- Использование неинициализированного значения
Perl will now try to tell you the name of the variable (if any) that was undefined.
- Запрещено использование my() в ложных условных выражение
A new deprecation warning, Deprecated use of my() in false conditional, has been added, to warn against the use of the dubious and deprecated construct
my $x if 0;
See perldiag. Use
statevariables instead. - !=~ должен быть !~
A new warning,
!=~ should be !~, is emitted to prevent this misspelling of the non-matching operator. - Символ перевода строки с левого края строки
The warning Newline in left-justified string has been removed.
- Слишком поздно для опции "-T"
The error Too late for "-T" option has been reformulated to be more descriptive.
- "%s" variable %s masks earlier declaration
This warning is now emitted in more consistent cases; in short, when one of the declarations involved is a
myvariable:my $x; my $x; # warns my $x; our $x; # warns our $x; my $x; # warns
On the other hand, the following:
our $x; our $x;
now gives a
"our" variable %s redeclaredwarning. - readdir()/closedir()/etc. attempted on invalid dirhandle
These new warnings are now emitted when a dirhandle is used but is either closed or not really a dirhandle.
- Opening dirhandle/filehandle %s also as a file/directory
Two deprecation warnings have been added: (Rafael)
Opening dirhandle %s also as a file Opening filehandle %s also as a directory - Use of -P is deprecated
Perl's command-line switch
-Pis now deprecated. - v-string in use/require is non-portable
Perl will warn you against potential backwards compatibility problems with the
use VERSIONsyntax. - perl -V
perl -Vhas several improvements, making it more useable from shell scripts to get the value of configuration variables. See perlrun for details.
[↑] Внутренние изменения
In general, the source code of perl has been refactored, tidied up, and optimized in many places. Also, memory management and allocation has been improved in several points.
When compiling the perl core with gcc, as many gcc warning flags are turned on as is possible on the platform. (This quest for cleanliness doesn't extend to XS code because we cannot guarantee the tidiness of code we didn't write.) Similar strictness flags have been added or tightened for various other C compilers.
[↑] Изменение порядка SVt_* констант
The relative ordering of constants that define the various types of sv
have changed; in particular, SVt_PVGV
has been moved before SVt_PVLV
,
SVt_PVAV
, SVt_PVHV
and SVt_PVCV
. This is unlikely to make any
difference unless you have code that explicitly makes assumptions about that
ordering. (The inheritance hierarchy of B::*
objects has been changed
to reflect this.)
[↑] Ликвидирован SVt_PVBM
Related to this, the internal type SVt_PVBM
has been been removed. This
dedicated type of sv
was used by the index
operator and parts of the
regexp engine to facilitate fast Boyer-Moore matches. Its use internally has
been replaced by sv
s of type SVt_PVGV
.
[↑] Новый тип SVt_BIND
A new type SVt_BIND
has been added, in readiness for the project to
implement Perl 6 on 5. There deliberately is no implementation yet, and
they cannot yet be created or destroyed.
[↑] Удалены CPP символы
The C preprocessor symbols PERL_PM_APIVERSION
and
PERL_XS_APIVERSION
, which were supposed to give the version number of
the oldest perl binary-compatible (resp. source-compatible) with the
present one, were not used, and sometimes had misleading values. They have
been removed.
[↑] BASEOP занимает меньше пространства
The BASEOP
structure now uses less space. The op_seq
field has been
removed and replaced by a single bit bit-field op_opt
. op_type
is now 9
bits long. (Consequently, the B::OP
class doesn't provide an seq
method anymore.)
[↑] Новый анализатор
perl's parser is now generated by bison (it used to be generated by byacc.) As a result, it seems to be a bit more robust.
Also, Dave Mitchell improved the lexer debugging output under -dt
.
[↑] Использование const
Andy Lester supplied many improvements to determine which function
parameters and local variables could actually be declared const
to the C
compiler. Steve Peters provided new *_set
macros and reworked the core to
use these rather than assigning to macros in LVALUE context.
[↑]Mathoms
A new file, mathoms.c, has been added. It contains functions that are
no longer used in the perl core, but that remain available for binary or
source compatibility reasons. However, those functions will not be
compiled in if you add -DNO_MATHOMS
in the compiler flags.
[↑] AvFLAGS
удален
The AvFLAGS
macro has been removed.
[↑] Изменения в функциях av_*
The av_*()
functions, used to manipulate arrays, no longer accept null
AV*
parameters.
[↑] $^H и %^H
The implementation of the special variables $^H and %^H has changed, to allow implementing lexical pragmas in pure Perl.
[↑] Изменения в модулях B::*
The inheritance hierarchy of B::
modules has changed; B::NV
now
inherits from B::SV
(it used to inherit from B::IV
).
[↑] Конструкторы анонимных хэшей и массивов
The anonymous hash and array constructors now take 1 op in the optree instead of 3, now that pp_anonhash and pp_anonlist return a reference to an hash/array when the op is flagged with OPf_SPECIAL. (Nicholas Clark)
[↑] Известные проблемы
There's still a remaining problem in the implementation of the lexical
$_
: it doesn't work inside /(?{...})/
blocks. (See the TODO test in
t/op/mydef.t.)
Stacked filetest operators won't work when the filetest
pragma is in
effect, because they rely on the stat() buffer _
being populated, and
filetest bypasses stat().
[↑] Проблемы UTF-8
The handling of Unicode still is unclean in several places, where it's dependent on whether a string is internally flagged as UTF-8. This will be made more consistent in perl 5.12, but that won't be possible without a certain amount of backwards incompatibility.
[↑] Проблемы, специфичные для платформ
When compiled with g++ and thread support on Linux, it's reported that the
$!
stops working correctly. This is related to the fact that the glibc
provides two strerror_r(3) implementation, and perl selects the wrong
one.
[↑] Сообщения об ошибках
If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup and the perl bug database at http://rt.perl.org/rt3/ . There may also be information at http://www.perl.org/ , the Perl Home Page.
If you believe you have an unreported bug, please run the perlbug
program included with your release. Be sure to trim your bug down
to a tiny but sufficient test case. Your bug report, along with the
output of perl -V
, will be sent off to perlbug@perl.org to be
analysed by the Perl porting team.
[↑] СМ. ТАКЖЕ
The Changes file and the perl590delta to perl595delta man pages for exhaustive details on what changed.
The INSTALL file for how to build Perl.
The README file for general stuff.
The Artistic and Copying files for copyright information.