AWK是否支持动态用户定义的变量? [英] Does awk support dynamic user-defined variables?
问题描述
AWK支持这样的:
awk '{print $(NF-1);}'
而不是用户定义的变量:
but not for user-defined variables:
awk '{a=123; b="a"; print $($b);}'
顺便说一句,外壳支持这样的:
by the way, shell supports this:
a=123;
b="a";
eval echo \${$b};
我
如何才能实现我的目的AWK?
How can I achieve my purpose in awk?
推荐答案
目前不。不过,如果你提供了一个包装,这是(有点哈克和肮脏的)成为可能。
我们的想法是使用@操作符,在最新版本的gawk介绍。
Not at the moment. However, if you provide a wrapper, it is (somewhat hacky and dirty) possible. The idea is to use @ operator, introduced in the recent versions of gawk.
这@操作符通常用于按名称来调用一个函数。
所以,如果你有
This @ operator is normally used to call a function by name. So if you had
function foo(s){print "Called foo "s}
function bar(s){print "Called bar "s}
{
var = "";
if(today_i_feel_like_calling_foo){
var = "foo";
}else{
var = "bar";
}
@var( "arg" ); # This calls function foo(), or function bar() with "arg"
}
现在,这是它自己的有用。
假设我们知道变种名称预先,我们可以写一个包装来间接修改,并获得瓦尔
Now, this is usefull on it's own. Assuming we know var names beforehand, we can write a wrapper to indirectly modify and obtain vars
function get(varname, this, call){call="get_"varname;return @call();}
function set(varname, arg, this, call){call="set_"varname; @call(arg);}
所以,现在,您要prrvide按名称访问的每个变量名称,要声明这两个函数
So now, for each var name you want to prrvide access by name, you declare these two functions
function get_my_var(){return my_var;}
function set_my_var(arg){my_var = arg;}
和prahaps,在BEGIN {}块地方,
And prahaps, somewhere in your BEGIN{} block,
BEGIN{ my_var = ""; }
要声明它的全局访问。
然后你可以使用
To declare it for global access. Then you can use
get("my_var");
set("my_var", "whatever");
这可以在第一次出现没有用,但也有非常良好的使用情况下,如
保持瓦尔的一个链表,通过在另一变种的阵列,并且这样保持变种的名字。
它适用于阵列过了,说实话,我用这对中嵌套和连接阵列
阵列,这样我就可以通过多种阵列走路像使用指针。
This may appear useless at first, however there are perfectly good use cases, such as keeping a linked list of vars, by holding the var's name in another var's array, and such. It works for arrays too, and to be honest, I use this for nesting and linking Arrays within Arrays, so I can walk through multiple Arrays like using pointers.
您也可以写配置参考VAR名字里面的awk这样的脚本,
实际上有一个跨preTER-内-A-间preTER的东西类型,也...
You can also write configure scripts that refer to var names inside awk this way, in effect having a interpreter-inside-a-interpreter type of things, too...
不做事的最佳途径,但是,它可以完成任务,我不担心
空指针异常,或GC和这样的: - )
Not the best way to do things, however, it gets the job done, and I do not have to worry about null pointer exceptions, or GC and such :-)
这篇关于AWK是否支持动态用户定义的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!