Log::Report::Message
a piece of text to be translated
- Provided by: liblog-report-perl (Version: 1.44-1)
- Report a bug
a piece of text to be translated
Log::Report::Message is extended by Dancer2::Plugin::LogReport::Message
# Objects 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
Any use of a constructor function exported by Log::Report, like "__()" (the function is named underscore-underscore) or "__x()" (underscore-underscore-x) will result in this Message object. It will capture some environmental information as well.
The optional translation is delayed until it is really needed. Creating an object first and translating it later, might be slower than translating it immediately. However (by design decissions of Log::Report) on the location where the message is produced, we do not yet know in what language to translate it to: that depends on the actual log dispatcher configurations in the main program.
» 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
-Option --Default
_append undef
_category undef
_class undef
_classes undef
_context undef
_count undef
_domain <from "use Log::Report">
_expand false
_join $" $LIST_SEPARATOR
_lang <from locale>
_msgctxt undef
_msgid undef
_plural undef
_prepend undef
_tag []
_tags []
_to undef
With this parameter, your can "borrow" translations from other textdomains. Be very careful with this (although there are good use-cases) The xgettext msgid extractor may add the used msgid to this namespace as well. To avoid that, add a harmless '+':
print __x(+"errors", _domain => 'global');
The extractor will not take the msgid when it is an expression. The '+' has no effect on the string at runtime.
Leading white-space "\s" will be added to "_prepend". Trailing white-space will be added before "_append".
White-space at the beginning and end of the string are stripped off. The white-space provided by the "_msgid" will be used.
The $tags is interpreted as comma- and/or blank separated list of class tokens (barewords), the ARRAY lists all tags separately. See tags().
» 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, # or scalar(@files)
_tags => [ '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 @tags = $msg->tags; # 'IO', 'files'
if($msg->taggedWith('files')) # true
Simplified, the above example can also be written as:
local $" = ', '; # Perl default
my $msg = __xn
"found one file: {files}",
"found {_count} files: {files}",
@files, # has scalar context
files => \@files,
_tags => 'IO, files';
» example: of concatenation
print __"Hello" . ' ' . __"World!\n";
print __("Hello")->concat(' ')->concat(__"World!")->concat("\n");
[1.20] When used in combination with a templating system, you may want to use "<content_for =" 'HTML'>> in Log::Report::Domain::configure(formatter).
» example:
print $msg->toHTML('NL');
The message cast by the Log::Report exception framework can be plain strings. This is sufficient for some cases, for instance: which would you bother much about the content of "trace" messages? Message which are destined for end-users or log-files however, need more care; require a higher quality. In this case, you can better use cast message objects which support interpolation.
An exception message as a string is pretty inflexible. It cannot be translated anymore, and it cannot contain related information like an error code. An exception message as an object (as this module implements) is able to contain additional information.
The easiest way to create Log::Report::Message objects, is via the "__x()" (and friends) functions which are exported by Log::Report. These are nearly equivalent:
my $msg = Log::Report::Message->new(_msgid => "Hello, World!"); my $msg = __"Hello, World!";
The name "msgid" is used, because this object can do translations. In the GNU gettext library for translations, the term "msgid" is used to describe the string which has to be looked-up in translation tables. When there are no tables, or the "msgid" is not found, then the output string is equivalent to the "msgid".
So, without any translation configuration, this happens:
my $msg = __"Hello, World!"; print "$msg\n"; # Hello, World!⏎
The "__()" function can be used with a static string, although you could do this:
my $msg = __"Hello $name!"; #XXX Don't do this! print "$msg\n"; # Hello Mark!⏎
With the "__x()" or "__nx()", interpolation will take place on the (optionally) translated "msgid" string. This is how to write above:
my $msg = __x"Hello {name}!", name => $name;
So: the "msgid" is usually a format string. Only when you use formats correctly, you will be able to introduce translation later.
Simple perl scripts will use print() with variables in the string. However, when the content of the variable gets more unpredictable or needs some pre-processing, then it gets tricky. When you do want to introduce translations (in the far future of your successful project) it gets impossible. Let me give you some examples:
print "product: $name\n"; # simple perl
# Will not work because "$name" is interpolated too early
print translate("product: $name"), "\n";
# This is the gettext solution, with formats
printf translate("product: %s\n"), $name;
# With named in stead of positional parameters
print translate("product: {p}\n", p => $name);
# With Log::Report, the translate() is hidden in __x()
print __x"product: {p}\n", p => $name;
Besides making translation possible, interpolation via format strings is much cleaner than in the simpelest perl way. For instance, these cases:
# Safety measures while interpolation
my $name = undef;
print "product: $name\n"; # uninitialized warning
print __x"product: {p}\n", p => $name; # --> product: undef
# Interpolation of more complex data
my @names = qw/a b c/;
print "products: ", join(', ', @names), "\n";
print __x"products: {p}\n", p => \@names;
# Padded values hard to do without format strings
print "padded counter: ", ' ' x (6-length $c), "$c\n";
printf "padded counter: %6d\n", $counter;
print __x"padded counter: {c%6d}\n", c => $counter;
So: using formats has many advantages. Advice: use simple perl only in "trace" and "assert" messages, maybe also with panics. For serious output of your program, use formatted output.
The Log::Report::__xn() message constructor is used when you need a different translation based on the count of one of the inserted fields.
fault __x"cannot read {file}", file => $fn;
# --> FAULT: cannot read /etc/shadow: Permission denied\n
print __xn"directory {dir} contains one file",
"directory {dir} contains {nr_files} files",
scalar(@files), # (1) (2) (3)
nr_files => scalar @files, # (4)
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) you could also simply pass a reference to the ARRAY: it will take the length as counter. With a HASH, it will count the number of keys.
(4) 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" value, to see how the "nr_files" parameter can disappear.
print __xn"directory {dir} contains one file",
"directory {dir} contains {_count} files",
\@files, dir => $dir;
Some languages need more than two translations based on the counter. This is solved by the translation table definition. The two msgids give here are simply the fallback, when there is not translation table active.
Interpolation with String::Print
There is no way of checking beforehand whether you have provided all required values, to be interpolated in the translated string.
This Log::Report::Message uses String::Print to handle formatted strings. On object of that module is hidden in the logic of "__x()" and friends.
String::Print is a very capable format string processor, and you should really read its manual page to see how it can help you. It would be possible to support an other formatter (pretty simple even), but this is not (yet) supported.
» Example: using format features
# This tries to display the $param as useful and safe as possible,
# where you have totally no idea what its contents is.
error __x"illegal parameter {p UNKNOWN}.", p => $param;
# ---> "illegal parameter 'accidentally passed text'."
# ---> "illegal parameter Unexpected::Object::Type."
# fault() adds ": $!", with $! translated when configured.
open my($fh), "<:encoding(utf-8)", $filename
or fault __x"cannot read {file}", file => $filename;
# Auto-abbreviation
trace __x"first lines: '{text EL}'\n", text => $t;
# ---> "first lines: 'This text is long, we sho⋯'.\n"
trace __x"first lines: {text CHOP}\n", text => $t;
# ---> "This text is long, we [+3712 chars]\n"
info __x"file {file} size {size BYTES}\n", file => $fn, size => -s $fn;
# --> "/etc/passwd size 23kB\n"
# HASH or object values
print __x"Name: {user.first} {user.surname}\n", user => $login;
There are more nice standard interpolation modifiers, and you can add your own. Besides, you can add serializers which determine how objects are inlined.
Besides the parameters which you specify yourself, Log::Report will add a few which can also be interpolated. The all start with an underscore ("_"). These are collected when this Message object is instantiated, see the %options of new(). These parameters have a purpose, but you are also permitted tp interpolate them in your message. This may simplify your coding.
The useful names are:
» Example: using the _count
With Locale::TextDomain, you have to do
use Locale::TextDomain;
print __nx(
"One file has been deleted.\n",
"{num} files have been deleted.\n",
$num_files,
num => $num_files,
);
With "Log::Report", you can do
use Log::Report;
print __nx(
"One file has been deleted.\n",
"{_count} files have been deleted.\n",
$num_files,
);
Of course, you need to be aware that the name used to reference the counter is fixed to "_count". The first example works as well, but is more verbose.
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 "ignorable 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 before 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 "Log::Report::__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 because the first value of $i is captured in the initial message object. With Log::Report, you can do it (except when you use contexts)
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.
This module is part of Log-Report version 1.44, built on December 22, 2025. Website: http://perl.overmeer.net/CPAN/
For contributors see file ChangeLog.
This software is copyright (c) 2007-2025 by Mark Overmeer.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.