Last active
December 16, 2015 20:18
-
-
Save riywo/5490962 to your computer and use it in GitHub Desktop.
dynamic function calling in perl/python/ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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:]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
please let me know about other languages!