Debian Codegraph @

t/08func-refalias.t

raw
1 #!/usr/bin/perl
2
3 use v5.14;
4 use warnings;
5
6 use Test2::V0 0.000147; # is_oneref
7 BEGIN {
8 $] >= 5.026000 or plan skip_all => "No parse_subsignature()";
9 }
10
11 use feature 'signatures';
12 no warnings 'experimental';
13
14 use lib "t";
15 use testcase "t::func";
16
17 BEGIN { $^H{"t::func/rfunc"}++ }
18
19 {
20 rfunc totals(\@array, \%hash) {
21 return scalar @array + scalar keys %hash;
22 }
23
24 is( totals( [10, 11], {a => "A"} ), 3,
25 'func with refalias invoked');
26
27 like( dies { totals( {}, {} ) },
28 qr/^Expected argument 1 to main::totals to be a reference to ARRAY at /,
29 'Exception thrown by wrong reference type' );
30 like( dies { totals( [], [] ) },
31 qr/^Expected argument 2 to main::totals to be a reference to HASH at /,
32 'Exception thrown by wrong reference type' );
33 }
34
35 # refalias parameters can have defaults
36 {
37 rfunc add_them_all(\@arr = [1, 2]) {
38 my $n = 0;
39 $n += $_ for @arr;
40 return $n;
41 }
42
43 is( add_them_all(), 3, 'refalias with default applies when absent' );
44 is( add_them_all( [ 4, 5 ] ), 9, 'refalias param default can be overridden' );
45
46 rfunc default_explodes(\@arr = die "This should not be invoked") { }
47
48 ok( lives { default_explodes( [] ) },
49 'Defaulting expression of refalias parameter is not invoked with passed value' );
50 }
51
52 # refaliased variables can be edited in place
53 {
54 rfunc inc_all(\@arr) {
55 $_++ for @arr;
56 }
57
58 my @array = ( 1, 2, 3 );
59 inc_all \@array;
60 is( \@array, [ 2, 3, 4 ],
61 'refalias func can mutate caller-passed container' );
62
63 my $arr = [];
64 inc_all $arr;
65 is_oneref( $arr, '$arr has one reference after refaliasing call' );
66 }
67
68 # refalias on named parameters
69 {
70 rfunc refnamed_scalar( :\$scl ) { return 0 + !!defined $scl; }
71 rfunc refnamed_array ( :\@arr ) { return scalar @arr; }
72 rfunc refnamed_hash ( :\%hsh ) { return scalar keys %hsh; }
73
74 is( refnamed_scalar( scl => \1 ), 1,
75 'Refalias named scalar parameter' );
76 is( refnamed_array( arr => ['x', 'y', 'z'] ), 3,
77 'Refalias named array parameter' );
78 is( refnamed_hash( hsh => { x => 1, y => 2 } ), 2,
79 'Refalias named hash parameter' );
80
81 like( dies { refnamed_array() },
82 qr/^Missing argument 'arr' for subroutine main::refnamed_array at /,
83 'complaint from missing named param' );
84 }
85
86 # refalias named can have defaults
87 {
88 rfunc refnamed_maybe_array( :\@arr = [2] ) { return $arr[0]; }
89
90 is( refnamed_maybe_array( ), 2,
91 'Refalias named array parameter default applies' );
92 is( refnamed_maybe_array( arr => [5] ), 5,
93 'Refalias named array parameter with value overrides default' );
94 }
95
96 done_testing;