Mark Overmeer > Log-Report-0.996 > Log::Report::Message

Download:
Log-Report-0.996.tar.gz

Dependencies

Annotate this POD

CPAN RT

Open  4
View/Report Bugs
Module Version: 0.996   Source   Latest Release: Log-Report-1.05

NAME ^

Log::Report::Message - a piece of text to be translated

SYNOPSIS ^

 # Created by Log::Report's __ functions
 # Full feature description in the DETAILS section

 # no interpolation
 __"Hello, World";

 # with interpolation
 __x"age {years}", years => 12;

 # interpolation for one or many
 my $nr_files = @files;
 __nx"one file", "{_count} files", $nr_files;
 __nx"one file", "{_count} files", \@files;

 # interpolation of arrays
 __x"price-list: {prices%.2f}", prices => \@prices, _join => ', ';

 # white-spacing on msgid preserved
 print __"\tCongratulations,\n";
 print "\t", __("Congratulations,"), "\n";  # same

DESCRIPTION ^

Any use of a translation function exported by Log::Report, like __() (the function is named underscore-underscore) or __x() (underscore-underscore-x) will result in this object. It will capture some environmental information, and delay the translation until it is needed.

Creating an object first and translating it later, is slower than translating it immediately. However, on the location where the message is produced, we do not yet know in what language to translate it to: that depends on the front-end, the log dispatcher.

METHODS ^

Constructors

$obj->clone(OPTIONS, VARIABLES)

Returns a new object which copies info from original, and updates it with the specified OPTIONS and VARIABLES. The advantage is that the cached translations are shared between the objects.

example: use of clone()

 my $s = __x "found {nr} files", nr => 5;
 my $t = $s->clone(nr => 3);
 my $t = $s->(nr => 3);      # equivalent
 print $s;     # found 5 files
 print $t;     # found 3 files
Log::Report::Message->fromTemplateToolkit(DOMAIN, MSGID, PARAMS)

See Log::Report::Extract::Template on the details how to integrate Log::Report translations with Template::Toolkit (version 1 and 2)

Log::Report::Message->new(OPTIONS)

End-users: do not use this method directly, but use Log::Report::__() and friends. The OPTIONS is a mixed list of object initiation parameters (all with a leading underscore) and variables to be filled in into the translated _msgid string.

 -Option   --Default
  _append    undef
  _category  undef
  _class     []
  _classes   []
  _count     undef
  _domain    from use
  _expand    false
  _join      $" $LIST_SEPARATOR
  _msgid     undef
  _plural    undef
  _prepend   undef
  _to        <undef>
_append => STRING|MESSAGE

Text as STRING or MESSAGE object to be displayed after the display of this message.

_category => INTEGER

The category when the real gettext library is used, for instance LC_MESSAGES.

_class => STRING|ARRAY

When messages are used for exception based programming, you add _class parameters to the argument list. Later, with for instance Log::Report::Dispatcher::Try::wasFatal(class), you can check the category of the message.

One message can be part of multiple classes. The STRING is used as comma- and/or blank separated list of class tokens (barewords), the ARRAY lists all tokens separately. See classes().

_classes => STRING|ARRAY

Alternative for _class, which cannot be used at the same time.

_count => INTEGER|ARRAY|HASH

When defined, the _plural need to be defined as well. When an ARRAY is provided, the length of the ARRAY is taken. When a HASH is given, the number of keys in the HASH is used.

_domain => STRING

The text-domain (translation table) to which this _msgid belongs.

_expand => BOOLEAN

Indicates whether variables are to be filled-in.

_join => STRING

Which STRING to be used then an ARRAY is being filled-in.

_msgid => MSGID

The message label, which refers to some translation information. Usually a string which is close the English version of the message. This will also be used if there is no translation possible/known.

Leading white-space \s will be added to _prepend. Trailing white-space will be added before _append.

_plural => MSGID

Can be used together with _count. This plural form of the _msgid text is used to simplify the work of translators, and as fallback when no translation is possible: therefore, this can best resemble an English message.

White-space at the beginning and end of the string are stripped off. The white-space provided by the _msgid will be used.

_prepend => STRING|MESSAGE

Text as STRING or MESSAGE object to be displayed before the display of this message.

_to => NAME

Specify the NAME of a dispatcher as destination explicitly. Short for report {to => NAME}, ... See to()

Accessors

$obj->append()

Returns the string or Log::Report::Message object which is appended after this one. Usually undef.

$obj->classes()

Returns the LIST of classes which are defined for this message; message group indicators, as often found in exception-based programming.

$obj->count()

Returns the count, which is used to select the translation alternatives.

$obj->domain()

Returns the domain of the first translatable string in the structure.

$obj->msgid()

Returns the msgid which will later be translated.

$obj->prepend()

Returns the string which is prepended to this one. Usually undef.

$obj->to([NAME])

Returns the NAME of a dispatcher if explicitly specified with the '_to' key. Can also be used to set it. Usually, this will return undef, because usually all dispatchers get all messages.

$obj->valueOf(PARAMETER)

Lookup the named PARAMETER for the message. All pre-defined names have their own method which should be used with preference.

example:

When the message was produced with

  my @files = qw/one two three/;
  my $msg = __xn "found one file: {file}"
               , "found {nrfiles} files: {files}"
               , scalar @files
               , file    => $files[0]
               , files   => \@files
               , nrfiles => @files+0
               , _class  => 'IO, files'
               , _join   => ', ';

then the values can be takes from the produced message as

  my $files = $msg->valueOf('files');  # returns ARRAY reference
  print @$files;              # 3
  my $count = $msg->count;    # 3
  my @class = $msg->classes;  # 'IO', 'files'
  if($msg->inClass('files'))  # true

Simplified, the above example can also be written as:

  local $" = ', ';
  my $msg  = __xn "found one file: {files}"
                , "found {_count} files: {files}"
                , @files      # has scalar context
                , files   => \@files
                , _class  => 'IO, files';

Processing

$obj->concat(STRING|OBJECT, [PREPEND])

This method implements the overloading of concatenation, which is needed to delay translations even longer. When PREPEND is true, the STRING or OBJECT (other Log::Report::Message) needs to prepended, otherwise it is appended.

example: of concatenation

 print __"Hello" . ' ' . __"World!";
 print __("Hello")->concat(' ')->concat(__"World!")->concat("\n");
$obj->inClass(CLASS|REGEX)

Returns true if the message is in the specified CLASS (string) or matches the REGEX. The trueth value is the (first matching) class.

$obj->toString([LOCALE])

Translate a message. If not specified, the default locale is used.

$obj->untranslated()

Return the concatenation of the prepend, msgid, and append strings. Variable expansions within the msgid is not performed.

DETAILS ^

OPTIONS and VARIABLES

The Log::Report functions which define translation request can all have OPTIONS. Some can have VARIABLES to be interpolated in the string as well. To distinguish between the OPTIONS and VARIABLES (both a list of key-value pairs), the keys of the OPTIONS start with an underscore _. As result of this, please avoid the use of keys which start with an underscore in variable names. On the other hand, you are allowed to interpolate OPTION values in your strings.

Interpolating

With the __x() or __nx(), interpolation will take place on the translated MSGID string. The translation can contain the VARIABLE and OPTION names between curly brackets. Text between curly brackets which is not a known parameter will be left untouched.

 fault __x"cannot open open {filename}", filename => $fn;

 print __xn"directory {dir} contains one file"
          ,"directory {dir} contains {nr_files} files"
          , scalar(@files)            # (1) (2)
          , nr_files => scalar @files # (3)
          , dir      => $dir;

(1) this required third parameter is used to switch between the different plural forms. English has only two forms, but some languages have many more.

(2) the "scalar" keyword is not needed, because the third parameter is in SCALAR context. You may also pass \@files there, because ARRAYs will be converted into their length. A HASH will be converted into the number of keys in the HASH.

(3) the scalar keyword is required here, because it is LIST context: otherwise all filenames will be filled-in as parameters to __xn(). See below for the available _count valure, to see how the nr_files parameter can disappear.

Interpolation of VARIABLES

There is no way of checking beforehand whether you have provided all required values, to be interpolated in the translated string.

For interpolating, the following rules apply:

 local $" = ', ';
 error __x"matching files: {files}", files => \@files;

 error __x"matching files: {files}", files => \@files, _join => ', ';

Interpolating formatted

Next to the name, you can specify a format code. With gettext(), you often see this:

 printf gettext("approx pi: %.6f\n"), PI;

Locale::TextDomain has two ways.

 printf __"approx pi: %.6f\n", PI;
 print __x"approx pi: {approx}\n", approx => sprintf("%.6f", PI);

The first does not respect the wish to be able to reorder the arguments during translation. The second version is quite long. With Log::Report, above syntaxes do work, but you can also do

 print __x"approx pi: {pi%.6f}\n", pi => PI;

So: the interpolation syntax is { name [format] } . Other examples:

 print __x "{perms} {links%2d} {user%-8s} {size%10d} {fn}\n"
         , perms => '-rw-r--r--', links => 1, user => 'me'
         , size => '12345', fn => $filename;

An additional advantage is the fact that not all languages produce comparable length strings. Now, the translators can take care that the layout of tables is optimal.

Interpolation of OPTIONS

You are permitted the interpolate OPTION values in your string. This may simplify your coding. The useful names are:

_msgid

The MSGID as provided with Log::Report::__() and Log::Report::__x()

_plural, _count

The PLURAL MSGIDs, respectively the COUNT as used with Log::Report::__n() and Log::Report::__nx()

_textdomain

The label of the textdomain in which the translation takes place.

_class or _classes

Are to be used to group reports, and can be queried with inClass(), Log::Report::Exception::inClass(), or Log::Report::Dispatcher::Try::wasFatal().

Handling white-spaces

In above examples, the msgid and plural form have a trailing new-line. In general, it is much easier to write

   print __x"Hello, World!\n";

than

   print __x("Hello, World!") . "\n";

For the translation tables, however, that trailing new-line is "over information"; it is an layout issue, not a translation issue.

Therefore, the first form will automatically be translated into the second. All leading and trailing white-space (blanks, new-lines, tabs, ...) are removed from the msgid befor the look-up, and then added to the translated string.

Leading and trailing white-space on the plural form will also be removed. However, after translation the spacing of the msgid will be used.

Avoiding repetative translations

This way of translating is somewhat expensive, because an object to handle the __x() is created each time.

 for my $i (1..100_000)
 {   print __x "Hello World {i}\n", i => $i;
 }

The suggestion that Locale::TextDomain makes to improve performance, is to get the translation outside the loop, which only works without interpolation:

 use Locale::TextDomain;
 my $i = 42;
 my $s = __x("Hello World {i}\n", i => $i);
 foreach $i (1..100_000)
 {   print $s;
 }

Oops, not what you mean. With Log::Report, you can do it.

 use Log::Report;
 my $i;
 my $s = __x("Hello World {i}\n", i => \$i);
 foreach $i (1..100_000)
 {   print $s;
 }

Mind you not to write: for my $i in above case!!!!

You can also write an incomplete translation:

 use Log::Report;
 my $s = __x "Hello World {i}\n";
 foreach my $i (1..100_000)
 {   print $s->(i => $i);
 }

In either case, the translation will be looked-up only once.

OVERLOADING ^

overload: as function()

When the object is used to call as function, a new object is created with the data from the original one but updated with the new parameters. Implemented in clone().

overload: concatenation()

An (accidental) use of concatenation (a dot where a comma should be used) would immediately stringify the object. This is avoided by overloading that operation.

overload: stringification()

When the object is used in string context, it will get translated. Implemented as toString().

SEE ALSO ^

This module is part of Log-Report distribution version 0.996, built on September 04, 2013. Website: http://perl.overmeer.net/log-report/

LICENSE ^

Copyrights 2007-2013 by [Mark Overmeer]. For other contributors see ChangeLog.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html

syntax highlighting: