- 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.
- Progressive Web Apps with React
- Data Analysis with IBM SPSS Statistics
- Troubleshooting PostgreSQL
- EPLAN實戰設計
- 零基礎趣學C語言
- 從零開始學Linux編程
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- MySQL程序員面試筆試寶典
- Getting Started with React VR
- Web前端開發技術:HTML、CSS、JavaScript
- Python機器學習開發實戰
- 例說FPGA:可直接用于工程項目的第一手經驗
- Go Systems Programming
- 透視C#核心技術:系統架構及移動端開發
- Illustrator CS6中文版應用教程(第二版)