且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以确保在 5.10+ 上编写的 Perl 代码可以在 5.8 上运行吗?

更新时间:2023-01-19 13:18:15

当我想确保程序能在特定版本的 perl 下运行时,我会在该版本的 perl 下测试它.我的 release 应用程序在实际上传之前在多个 perls 下进行测试.

When I want to ensure that a program will run under particular versions of perl, I test it under that version of perl. A feature of my release application tests under multiple perls before it actually uploads.

这要求您拥有合适的测试套件并编写足够的测试.同时维护多个单独的 perl 安装也很容易,正如我在 Effective Perl Programming 中展示的那样.

This requires that you have a proper test suite and write enough tests. It's easy to maintain several separate perl installations at the same time, too, as I show in Effective Perl Programming.

Test::MinimumVersion 听起来似乎可行,但它有几个限制.它只查看你给它的文件(所以它不会检查你加载的任何东西),我认为它实际上并不在正则表达式模式中.这些报告中的每一个都报告最低版本为 5.004,这对它们中的任何一个都不正确:

Test::MinimumVersion almost sounds like it might work, but it has several limitations. It only looks at the file you give it (so it will not check anything you load), and I don't think it actually looks inside regex patterns. Each of these report that the minimum version is 5.004, which is not true for any of them:

#!perl

use Perl::MinimumVersion;

my $p_flag = <<'SOURCE';
'123' =~ m/[123]/p; # 5.10 feature
SOURCE

my $named_capture = <<'SOURCE';
'123' =~ m/(?<num>[123])/; # 5.10 feature
SOURCE

my $r_line_ending = <<'SOURCE';
'123' =~ m/[123]\R/p; # 5.12 feature
SOURCE

my $say = <<'SOURCE';
say 'Hello';
SOURCE

my $smart_match = <<'SOURCE';
$boolean = '123' ~~ @array;
SOURCE

my $given = <<'SOURCE';
given( $foo ) {
    when( /123/ ) { say 'Hello' }
    };

SOURCE

foreach my $source ( $p_flag, $named_capture, $r_line_ending, $say, $smart_match, $given ) {
    print "----Source---\n$source\n-----";
    my $version = Perl::MinimumVersion->new( \$source  )->minimum_version;
    print "Min version is $version\n";
    }

Perl::MinimumVersion 工作的部分原因是因为它寻找提示源码已经给了,比如use 5.010use feature等等.但是,这并不是启用功能的唯一方法.而且,正如您将注意到的,它会遗漏诸如 /p 标志之类的东西,至少在有人为此添加检查之前是这样.但是,您总是会使用 PPI 解决方案来解决此类问题.

Part of the reason Perl::MinimumVersion works is because it looks for hints that the source gives it already, such as use 5.010, and use feature so on. However, that's not the only way to enable features. And, as you'll note, it misses things like the /p flag, at least until someone adds a check for that. However, you'll always be chasing things like that with a PPI solution.

只需编译它、运行测试并找出结果就更容易了.

It's easier just to compile it, run the tests, and find out.