1 package Sub::Prototype::Util;
9 use Scalar::Util qw/reftype/;
13 Sub::Prototype::Util - Prototype-related utility routines.
21 use vars qw/$VERSION/;
27 use Sub::Prototype::Util qw/flatten wrap recall/;
30 my @args = ( \@a, 1, { d => 2 }, undef, 3 );
32 my @flat = flatten '\@$;$', @args; # ('a', 'b', 'c', 1, { d => 2 })
33 recall 'CORE::push', @args; # @a contains 'a', 'b', 'c', 1, { d => 2 }, undef, 3
34 my $splice = wrap 'CORE::splice';
35 my @b = $splice->(\@a, 4, 2); # @a is now ('a', 'b', 'c', 1, 3) and @b is ({ d => 2 }, undef)
39 Prototypes are evil, but sometimes you just have to bear with them, especially when messing with core functions.
40 This module provides several utilities aimed at facilitating "overloading" of prototyped functions.
42 They all handle C<5.10>'s C<_> prototype.
48 my %sigils = qw/SCALAR $ ARRAY @ HASH % GLOB * CODE &/;
49 my %reftypes = reverse %sigils;
54 if (!defined $a || !defined($r = reftype $a)) { # not defined or plain scalar
55 croak 'Got ' . ((defined $a) ? 'a plain scalar' : 'undef')
56 . ' where a reference was expected';
58 croak 'Unexpected ' . $r . ' reference' unless exists $sigils{$r}
59 and $p =~ /\Q$sigils{$r}\E/;
65 $msg =~ s/(?:\s+called)?\s+at\s+.*$//s;
69 =head2 C<flatten $proto, @args>
71 Flattens the array C<@args> according to the prototype C<$proto>.
72 When C<@args> is what C<@_> is after calling a subroutine with prototype C<$proto>, C<flatten> returns the list of what C<@_> would have been if there were no prototype.
73 It croaks if the arguments can't possibly match the required prototype, e.g. when a reference type is wrong or when not enough elements were provided.
80 return @_ unless defined $proto;
83 while ($proto =~ /(\\?)(\[[^\]]+\]|[^\];])/g) {
88 my $reftype = _check_ref $arg, $sigil;
90 push @args, $reftype eq 'SCALAR'
92 : ($reftype eq 'ARRAY'
98 : &$arg # _check_ref ensures this must be a code ref
103 } elsif ($sigil =~ /[\@\%]/) {
107 croak 'Not enough arguments to match this prototype' unless @_;
115 =head2 C<wrap $name, %opts>
117 Generates a wrapper that calls the function C<$name> with a prototyped argument list.
118 That is, the wrapper's arguments should be what C<@_> is when you define a subroutine with the same prototype as C<$name>.
121 my $push = wrap 'CORE::push';
122 $push->($a, 3, 4); # returns 3 + 2 = 5 and $a now contains 0 .. 4
124 You can force the use of a specific prototype.
125 In this case, C<$name> must be a hash reference that holds exactly one key / value pair, the key being the function name and the value the prototpye that should be used to call it.
127 my $push = wrap { 'CORE::push' => '\@$' }; # only pushes 1 arg
129 Others arguments are seen as key / value pairs that are meant to tune the code generated by L</wrap>.
134 =item C<< ref => $func >>
136 Specifies the function used in the generated code to test the reference type of scalars.
137 Defaults to C<'ref'>.
138 You may also want to use L<Scalar::Util/reftype>.
140 =item C<< wrong_ref => $code >>
142 The code executed when a reference of incorrect type is encountered.
143 The result of this snippet is also the result of the generated code, hence it defaults to C<'undef'>.
144 It's a good place to C<croak> or C<die> too.
146 =item C<< sub => $bool >>
148 Encloses the code into a C<sub { }> block.
151 =item C<< compile => $bool >>
153 Makes L</wrap> compile the code generated and return the resulting code reference.
154 Be careful that in this case C<ref> must be a fully qualified function name.
155 Defaults to true, but turned off when C<sub> is false.
159 For example, this allows you to recall into C<CORE::grep> and C<CORE::map> by using the C<\&@> prototype :
161 my $grep = wrap { 'CORE::grep' => '\&@' };
162 sub mygrep (&@) { $grep->(@_) } # the prototypes are intentionally different
167 my ($name, $proto, $i, $args, $coderefs, $opts) = @_;
169 while ($proto =~ s/(\\?)(\[[^\]]+\]|[^\];])//) {
170 my ($ref, $sigil) = ($1, $2);
171 $sigil = $1 if $sigil =~ /^\[([^\]]+)\]/;
176 if (length $sigil > 1) {
177 my $code = "my \$r = $opts->{ref}($cur); ";
180 $name, $proto, ($i + 1), $args . "$_\{$cur}, ", $coderefs, $opts
182 "if (\$r eq '$reftypes{$_}') { $subcall }";
184 $code .= join ' els', @branches, "e { $opts->{wrong_ref} }";
187 $args .= "$sigil\{$cur}, ";
189 } elsif ($sigil =~ /[\@\%]/) {
190 $args .= '@_[' . $i . '..$#_]';
191 } elsif ($sigil =~ /\&/) {
192 my %h = do { my $c; map { $_ => $c++ } @$coderefs };
200 $args .= "sub{&{\$c[$j]}}, ";
201 } elsif ($sigil eq '_') {
202 $args .= "((\@_ > $i) ? $cur : \$_), ";
212 return "$name($args)";
217 croak 'No subroutine specified' unless $name;
222 $proto = prototype $name;
223 } elsif ($r eq 'HASH') {
224 croak 'Forced prototype hash reference must contain exactly one key/value pair' unless keys %$name == 1;
225 ($name, $proto) = %$name;
227 croak 'Unhandled ' . $r . ' reference as first argument';
231 $name =~ s/[\s\$\@\%\*\&;].*//;
233 return $name, $proto;
237 my ($name, $proto) = _check_name shift;
238 croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
241 $opts{ref} ||= 'ref';
242 $opts{sub} = 1 unless defined $opts{sub};
243 $opts{compile} = 1 if not defined $opts{compile} and $opts{sub};
244 $opts{wrong_ref} = 'undef' unless defined $opts{wrong_ref};
248 if (defined $proto) {
249 $call = _wrap $name, $proto, 0, '', \@coderefs, \%opts;
251 $call = _wrap $name, '', 0, '@_';
255 my $decls = @coderefs > 1 ? 'my @c = @_[' . join(', ', @coderefs) . ']; '
256 : 'my @c = ($_[' . $coderefs[0] . ']); ';
257 $call = $decls . $call;
261 $call = "sub $call" if $opts{sub};
263 if ($opts{compile}) {
270 croak _clean_msg $err if $err;
276 =head2 C<recall $name, @args>
278 Calls the function C<$name> with the prototyped argument list C<@args>.
279 That is, C<@args> should be what C<@_> is when you call a subroutine with C<$name> as prototype.
280 You can still force the prototype by passing C<< { $name => $proto } >> as the first argument.
283 recall { 'CORE::push' => '\@$' }, $a, 1, 2, 3; # $a just contains 1
285 It's implemented in terms of L</wrap>, and hence calls C<eval> at each run.
286 If you plan to recall several times, consider using L</wrap> instead.
296 $wrap = eval { wrap $name };
299 croak _clean_msg $err if $err;
306 The functions L</flatten>, L</wrap> and L</recall> are only exported on request, either by providing their name or by the C<':funcs'> and C<':all'> tags.
310 use base qw/Exporter/;
312 use vars qw/@EXPORT @EXPORT_OK %EXPORT_TAGS/;
316 'funcs' => [ qw/flatten wrap recall/ ]
318 @EXPORT_OK = map { @$_ } values %EXPORT_TAGS;
319 $EXPORT_TAGS{'all'} = [ @EXPORT_OK ];
323 L<Carp>, L<Exporter> (core modules since perl 5), L<Scalar::Util> (since 5.7.3).
327 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
329 You can contact me by mail or on C<irc.perl.org> (vincent).
333 Please report any bugs or feature requests to C<bug-sub-prototype-util at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Sub-Prototype-Util>.
334 I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
338 You can find documentation for this module with the perldoc command.
340 perldoc Sub::Prototype::Util
342 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Prototype-Util>.
344 =head1 COPYRIGHT & LICENSE
346 Copyright 2008,2009,2010,2011 Vincent Pit, all rights reserved.
348 This program is free software; you can redistribute it and/or modify it
349 under the same terms as Perl itself.
353 1; # End of Sub::Prototype::Util