1Log::Report::Message(3)User Contributed Perl DocumentatioLnog::Report::Message(3)
2
3
4

NAME

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

INHERITANCE

9        Log::Report::Message is extended by
10          Dancer2::Plugin::LogReport::Message
11

SYNOPSIS

13        # Objects created by Log::Report's __ functions
14        # Full feature description in the DETAILS section
15
16        # no interpolation
17        __"Hello, World";
18
19        # with interpolation
20        __x"age {years}", years => 12;
21
22        # interpolation for one or many
23        my $nr_files = @files;
24        __nx"one file", "{_count} files", $nr_files;
25        __nx"one file", "{_count} files", \@files;
26
27        # interpolation of arrays
28        __x"price-list: {prices%.2f}", prices => \@prices, _join => ', ';
29
30        # white-spacing on msgid preserved
31        print __"\tCongratulations,\n";
32        print "\t", __("Congratulations,"), "\n";  # same
33

DESCRIPTION

35       Any use of a translation function exported by Log::Report, like "__()"
36       (the function is named underscore-underscore) or "__x()" (underscore-
37       underscore-x) will result in this object.  It will capture some
38       environmental information, and delay the translation until it is
39       needed.
40
41       Creating an object first and translating it later, is slower than
42       translating it immediately.  However, on the location where the message
43       is produced, we do not yet know in what language to translate it to:
44       that depends on the front-end, the log dispatcher.
45

METHODS

47   Constructors
48       $obj->clone(%options, $variables)
49           Returns a new object which copies info from original, and updates
50           it with the specified %options and $variables.  The advantage is
51           that the cached translations are shared between the objects.
52
53           example: use of clone()
54
55            my $s = __x "found {nr} files", nr => 5;
56            my $t = $s->clone(nr => 3);
57            my $t = $s->(nr => 3);      # equivalent
58            print $s;     # found 5 files
59            print $t;     # found 3 files
60
61       Log::Report::Message->fromTemplateToolkit($domain, $msgid, $params)
62           See Log::Report::Extract::Template on the details how to integrate
63           Log::Report translations with Template::Toolkit (version 1 and 2)
64
65       Log::Report::Message->new(%options)
66           End-users: do not use this method directly, but use
67           Log::Report::__() and friends.  The %options is a mixed list of
68           object initiation parameters (all with a leading underscore) and
69           variables to be filled in into the translated "_msgid" string.
70
71            -Option   --Default
72             _append    undef
73             _category  undef
74             _class     []
75             _classes   []
76             _context   undef
77             _count     undef
78             _domain    <from "use Log::Report">
79             _expand    false
80             _join      $" $LIST_SEPARATOR
81             _lang      <from locale>
82             _msgctxt   undef
83             _msgid     undef
84             _plural    undef
85             _prepend   undef
86             _to        <undef>
87
88           _append => STRING|MESSAGE
89             Text as STRING or MESSAGE object to be displayed after the
90             display of this message.
91
92           _category => INTEGER
93             The category when the real gettext library is used, for instance
94             LC_MESSAGES.
95
96           _class => STRING|ARRAY
97             When messages are used for exception based programming, you add
98             "_class" parameters to the argument list.  Later, with for
99             instance Log::Report::Dispatcher::Try::wasFatal(class), you can
100             check the category of the message.
101
102             One message can be part of multiple classes.  The STRING is used
103             as comma- and/or blank separated list of class tokens
104             (barewords), the ARRAY lists all tokens separately. See
105             classes().
106
107           _classes => STRING|ARRAY
108             Alternative for "_class", which cannot be used at the same time.
109
110           _context => WORDS|ARRAY
111             [1.00] Set keywords which can be used to select alternatives
112             between translations.  Read the DETAILS section in
113             Log::Report::Translator::Context
114
115           _count => INTEGER|ARRAY|HASH
116             When defined, the "_plural" need to be defined as well.  When an
117             ARRAY is provided, the length of the ARRAY is taken.  When a HASH
118             is given, the number of keys in the HASH is used.
119
120           _domain => STRING
121             The text-domain (translation table) to which this "_msgid"
122             belongs.
123
124             With this parameter, your can "borrow" translations from other
125             textdomains.  Be very careful with this (although there are good
126             use-cases)  The xgettext msgid extractor may add the used msgid
127             to this namespace as well.  To avoid that, add a harmless '+':
128
129               print __x(+"errors", _domain => 'global');
130
131             The extractor will not take the msgid when it is an expression.
132             The '+' has no effect on the string at runtime.
133
134           _expand => BOOLEAN
135             Indicates whether variables are to be filled-in.
136
137           _join => STRING
138             Which STRING to be used then an ARRAY is being filled-in.
139
140           _lang => ISO
141             [1.00] Override language setting from locale, for instance
142             because that is not configured correctly (yet).  This does not
143             extend to prepended or appended translated message object.
144
145           _msgctxt => STRING
146             [1.22] Message context in the translation file, the traditional
147             use.  Cannot be combined with "_context" on the same msgids.
148
149           _msgid => MSGID
150             The message label, which refers to some translation information.
151             Usually a string which is close the English version of the
152             message.  This will also be used if there is no translation
153             possible/known.
154
155             Leading white-space "\s" will be added to "_prepend".  Trailing
156             white-space will be added before "_append".
157
158           _plural => MSGID
159             Can be used together with "_count".  This plural form of the
160             "_msgid" text is used to simplify the work of translators, and as
161             fallback when no translation is possible: therefore, this can
162             best resemble an English message.
163
164             White-space at the beginning and end of the string are stripped
165             off.  The white-space provided by the "_msgid" will be used.
166
167           _prepend => STRING|MESSAGE
168             Text as STRING or MESSAGE object to be displayed before the
169             display of this message.
170
171           _to => NAME
172             Specify the NAME of a dispatcher as destination explicitly. Short
173             for  "report {to => NAME}, ..."  See to()
174
175   Accessors
176       $obj->append()
177           Returns the string or Log::Report::Message object which is appended
178           after this one.  Usually "undef".
179
180       $obj->classes()
181           Returns the LIST of classes which are defined for this message;
182           message group indicators, as often found in exception-based
183           programming.
184
185       $obj->context()
186           Returns an HASH if there is a context defined for this message.
187
188       $obj->count()
189           Returns the count, which is used to select the translation
190           alternatives.
191
192       $obj->domain()
193           Returns the domain of the first translatable string in the
194           structure.
195
196       $obj->msgctxt()
197           The message context for the translation table lookup.
198
199       $obj->msgid()
200           Returns the msgid which will later be translated.
201
202       $obj->prepend()
203           Returns the string which is prepended to this one.  Usually
204           "undef".
205
206       $obj->to( [$name] )
207           Returns the $name of a dispatcher if explicitly specified with the
208           '_to' key. Can also be used to set it.  Usually, this will return
209           undef, because usually all dispatchers get all messages.
210
211       $obj->valueOf($parameter)
212           Lookup the named $parameter for the message.  All pre-defined names
213           have their own method which should be used with preference.
214
215           example:
216
217           When the message was produced with
218
219             my @files = qw/one two three/;
220             my $msg = __xn "found one file: {file}"
221                          , "found {nrfiles} files: {files}"
222                          , scalar @files
223                          , file    => $files[0]
224                          , files   => \@files
225                          , nrfiles => @files+0
226                          , _class  => 'IO, files'
227                          , _join   => ', ';
228
229           then the values can be takes from the produced message as
230
231             my $files = $msg->valueOf('files');  # returns ARRAY reference
232             print @$files;              # 3
233             my $count = $msg->count;    # 3
234             my @class = $msg->classes;  # 'IO', 'files'
235             if($msg->inClass('files'))  # true
236
237           Simplified, the above example can also be written as:
238
239             local $" = ', ';
240             my $msg  = __xn "found one file: {files}"
241                           , "found {_count} files: {files}"
242                           , @files      # has scalar context
243                           , files   => \@files
244                           , _class  => 'IO, files';
245
246   Processing
247       $obj->concat( STRING|$object, [$prepend] )
248           This method implements the overloading of concatenation, which is
249           needed to delay translations even longer.  When $prepend is true,
250           the STRING or $object (other "Log::Report::Message") needs to
251           prepended, otherwise it is appended.
252
253           example: of concatenation
254
255            print __"Hello" . ' ' . __"World!";
256            print __("Hello")->concat(' ')->concat(__"World!")->concat("\n");
257
258       $obj->inClass($class|Regexp)
259           Returns true if the message is in the specified $class (string) or
260           matches the Regexp.  The trueth value is the (first matching)
261           class.
262
263       $obj->toHTML( [$locale] )
264           [1.11] Translate the message, and then entity encode HTML volatile
265           characters.
266
267           [1.20] When used in combination with a templating system, you may
268           want to use "<content_for =" 'HTML'>> in
269           Log::Report::Domain::configure(formatter).
270
271           example:
272
273             print $msg->toHTML('NL');
274
275       $obj->toString( [$locale] )
276           Translate a message.  If not specified, the default locale is used.
277
278       $obj->untranslated()
279           Return the concatenation of the prepend, msgid, and append strings.
280           Variable expansions within the msgid is not performed.
281

DETAILS

283   OPTIONS and VARIABLES
284       The Log::Report functions which define translation request can all have
285       OPTIONS.  Some can have VARIABLES to be interpolated in the string as
286       well.  To distinguish between the OPTIONS and VARIABLES (both a list of
287       key-value pairs), the keys of the OPTIONS start with an underscore "_".
288       As result of this, please avoid the use of keys which start with an
289       underscore in variable names.  On the other hand, you are allowed to
290       interpolate OPTION values in your strings.
291
292       Interpolating
293
294       With the "__x()" or "__nx()", interpolation will take place on the
295       translated MSGID string.  The translation can contain the VARIABLE and
296       OPTION names between curly brackets.  Text between curly brackets which
297       is not a known parameter will be left untouched.
298
299        fault __x"cannot open open {filename}", filename => $fn;
300
301        print __xn"directory {dir} contains one file"
302                 ,"directory {dir} contains {nr_files} files"
303                 , scalar(@files)            # (1) (2)
304                 , nr_files => scalar @files # (3)
305                 , dir      => $dir;
306
307       (1) this required third parameter is used to switch between the
308       different plural forms.  English has only two forms, but some languages
309       have many more.
310
311       (2) the "scalar" keyword is not needed, because the third parameter is
312       in SCALAR context.  You may also pass " \@files " there, because ARRAYs
313       will be converted into their length.  A HASH will be converted into the
314       number of keys in the HASH.
315
316       (3) the "scalar" keyword is required here, because it is LIST context:
317       otherwise all filenames will be filled-in as parameters to "__xn()".
318       See below for the available "_count" valure, to see how the "nr_files"
319       parameter can disappear.
320
321       Interpolation of VARIABLES
322
323       "Log::Report" uses String::Print to interpolate values in(translated)
324       messages.  This is a very powerful syntax, and you should certainly
325       read that manual-page.  Here, we only described additional features,
326       specific to the usage of "String::Print" in "Log::Report::Message"
327       objects.
328
329       There is no way of checking beforehand whether you have provided all
330       required values, to be interpolated in the translated string.
331
332       For interpolating, the following rules apply:
333
334       •   Simple scalar values are interpolated "as is"
335
336       •   References to SCALARs will collect the value on the moment that the
337           output is made.  The "Log::Report::Message" object which is created
338           with the "__xn" can be seen as a closure.  The translation can be
339           reused.  See example below.
340
341       •   Code references can be used to create the data "under fly".  The
342           "Log::Report::Message" object which is being handled is passed as
343           only argument.  This is a hash in which all OPTIONS and VARIABLES
344           can be found.
345
346       •   When the value is an ARRAY, all members will be interpolated with
347           $" between the elements.  Alternatively (maybe nicer), you can pass
348           an interpolation parameter via the "_join" OPTION.
349
350        local $" = ', ';
351        error __x"matching files: {files}", files => \@files;
352
353        error __x"matching files: {files}", files => \@files, _join => ', ';
354
355       Interpolation of OPTIONS
356
357       You are permitted the interpolate OPTION values in your string.  This
358       may simplify your coding.  The useful names are:
359
360       _msgid
361           The MSGID as provided with Log::Report::__() and Log::Report::__x()
362
363       _plural, _count
364           The PLURAL MSGIDs, respectively the COUNT as used with
365           Log::Report::__n() and Log::Report::__nx()
366
367       _textdomain
368           The label of the textdomain in which the translation takes place.
369
370       _class or _classes
371           Are to be used to group reports, and can be queried with inClass(),
372           Log::Report::Exception::inClass(), or
373           Log::Report::Dispatcher::Try::wasFatal().
374
375       . Example: using the _count
376
377       With Locale::TextDomain, you have to do
378
379         use Locale::TextDomain;
380         print __nx ( "One file has been deleted.\n"
381                    , "{num} files have been deleted.\n"
382                    , $num_files
383                    , num => $num_files
384                    );
385
386       With "Log::Report", you can do
387
388         use Log::Report;
389         print __nx ( "One file has been deleted.\n"
390                    , "{_count} files have been deleted.\n"
391                    , $num_files
392                    );
393
394       Of course, you need to be aware that the name used to reference the
395       counter is fixed to "_count".  The first example works as well, but is
396       more verbose.
397
398       Handling white-spaces
399
400       In above examples, the msgid and plural form have a trailing new-line.
401       In general, it is much easier to write
402
403          print __x"Hello, World!\n";
404
405       than
406
407          print __x("Hello, World!") . "\n";
408
409       For the translation tables, however, that trailing new-line is "over
410       information"; it is an layout issue, not a translation issue.
411
412       Therefore, the first form will automatically be translated into the
413       second.  All leading and trailing white-space (blanks, new-lines, tabs,
414       ...) are removed from the msgid before the look-up, and then added to
415       the translated string.
416
417       Leading and trailing white-space on the plural form will also be
418       removed.  However, after translation the spacing of the msgid will be
419       used.
420
421       Avoiding repetative translations
422
423       This way of translating is somewhat expensive, because an object to
424       handle the "__x()" is created each time.
425
426        for my $i (1..100_000)
427        {   print __x "Hello World {i}\n", i => $i;
428        }
429
430       The suggestion that Locale::TextDomain makes to improve performance, is
431       to get the translation outside the loop, which only works without
432       interpolation:
433
434        use Locale::TextDomain;
435        my $i = 42;
436        my $s = __x("Hello World {i}\n", i => $i);
437        foreach $i (1..100_000)
438        {   print $s;
439        }
440
441       Oops, not what you mean because the first value of $i is captured in
442       the initial message object.  With Log::Report, you can do it (except
443       when you use contexts)
444
445        use Log::Report;
446        my $i;
447        my $s = __x("Hello World {i}\n", i => \$i);
448        foreach $i (1..100_000)
449        {   print $s;
450        }
451
452       Mind you not to write: "for my $i" in above case!!!!
453
454       You can also write an incomplete translation:
455
456        use Log::Report;
457        my $s = __x "Hello World {i}\n";
458        foreach my $i (1..100_000)
459        {   print $s->(i => $i);
460        }
461
462       In either case, the translation will be looked-up only once.
463

OVERLOADING

465       overload: as $function
466           When the object is used to call as $function, a new object is
467           created with the data from the original one but updated with the
468           new parameters.  Implemented in "clone()".
469
470       overload: concatenation
471           An (accidental) use of concatenation (a dot where a comma should be
472           used) would immediately stringify the object.  This is avoided by
473           overloading that operation.
474
475       overload: stringification
476           When the object is used in string context, it will get translated.
477           Implemented as toString().
478

SEE ALSO

480       This module is part of Log-Report distribution version 1.33, built on
481       July 17, 2021. Website: http://perl.overmeer.net/CPAN/
482

LICENSE

484       Copyrights 2007-2021 by [Mark Overmeer <markov@cpan.org>]. For other
485       contributors see ChangeLog.
486
487       This program is free software; you can redistribute it and/or modify it
488       under the same terms as Perl itself.  See http://dev.perl.org/licenses/
489
490
491
492perl v5.34.0                      2021-07-22           Log::Report::Message(3)
Impressum