Sah/Schema/str_or_code.pm

filter: Statementstmt 81.8% 9 / 11 Branchbran 0.0% 0 / 2 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 33.3% 1 / 3 Podpod n/a totaltotal 62.5% 10 / 16 CC 2 SCAR 13.2
CC
2
Cov
69%
__ANON__
6.0
__ANON__
2.0
BEGIN
1.0
CRAP 3.8
↑ Summary Sah/Schema/str_or_re_or_code.pm »
1 package Sah::Schema::str_or_code;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
6 1 our $DATE = '2024-02-06'; # DATE
7 1 our $DIST = 'Sah-Schemas-Str'; # DIST
8 1 our $VERSION = '0.018'; # VERSION
9  
10 our $schema = [any => {
11 summary => 'String or coderef (if string is of the form `sub {...}`)',
12 description => <<'MARKDOWN',
13  
14 Either string or coderef is accepted.
15  
16 If string matches the regex `qr/\Asub\s*\{.*\}\z/s`, then it will be eval'ed
17 into a coderef. If the code fails to compile, the value will be rejected. Note
18 that this means you accept arbitrary code from the user to execute! Please make
19 sure first and foremost that this is acceptable in your case.
20  
21 Currently string is eval'ed in the `main` package, without `use strict` or `use
22 warnings`.
23  
24 This schema is handy if you want to accept string or coderef from the
25 command-line.
26  
27 What's the difference between this schema and `code_from_str` (from
28 <pm:Sah::Schemas::Code>)? Both this schema and `code_from_str` accept string,
29 but `code_from_str` will directly compile any input string while this schema
30 will only convert string to code if it is in the form of `sub { ... }`. In other
31 words, this schema can output either string or coderef, while `code_from_str`
32 will always produce coderef.
33  
34 MARKDOWN
35 of => [
36 ['str'],
37 ['code'],
38 ],
39  
40 prefilters => ['Str::maybe_eval'],
41  
42 examples => [
43 {value=>'', valid=>1},
44 {value=>'a', valid=>1},
45 {value=>{}, valid=>0, summary=>'Not a string'},
46  
47 0 ▶ {value=>'sub {}', valid=>1, code_validate=>sub { ref($_[0]) eq 'CODE' & !defined($_[0]->()) }},
Subroutine __ANON__: not called CC=1 SCAR=6.9
48 0 ▶ {value=>'sub{"foo"}', valid=>1, code_validate=>sub { ref($_[0]) eq 'CODE' && $_[0]->() eq 'foo' }},
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "CODE" and $_[0]->() eq "foo" 0 0 0
49 1 {value=>'sub {', valid=>1, summary=>'Becomes a string'},
50  
51 {value=>'sub {1=2}', valid=>0, summary=>'Code does not compile'},
52 ],
53  
54 }];
55  
56 1 1;
57 # ABSTRACT:
58  
59 __END__
↑ Summary Sah/Schema/str_or_re_or_code.pm »