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;
33 # @flat contains now ('a', 'b', 'c', 1, { d => 2 })
35 my $res = recall 'CORE::push', @args;
36 # @a contains now 'a', 'b', 'c', 1, { d => 2 }, undef, 3
39 my $splice = wrap 'CORE::splice';
40 my @b = $splice->(\@a, 4, 2);
41 # @a contains now ('a', 'b', 'c', 1, 3)
42 # and @b is ({ d => 2 }, undef)
46 Prototypes are evil, but sometimes you just have to bear with them, especially when messing with core functions.
47 This module provides several utilities aimed at facilitating "overloading" of prototyped functions.
49 They all handle C<5.10>'s C<_> prototype.
55 my %sigils = qw<SCALAR $ ARRAY @ HASH % GLOB * CODE &>;
56 my %reftypes = reverse %sigils;
59 my ($arg, $sigil) = @_;
62 if (not defined $arg or not defined($reftype = reftype $arg)) {
63 # not defined or plain scalar
64 my $that = (defined $arg) ? 'a plain scalar' : 'undef';
65 croak "Got $that where a reference was expected";
68 croak "Unexpected $reftype reference" unless exists $sigils{$reftype}
69 and $sigil =~ /\Q$sigils{$reftype}\E/;
77 $msg =~ s/(?:\s+called)?\s+at\s+.*$//s;
84 my @flattened = flatten($proto, @args);
86 Flattens the array C<@args> according to the prototype C<$proto>.
87 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.
88 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.
95 return @_ unless defined $proto;
98 while ($proto =~ /(\\?)(\[[^\]]+\]|[^\];])/g) {
103 my $reftype = _check_ref $arg, $sigil;
105 push @args, $reftype eq 'SCALAR'
107 : ($reftype eq 'ARRAY'
109 : ($reftype eq 'HASH'
111 : ($reftype eq 'GLOB'
113 : &$arg # _check_ref ensures this must be a code ref
118 } elsif ($sigil =~ /[\@\%]/) {
122 croak 'Not enough arguments to match this prototype' unless @_;
132 my $wrapper = wrap($name, %opts);
133 my $wrapper = wrap({ $name => $proto }, %opts);
135 Generates a wrapper that calls the function C<$name> with a prototyped argument list.
136 That is, the wrapper's arguments should be what C<@_> is when you define a subroutine with the same prototype as C<$name>.
139 my $push = wrap 'CORE::push';
140 $push->($a, 3, 4); # returns 3 + 2 = 5 and $a now contains 0 .. 4
142 You can force the use of a specific prototype.
143 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.
145 my $push = wrap { 'CORE::push' => '\@$' }; # only pushes 1 arg
147 The remaining arguments C<%opts> are treated as key / value pairs that are meant to tune the code generated by L</wrap>.
152 =item C<< ref => $func >>
154 Specifies the function used in the generated code to test the reference type of scalars.
155 Defaults to C<'ref'>.
156 You may also want to use L<Scalar::Util/reftype>.
158 =item C<< wrong_ref => $code >>
160 The code executed when a reference of incorrect type is encountered.
161 The result of this snippet is also the result of the generated code, hence it defaults to C<'undef'>.
162 It's a good place to C<croak> or C<die> too.
164 =item C<< sub => $bool >>
166 Encloses the code into a C<sub { }> block.
169 =item C<< compile => $bool >>
171 Makes L</wrap> compile the code generated and return the resulting code reference.
172 Be careful that in this case C<ref> must be a fully qualified function name.
173 Defaults to true, but turned off when C<sub> is false.
177 For example, this allows you to recall into C<CORE::grep> and C<CORE::map> by using the C<\&@> prototype :
179 my $grep = wrap { 'CORE::grep' => '\&@' };
180 # the prototypes are intentionally different
181 sub mygrep (&@) { $grep->(@_) }
186 my ($name, $proto, $i, $args, $coderefs, $opts) = @_;
188 while ($proto =~ s/(\\?)(\[[^\]]+\]|[^\];])//) {
189 my ($ref, $sigil) = ($1, $2);
190 $sigil = $1 if $sigil =~ /^\[([^\]]+)\]/;
195 if (length $sigil > 1) {
196 my $code = "my \$r = $opts->{ref}($cur); ";
199 $name, $proto, ($i + 1), $args . "$_\{$cur}, ", $coderefs, $opts
201 "if (\$r eq '$reftypes{$_}') { $subcall }";
203 $code .= join ' els', @branches, "e { $opts->{wrong_ref} }";
206 $args .= "$sigil\{$cur}, ";
208 } elsif ($sigil =~ /[\@\%]/) {
209 $args .= '@_[' . $i . '..$#_]';
210 } elsif ($sigil =~ /\&/) {
211 my %h = do { my $c; map { $_ => $c++ } @$coderefs };
219 $args .= "sub{&{\$c[$j]}}, ";
220 } elsif ($sigil eq '_') {
221 $args .= "((\@_ > $i) ? $cur : \$_), ";
231 return "$name($args)";
236 croak 'No subroutine specified' unless $name;
241 $proto = prototype $name;
242 } elsif ($r eq 'HASH') {
243 croak 'Forced prototype hash reference must contain exactly one key/value pair' unless keys %$name == 1;
244 ($name, $proto) = %$name;
246 croak 'Unhandled ' . $r . ' reference as first argument';
250 $name =~ s/[\s\$\@\%\*\&;].*//;
252 return $name, $proto;
256 my ($name, $proto) = _check_name shift;
257 croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
260 $opts{ref} ||= 'ref';
261 $opts{sub} = 1 unless defined $opts{sub};
262 $opts{compile} = 1 if not defined $opts{compile} and $opts{sub};
263 $opts{wrong_ref} = 'undef' unless defined $opts{wrong_ref};
267 if (defined $proto) {
268 $call = _wrap $name, $proto, 0, '', \@coderefs, \%opts;
270 $call = _wrap $name, '', 0, '@_';
274 my $decls = @coderefs > 1 ? 'my @c = @_[' . join(', ', @coderefs) . ']; '
275 : 'my @c = ($_[' . $coderefs[0] . ']); ';
276 $call = $decls . $call;
280 $call = "sub $call" if $opts{sub};
282 if ($opts{compile}) {
289 croak _clean_msg $err if $err;
297 my @res = recall($name, @args);
298 my @res = recall({ $name => $proto }, @args);
300 Calls the function C<$name> with the prototyped argument list C<@args>.
301 That is, C<@args> should be what C<@_> is when you call a subroutine with C<$name> as prototype.
302 You can still force the prototype by passing C<< { $name => $proto } >> as the first argument.
305 recall { 'CORE::push' => '\@$' }, $a, 1, 2, 3; # $a just contains 1
307 It's implemented in terms of L</wrap>, and hence calls C<eval> at each run.
308 If you plan to recall several times, consider using L</wrap> instead.
315 my $safe_wrap = sub {
321 $wrap = eval { wrap $name };
329 # goto tends to crash a lot on perl 5.8.0
331 my ($wrap, $err) = $safe_wrap->(shift);
332 croak _clean_msg $err if $err;
337 my ($wrap, $err) = $safe_wrap->(shift);
338 croak _clean_msg $err if $err;
346 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.
350 use base qw<Exporter>;
352 use vars qw<@EXPORT @EXPORT_OK %EXPORT_TAGS>;
356 'funcs' => [ qw<flatten wrap recall> ]
358 @EXPORT_OK = map { @$_ } values %EXPORT_TAGS;
359 $EXPORT_TAGS{'all'} = [ @EXPORT_OK ];
363 L<Carp>, L<Exporter> (core modules since perl 5), L<Scalar::Util> (since 5.7.3).
367 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
369 You can contact me by mail or on C<irc.perl.org> (vincent).
373 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>.
374 I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
378 You can find documentation for this module with the perldoc command.
380 perldoc Sub::Prototype::Util
382 Tests code coverage report is available at L<http://www.profvince.com/perl/cover/Sub-Prototype-Util>.
384 =head1 COPYRIGHT & LICENSE
386 Copyright 2008,2009,2010,2011 Vincent Pit, all rights reserved.
388 This program is free software; you can redistribute it and/or modify it
389 under the same terms as Perl itself.
393 1; # End of Sub::Prototype::Util