0

更新

下面的原始描述有很多错误;gawk lint 不会抱怨用作 RHS 的未初始化数组in。例如,以下示例没有给出错误或警告。我没有删除这个问题,因为我即将接受的答案给出了使用split空字符串创建空数组的好建议。

BEGIN{
    LINT = "fatal"; 
    // print x; // LINT gives error if this is uncommented 
    thread = 0;
    if (thread in threads_start) { 
        print "if"; 
    } else {  
        print "not if"; 
    }
}

原始问题

我的很多 awk 脚本都有如下结构:

if (thread in threads_start) {  // LINT warning here
  printf("%s started at %d\n", threads[thread_start]));
} else {
  printf("%s started at unknown\n");
}

结果gawk --lint

警告:对未初始化变量“thread_start”的引用

所以我在 BEGIN 块中初始化如下。但这看起来很杂乱。有没有更优雅的方法来创建一个零元素数组?

BEGIN { LINT = 1; thread_start[0] = 0; delete thread_start[0]; }
4

2 回答 2

1

我认为您可能在代码中犯了一些错字。

if (thread in threads_start) { // LINT warning here (you think)

thread在这里,您可以在 array 中查找索引threads_start

  printf("%s started at %d\n", threads[thread_start])); // Actual LINT warning

但是在这里你打印thread_start数组中的索引threads!还要注意不同的 sthread/threadsthreads_start/ thread_start。Gawk 实际上是在正确警告您thread_start在第二行使用 (without s)。

printf您的格式也有错误。

当您更改这些时,lint 警告消失:

if (thread in threads_start) {
  printf("%s started at %d\n", thread, threads_start[thread]));
} else {
  printf("%s started at unknown\n");
}

但也许我误解了你的代码应该做什么。在这种情况下,您能否发布一个产生虚假 lint 警告的最小独立代码示例?

于 2011-11-08T11:39:48.960 回答
0

概括

在 Awk 中创建空数组的惯用方法是使用split().

细节

为了简化上面的示例以专注于您的问题而不是拼写错误,可以通过以下方式触发致命错误:

BEGIN{
    LINT = "fatal"; 
    if (thread in threads_start) { 
        print "if"; 
    } else {  
        print "not if"; 
    }
}

这会产生以下错误:

gawk: cmd. line:3: fatal: reference to uninitialized variable `thread'

thread在使用它进行搜索之前给出一个值threads_start通过 linting:

BEGIN{
    LINT = "fatal"; 
    thread = 0;
    if (thread in threads_start) { 
        print "if"; 
    } else {  
        print "not if"; 
    }
}

产生:

not if

要使用未初始化的数组创建 linting 错误,我们需要尝试访问不存在的条目:

BEGIN{
    LINT = "fatal"; 
    thread = 0;
    if (threads_start[thread]) { 
        print "if"; 
    } else {  
        print "not if"; 
    }
}

产生:

gawk: cmd. line:4: fatal: reference to uninitialized element `threads_start["0"]'

因此,您实际上并不需要在 awk 中创建一个空数组,但如果您这样做并回答您的问题,请使用split()

BEGIN{
    LINT = "fatal"; 
    thread = 0;
    split("", threads_start);
    if (thread in threads_start) { 
        print "if"; 
    } else {  
        print "not if"; 
    }
}

产生:

not if

于 2013-04-03T06:42:36.750 回答