官术网_书友最值得收藏!

Compatibility with Perl 5

Existing Perl 6 compilers cannot execute Perl 5 programs without modifications in the source code. Perl 5 and Perl 6 are sometimes called sister languages. Both share the same spirit of Perl, and, in many cases, it is possible to convert the program from Perl 5 to Perl 6.

One of the biggest advantages of Perl 5 is the CPAN (Comprehensive Perl Archive Network). It contains a myriad of modules for the immense number of areas. Most probably, your task is already solved by some author of CPAN. To use this useful heritage in your programs in Perl 6, you may want to use the Inline::Perl5 module, which allows using an existing Perl 5 module without modifying the source code.

For example, let's take one of the most popular modules in Perl 5, Text::CSV, and embed it in our program in Perl 6.

use Inline::Perl5;
use Text::CSV:from<Perl5>;

my $csv = Text::CSV.new;

$csv.parse('First name,Last name');
say $csv.fields.join("\t");

$csv.parse('Astrid,Lindgren');
say $csv.fields.join("\t");

With Inline::Perl5 enabled, the :from<Perl5> suffix loads the Text::CSV module from Perl 5 module directory. That module must be installed as a regular Perl 5 module from CPAN.

The rest of the program uses the $csv object, which is an instance of Text::CSV. Notice that you have to follow Perl 6 syntax, so, for instance, instead of creating the object with Text::CSV->new use Text::CSV.new. The same applies to calling the parse method: in Perl 5 it would be $csv->parse(), while in Perl 6 you use dot: $csv.parse(). Working with objects in Perl 6 is described in Chapter 8, Object-Oriented Programming.

Luckily, there is already a module Text::CSV for Perl 6. You can find it on the http://modules.perl6.org page. Using Inline::Perl5 can be very useful for those modules on CPAN, which do not yet have equivalents or replacement, written in Perl 6. For example, the following example taken from the module documentation shows how to connect to the database (of course, you need PostgreSQL to be installed to test the example):

use Inline::Perl5;
use DBI:from<Perl5>;

my $dbh = DBI.connect('dbi:Pg:database=test');
my $products = $dbh.selectall_arrayref(
'select * from products', {Slice => {}}
);

The Inline::Perl5 module is available at https://github.com/niner/Inline-Perl5.

主站蜘蛛池模板: 哈密市| 普陀区| 绥江县| 宁晋县| 石楼县| 界首市| 北碚区| 凤阳县| 息烽县| 深州市| 绥芬河市| 剑川县| 靖州| 龙岩市| 龙川县| 彭山县| 喜德县| 丰都县| 漳平市| 绥芬河市| 金坛市| 巴林左旗| 锡林郭勒盟| 古蔺县| 石棉县| 韶关市| 肥东县| 义乌市| 郸城县| 西平县| 周宁县| 双辽市| 阿尔山市| 隆昌县| 达拉特旗| 墨竹工卡县| 两当县| 观塘区| 独山县| 洪湖市| 定南县|