Skip to content

Instantly share code, notes, and snippets.

@riywo
Last active December 16, 2015 20:18
Show Gist options
  • Save riywo/5490962 to your computer and use it in GitHub Desktop.
Save riywo/5490962 to your computer and use it in GitHub Desktop.
dynamic function calling in perl/python/ruby
#!/usr/bin/env perl
use strict;
use warnings;
package CLI;
use Data::Dumper;
sub new {
bless {}, $_[0];
}
sub run {
my ($self, $argv) = @_;
my $command = $argv->[0];
my $func = "CMD_$command";
$self->$func([splice(@$argv, 1)]);
}
sub CMD_put {
my ($self, $argv) = @_;
print "run command put with $argv->[0]\n";
}
sub CMD_get {
my ($self, $argv) = @_;
print "run command get\n";
}
my $cli = CLI->new();
$cli->run([@ARGV]);
#!/usr/bin/env python
import sys
class CLI(object):
def run(self, argv):
command = argv[0]
func = "CMD_%s" % command
getattr(self, func)(argv[1:])
def CMD_put(self, argv):
print "run command put with %s" % argv[0]
def CMD_get(self, argv):
print "run command get"
if __name__ == "__main__":
cli = CLI()
cli.run(sys.argv[1:])
#!/usr/bin/env ruby
class CLI
def run(argv)
command = argv[0]
func = "CMD_#{command}"
send func, argv[1..-1]
end
def CMD_put(argv)
puts "run command put with #{argv[0]}"
end
def CMD_get(argv)
puts "run command get"
end
end
cli = CLI.new
cli.run(ARGV)
$ perl call_func.pl get
run command get
$ perl call_func.pl put aaa
run command put with aaa
$ python call_func.py get
run command get
$ python call_func.py put aaa
run command put with aaa
$ ruby call_func.rb get
run command get
$ ruby call_func.rb put aaa
run command put with aaa
@riywo
Copy link
Author

riywo commented Apr 30, 2013

please let me know about other languages!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment