2012-01-06 46 views
1

我試圖找到一種方法來將[正則表達式]用作[變量名稱]或[函數名稱]。是否有任何編程或腳本語言提供此功能?我想(使用類似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 
+1

爲什麼?在解決這個問題之後,必須有更好的方法來解決任何真正的問題。 – 2012-01-06 03:23:27

+0

我試圖使用多個名稱來引用一個函數或變量,以便我不需要記住具有長名稱的函數的確切名稱。鍵入與正則表達式匹配的字符串(convert | change)((int | integer)Array)(To)(DoubleArray | arrayOfDoubles)並使該正則表達式引用特定函數比嘗試記住功能。 – 2012-01-06 03:38:59

+0

我也可以設置某種宏來自動替換我正在使用的源代碼中的文本。這可能是一個更好的解決方案。 – 2012-01-06 03:45:03

回答

1

在Perl中,你可以使用AUTOLOAD功能做這樣的事情。

Example

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) 

不確定的變量,但它可能是可能的。

+1

看到這個問題的答案,我印象深刻。這可能是我在這裏發佈的最奇怪最深奧的問題,你仍然能夠回答它。 :) – 2012-01-06 03:58:59