- 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.
- AngularJS Testing Cookbook
- PHP 從入門到項目實踐(超值版)
- Oracle Database In-Memory(架構與實踐)
- Python自然語言處理(微課版)
- Mastering Swift 2
- ASP.NET程序設計教程
- Learning R for Geospatial Analysis
- Instant Lucene.NET
- Python機器學習之金融風險管理
- Learning VMware vSphere
- NGUI for Unity
- SQL Server 2014 Development Essentials
- Neo4j權威指南 (圖數(shù)據(jù)庫技術叢書)
- Hands-On Game Development Patterns with Unity 2019
- Java EE企業(yè)級應用開發(fā)教程:Spring+Spring MVC+MyBatis(第2版)