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

  • Perl 6 Deep Dive
  • Andrew Shitov
  • 365字
  • 2021-07-03 00:05:41

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.

主站蜘蛛池模板: 万山特区| 达拉特旗| 奎屯市| 南皮县| 张家港市| 武宣县| 田林县| 老河口市| 四会市| 夏邑县| 陆丰市| 德州市| 准格尔旗| 宜兰县| 黎平县| 自治县| 开平市| 盘锦市| 商都县| 宽城| 大关县| 濮阳市| 闽清县| 定州市| 莫力| 泰顺县| 静宁县| 湖南省| 定南县| 米林县| 郸城县| 图木舒克市| 山丹县| 太谷县| 奉新县| 乐至县| 阿巴嘎旗| 濮阳市| 桂阳县| 绥德县| 普洱|