File: DefHash.pod

package info (click to toggle)
libdefhash-perl 2.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 168 kB
  • sloc: perl: 39; makefile: 2
file content (409 lines) | stat: -rw-r--r-- 13,224 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package DefHash; # just to make PodWeaver happy

# AUTHORITY
# DATE
our $DIST = 'DefHash'; # DIST
# VERSION

1;
# ABSTRACT: Define things according to a specification, using hashes

__END__

=pod

=encoding UTF-8

=head1 NAME

DefHash - Define things according to a specification, using hashes

=head1 SPECIFICATION VERSION

 2

=head1 VERSION

This document describes version 2.0.1 of DefHash (from Perl distribution DefHash), released on 2022-10-21.

=head1 SYNOPSIS

A function returning a list of books from database, where each book is a
hash (DefHash):

 sub list_books {
     my $search_title = shift;

     $search_title = "%$search_title%" unless $search_title =~ /[%?]/;
     my $sth = $dbh->prepare("SELECT * FROM books WHERE title=?");
     $sth->execute($search_title);

     my @books;
     while (my $row = $sth->fetchrow_hashref) {
         push @books, {
             title   => $row->{title},
             summary => $row->{abstract},
             tags    => [($row->{in_print} ? () : ("out-of-print"))],
         };
     }
     @books;
 }

=head1 ABSTRACT

This document describes DefHash, a specification for using hashes to define
things. DefHash was born out of several other projects/specifications like
L<Sah>, L<Rinci>, L<Riap>, L<Module::Patch> (see L</"HISTORY">).

=head1 SPECIFICATION

In this document, hashes are written in JSON or pseudo-JSON (e.g. contains
ellipsis C<...> or JavaScript-style comments C<// ...> or dangling comma).

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL "NOT", "SHOULD",
"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
interpreted as described in RFC 2119.

=head2 Definitions

=over 4

=item * B<defhash>

A regular hash, or dictionary (as it is called in Python), or associative array
(as it is called in PHP), or object (as it is called in JavaScript). A defhash
has B<properties>, which translates to the hash key/value pairs. B<Property
names> translates to hash keys, while B<property values> translates to hash
values. The same hash key/value pairs are used to store B<property attributes>:

 {
     "v": 1,                         // set value for property 'v'
     "prop1": "value1",              // set value for property 'prop1'
     "prop2": ["value2", ...],       // set value for property 'prop2'

     "prop1.attr1": ...,             // set value for prop1's attribute
     "prop1.attr1.subattr1": ...,    // set value for prop1's attribute

     "_extra1": ...,                 // ignored property, starts with _
     "prop1._extra_attr": ...,       // ignored attribute, starts with _

     ".attr1": ...,                  // set value for the hash's attribute
     ".attr1.subattr1": ...,         // set value for the hash's attribute
 }

The above defhash defines two properties: C<prop1> and C<prop2>. C<prop1> has
two attributes, C<attr1> and C<attr1.subattr1>. Properties with names starting
with underscore (C<_>) are ignored; this can be used to put extra information.
Likewise for attribute names which start with underscore.

Property names must follow this regex '\A[A-Za-z_][A-Za-z0-9_]*\z' (an
alphanumeric-only word). Property attributes must follow this regex:
'\A([A-Za-z_][A-Za-z0-9_]*)?(\.[A-Za-z_][A-Za-z0-9_]*)+\z' (a dotted
alphanumeric-only word).

Property value can be anything. It can contain another defhash for defining
subentities, for example. In Rinci, a function metadata has a property called
C<args> to define function arguments; its value is a hash of argument names and
argument specification. Each argument specification is a defhash.

Property attributes can be used to store extra data into a property.

The hash itself can have attributes, stored in .<attr> keys:

 {
     ".attr1": ...,
     ".attr2.subattr": ...,
     "._ignored": ...
 }

=item * B<specification>

A set of recognized properties and property attributes, including whether the
properties are required, expected values (schema) for properties and attributes,
and default values.

For example, Rinci is a specification for function metadata (among others). One
writes a defhash (metadata) for a function, it contains properties to describe
the function. Rinci specifies what properties are available and the meaning and
expected values for each of those properties. An example of a Rinci function
metadata:

 // metadata for function 'sum'
 {
     "v": 2, // version of Rinci specification
     "summary": "Sum all the elements of array numerically",
     "description":
         "Non-numeric elements in array will be skipped. Empty array
          or no numeric elements in array will result in 0 for the
          sum.",
     "args": {
         "array": {
             "summary": "The array to sum",
             "schema": "array*",
         },
     },
 }

=back

=head2 Why write definitions in a defhash?

Hash is a basic data structure that is supported by all high-level languages,
including Perl, Python, PHP, Ruby, and JavaScript. It is particularly easy to
merge. It makes checking the existence of value of property very easy, by just
accessing the hash's key.

B<... instead of text (like POD)?> Putting definition in a data structure makes
it easier to manipulate the definition (merge, parse, normalize, convert, etc).

B<... instead of array?> Hash allows us to evolve more easily. If we deprecate a
property or add new ones, elements don't have to shift like in array.

B<... instead of a regular or nested hash?> Well, defhash is a regular hash. It
is just a convention to limit the range of valid keys (only alphanumeric
characters) in exchange for additional metadata for each key (which is stored as
regular keys in the same hash). Plus it establishes convention for some
predefined properties and attributes.

=head2 Common properties

These are the list of properties that all specifications must recognize:

=over 4

=item * B<v> => FLOAT (default: 1)

This specifies the version of specification that the defhash is following.

A specification can change over time. The C<v> property specifies the
specification version which the hash follows. Specification version is a
non-negative real number, but integer is recommended. If unspecified, it is
assumed to be 1. It can also be 0.

=item * B<defhash_v> => INT (default: 2)

This specifies the version of DefHash specification itself.

=item * B<name> => TEXT

A short (usually single-word) name for the thing that is described. For example,
in Rinci function metadata, it is the function's name. In Sah, it is a name of
the schema that can be used by the human compiler.

 // metadata for function 'sum'
 {
     "name": "sum",
     ...
 }

 // schema for describing positive integer
 ["int", {
     "name": "pos_int",
     "min": 0,
 }]

=item * B<caption> => text

Like C<name>, but for display purposes.

=item * B<summary> => TEXT

A short (< 72 character), one-line summary about the thing that is described.
For example, in Rinci function metadata, the C<summary> describes what the
function does:

 // metadata for function 'sum'
 {
     "summary": "Sum all the elements of an array numerically",
     ...
 }

=item * B<description> => TEXT

A longer description. Normally a paragraph or longer of text. The text is
assumed to be marked up in Markdown.

=item * B<tags> => ARRAY[TEXT | DEFHASH]

A list of one or more tags, can be used to categorize the thing that is
described. Example:

 "tags": ["important", "category:filtering", "category:filtering-for-foo"],

Each tag can also be a defhash for more detailed specification:

 "tags": ["important",
          {"name":"category:filtering", "summary":"filtering field"},
          {"name":"category:filtering-for-foo", "summary":"filtering for field 'foo'"}]

=item * B<default_lang> => TEXT

Default language. Defaults to parent's value, or if parent does not exist, from
environment LANG, or if undefined or C<C>, C<en_US>.

=item * B<x> => ANY

This property is used to store extended (application-specific) attributes, much
like the C<X-> prefix in HTTP or email headers. This property can be used as an
alternative to using underscore prefix (e.g. C<_foo>). Some processing tools
strip properties/attributes that begin with underscores, so to pass extended
metadata around, it might be more convenient to use the C<x> property.

Example:

 {
     "x.myapp.foo" => 1,
     "x.myapp.bar" => "some value",
 }

=back

=head2 Property attributes

Below is the list of property attributes that must be supported.

=over

=item * alt

This attribute can be used to store alternate property values.

B<alt.lang>. The most common is alternative language (C<alt.lang.LANG_CODE>),
where you want to provide translations. Example:

 {
     "summary": "An English summary",
     "summary.alt.lang.id_ID": "Ringkasan dalam bahasa Indonesia",
 }

B<alt.env>. Another kind of alternate is environment (C<alt.env.NAME>), for
example we might want to use different summary when displayed in a CLI program
vs web application. Example (in a Rinci function argument's specification):

 {
     "summary.alt.env.cmdline": "Like --foo, do something foobar-ish",
     "summary.alt.env.web": "Like the `foo` field, do something foobar-ish",
 }

B<alt.bool>. Another kind of alternate is boolean logic (C<alt.bool.WHICH>,
where C<WHICH> can be C<not>), when you want to specify the negative
sense/sentence instead of the regular positive one. Example (in a Rinci function
argument's specification):

 "tcp": {
     "schema": "bool",
     "default": true,
     "summary": "Parse TCP connections",
     "summary.alt.bool.not": "Do not parse TCP connections",
 }

B<alt.plurality>. Another kind of alternate is grammatical variance based on
noun plurality (C<alt.plurality.WHICH> where C<WHICH> can be C<singular> or
C<plural>). Example (in a Rinci function argument's specification, where an
array argument like C<files> translates in a CLI environment to multiple
C<--file> option specification):

 "files": {
     "schema": ["array*", {"of":"str*"}],
     "summary": "Specify one or more files to check",
     "summary.alt.plurality.singular": "Add a file to check (can be specified multiple times)",
 }

B<Combination of alternates.> Example:

 {
     "default_lang": "en_US",

     "summary": "An English summary",

     "summary.alt.lang.id_ID.env.web":"(Summary in Indonesian, for web)",
     "summary.alt.env.web.lang.id_ID":"(Summary in Indonesian, for web)", // equivalent to previous line

     "summary.alt.lang.id_ID.env.cmdline":"(Summary in Indonesian, for cmdline)",
     "summary.alt.env.cmdline.lang.id_ID":"(Summary in Indonesian, for cmdline)", // equivalent to previous line
 }

=back

=head2 When should specification version be increased?

When a backward-incompatible change is introduced. This is defined to be removal
of a recognized property, or the semantic change of an existing property, or
other incompatible change. For example,

 XXX (modp 1->2, 2->3; ri ->2, not using defhash but that is not the real reason, removal of features property)
 XXX riap also bumped to 2 just because it uses hash

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/DefHash>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-DefHash>.

=head1 SEE ALSO

Semantic Versioning, L<http://semver.org>

Markdown specification

Implementation: L<Hash::DefHash> is the official implementation in Perl to check
and manipulate DefHash. Other modules: L<Regexp::Pattern::DefHash>,
L<Sah::Schemas::DefHash>.

=head1 HISTORY

=head2 version 2 (Aug 2021)

Major version number bumped to 2 because we removed the C<PROP(LANG)> syntax
support.

=head2 version 1 (Sep 2012)

First release of the specification.

=head2 Sah (2009-2011), Rinci (2009-2012), Module::Patch (Jan 2012), Riap (Apr 2012)

I started using hash for putting metadata in projects like L<Sah>, L<Rinci>,
L<Riap>, and L<Module::Patch> and finding myself choosing the same property
names like C<summary>, C<description>, etc.

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 CONTRIBUTING


To contribute, you can send patches by email/via RT, or send pull requests on
GitHub.

Most of the time, you don't need to build the distribution yourself. You can
simply modify the code, then test via:

 % prove -l

If you want to build the distribution (e.g. to try to install it locally on your
system), you can install L<Dist::Zilla>,
L<Dist::Zilla::PluginBundle::Author::PERLANCAR>,
L<Pod::Weaver::PluginBundle::Author::PERLANCAR>, and sometimes one or two other
Dist::Zilla- and/or Pod::Weaver plugins. Any additional steps required beyond
that are considered a bug and can be reported to me.

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2022, 2021, 2019, 2015, 2014, 2013, 2012 by perlancar <perlancar@cpan.org>.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=DefHash>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=cut