- 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.
- 大學計算機基礎(第2版)(微課版)
- 領域驅動設計:軟件核心復雜性應對之道(修訂版)
- Hadoop 2.X HDFS源碼剖析
- Python函數式編程(第2版)
- 貫通Tomcat開發
- Responsive Web Design with jQuery
- MongoDB Cookbook
- Building Apple Watch Projects
- Ubuntu Server Cookbook
- 從零開始學UI設計·基礎篇
- PHP典型模塊與項目實戰大全
- Python AI游戲編程入門:基于Pygame和PyTorch
- Hands-On GUI Application Development in Go
- Learning HTML5 by Creating Fun Games
- Arduino Robotic Projects