perl - 使用 gettext 和 Locale::TextDomain 在 Perl 中进行本地化,如果 Locale::TextDomain 不可用,则进行回退

标签 perl localization internationalization gettext

2009 年 4 月 26 日发布的“On the state of i18n in Perl ”博客文章建议使用 Locale::TextDomain来自 libintl-perl 发行版的 Perl 中的 l10n/i18n 模块。此外,无论如何我都必须使用 gettext,并且 Locale::Messages/Locale::TextDomain 中的 gettext 支持比 Locale::Maketext 中的 gettext 模拟更自然。 .

GNU gettext 手册中“15.5.18 Perl”一章中的“15 Other Programming Languages”小节说:

Portability

The libintl-perl package is platform independent but is not part of the Perl core. The programmer is responsible for providing a dummy implementation of the required functions if the package is not installed on the target system.

但是 examples/hello-perl 中的两个例子都没有gettext 源中(一个使用较低级别的 Locale::Messages,一个使用较高级别的 Locale::TextDomain)包括检测包是否安装在目标系统上,并提供虚拟实现如果不是。

使事情变得复杂(关于检测软件包是否安装)的是 Locale::TextDomain 手册页的以下片段:

SYNOPSIS

use Locale::TextDomain ('my-package', @locale_dirs);

use Locale::TextDomain qw (my-package);

USAGE

It is crucial to remember that you use Locale::TextDomain(3) as specified in the section "SYNOPSIS", that means you have to use it, not require it. The module behaves quite differently compared to other modules.

您能否告诉我如何检测目标系统上是否存在 libintl-perl,以及如何在未安装时提供虚拟的失败实现?或者给出执行此操作的程序/模块的示例?

最佳答案

gettext 手册错误地建议您不可以 demand a CPAN prerequisite 。在 Perl 世界中每个人都这样做,并且由于 CPAN 基础设施和工具链,它工作得很好。在最坏的情况下,您可以捆绑所需的依赖项。

您问题的直接答案是:

use Try::Tiny;
try {
    require Locale::TextDomain;
    Locale::TextDomain->import('my-package', @locale_dirs);
} catch {
    warn 'Soft dependency could not be loaded, using fallback.';
    require inc::Local::Dummy::Locale::TextDomain;
};

说明:use is just require at compile time followed by import ,并且可以将其拆分以强制其在运行时执行。

关于perl - 使用 gettext 和 Locale::TextDomain 在 Perl 中进行本地化,如果 Locale::TextDomain 不可用,则进行回退,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2965626/

相关文章:

ruby-on-rails - 如何翻译 Rails 3.2 中的 ActiveRecord 属性名称?

javascript - 为模块化应用程序组织 Javascript i18n 文件

perl - 在 Perl 中转换为 unicode 字符?

perl - File::Slurp 成多 GB 标量 - 如何有效拆分?

android - 本地化多平台项目 - 合并字符串文件

android - Kotlin - 如何更改语言环境

java - Wicket:如何以编程方式呈现页面并将结果作为字符串获取?

Perl 或做多件事

regex - 替换复杂模式中的字符

Qt 文化感知的 QString 容器类