如何创建一个空数组 [英] how to create an empty array

查看:1080
本文介绍了如何创建一个空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新

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

The original description below has many errors; gawk lint does not complain about uninitialized arrays used as RHS of in. For example, the following example gives no errors or warnings. I am not deleting the question because the answer I am about to accept gives good suggestion of using split with an empty string to create an empty array.

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脚本的结构如下:

A lot of my awk scripts have a construct as follows:

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"

warning: reference to uninitialized variable `thread_start'

因此,我在BEGIN块中进行了如下初始化.但这看起来很k.有没有更优雅的方法来创建零元素数组?

So I initialize in the BEGIN block as follows. But this looks kludge-y. Is there a more elegant way to create a zero-element array?

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

推荐答案

摘要

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

详细信息

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

To simplify your example above to focus on your question rather than your typos, the fatal error can be triggered with:

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中使用值提供thread之前进行搜索会导致掉毛:

Giving thread a value before using it to search in threads_start passes linting:

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

产生:

not if

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

To create a linting error with an uninitialised array, we need to attempt to access an non-existent entry:

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() :

So, you don't really need to create an empty array in Awk, but if you want to do so, and answer your question, use split():

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

产生:

not if

这篇关于如何创建一个空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆