On Tue, Apr 21, 2009 at 20:12, Chas. Owens <[email protected]> wrote:
> On Tue, Apr 21, 2009 at 20:00, Kelly Jones <[email protected]>
> wrote:
>> I want to do "function completion". If I have functions called where()
>> and which(), I want whe() to call where(), whi() to call which(), and
>> wh() to return something like "Ambigious: where() and which() both
>> match wh()".
>>
>> What's the best/easiest way to do this?
> snip
>
> This is a bad idea, but you should be able to achieve this through
> the AUTOLOAD[1] functionality.
>
> 1. http://perldoc.perl.org/perlsub.html#Autoloading
>
> --
> Chas. Owens
> wonkden.net
> The most important skill a programmer can have is the ability to read.
>
I still say it is a bad idea, but here you go:
#!/usr/bn/perl
use strict;
use warnings;
use Carp;
sub who { print "who: @_\n"; }
sub when { print "when: @_\n"; }
sub where { print "where: @_\n"; }
sub what { print "what: @_\n"; }
sub why { print "why: @_\n"; }
sub AUTOLOAD {
our $AUTOLOAD;
my ($sub) = $AUTOLOAD =~ /main::(.*)/;
my @subs = grep { defined &{$_} and /^\Q$sub\E/ } keys %main::;
#replace AUTOLOAD with the matched function
goto &{$subs[0]} if @subs == 1;
#die if with special error if multiple matches
croak "ambiguos function $sub" if @subs;
#die if there are no matches;
croak "no function named $sub";
}
eval { how(1, 2, 3) };
print $@;
eval { wh(1, 2, 3) };
print $@;
eval { whe(1, 2, 3) };
print $@;
wher(1, 2, 3);
why(1, 2, 3);
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/