Skip to content

Commit 85e963c

Browse files
committed
Add some code examples
1 parent 5df5a0e commit 85e963c

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

ppcs/ppcTODO-signature-named-parameters.md

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,49 @@ There are no anticipated security concerns with expanding the way that subroutin
8686

8787
As the intention of this syntax addition is to make existing code practice more consise and simple to write, it would be illustrative to compare pairs of functions written in the newly proposed vs. the existing style.
8888

89-
TODO
89+
One example comes from [`IPC::MicroSocket::Server`](https://metacpan.org/pod/IPC::MicroSocket::Server). This is currently using the `Sublike::Extended` module (see "Prototype Implementation" below) to provide the syntax. The actual module also uses `Object::Pad` to provide the `method` keyword; this example is paraphrased to avoid that. This module requires a `path` named argument, and optionally takes a `listen` argument, defaulting its value to 5 if the caller did not provide a defined value.
90+
91+
```perl
92+
extended sub new_unix ( $class, :$path, :$listen //= 5 )
93+
{
94+
...
95+
}
96+
```
97+
98+
This replaces the previous version of the code which handled arguments by the more traditional approach of assigning into a hash:
99+
100+
```perl
101+
sub new_unix ( $class, %args )
102+
{
103+
my $path = $args{path};
104+
my $listen = $args{listen} // 5;
105+
...
106+
}
107+
```
108+
109+
Already the new code is shorter and more consise. Additionally it contains error checking that complains about missing mandatory keys, or unrecognised keys, which the previous version of the code did not include.
110+
111+
Another example, this time from [`Text::Treesitter::QueryCursor`](https://metacpan.org/pod/Text::Treesitter::QueryCursor). This method takes an optional argument named `multi`, tested for truth. If absent it should default to false.
112+
113+
```perl
114+
sub next_match_captures ( $self, :$multi = 0 )
115+
{
116+
...
117+
}
118+
```
119+
120+
The previous version of this code did include complaints about unrecognised keys, and was rather longer because of it:
121+
122+
```perl
123+
sub next_match_captures ( $self, %options )
124+
{
125+
my $multi = delete $options{multi};
126+
keys %options and
127+
croak "Unrecognised options to ->next_captures: " . join( ", ", keys %options );
128+
129+
...
130+
}
131+
```
90132

91133
## Prototype Implementation
92134

0 commit comments

Comments
 (0)