我正试图找到一种方法来使用[正则表达式]作为[变量名]或[函数名]。是否有任何编程或脚本语言提供此功能?
我想要的功能示例(使用类似Java的伪代码):
int <<(my|a|an)(number|Integer)>> = 10;
//this variable has a regular expression as a name
function <<((print|write)(Stuff|Things|Words))>>(int myInt){
//this function has a regular expression as a name
System.out.println(myInt);
}
printStuff(myInt); //should have the same effect as the next line
writeWords(anInteger); //should have the same effect as the previous line
答案 0 :(得分:1)
在Perl中,您可以使用AUTOLOAD
为函数执行此类操作。
my @refun = (
[qr/(print|write)(Stuff|Things|Words)/ => sub { print "printStuff(@_)\n"; }],
[qr/fo+(?:ba+r)?/ => sub { print "foobar(@_)\n"; }],
);
our $AUTOLOAD;
sub AUTOLOAD{
for(@refun){
my ($re, $sub) = @$_;
goto &$sub if $AUTOLOAD =~ /$re/;
}
my ($package, $filename, $line) = caller;
die "Undefined subroutine &$AUTOLOAD called at $filename line $line.\n";
}
printStuff(10);
writeWords(10);
foo();
fooooooooooooooobar(1,2,3);
输出:
printStuff(10)
printStuff(10)
foobar()
foobar(1 2 3)
不确定变量,但也可能是这样。