2014-07-11 26 views
0

有人可以解釋,爲什麼我沒有得到預期的結果?awk,自定義的delarray函數

awk ' 
# I know there is delete array, but this is more portable 
# that is what docs are saying, anyway wanted to test it out. 
function delarray(a, i) 
{ 
    for (i in a) 
     delete a[i] 
} 

BEGIN { 
    a[3]="" 
    a[4]="" 
    for (e in a) 
     print e 
    delarray(a) 
    for (e in a) 
     print ".." 
     print e 
} 
' 

執行上面的腳本,我期望看到:

3 
4 
..(nothing here) 

我以前..想法,我不會看到任何東西,因爲 刪除陣列值,這樣正好看到..爲佔位符)

,但實際輸出我看到的是:

3 
4 
4 #(why this?, and where are two dots?) 

,退出代碼爲1,爲什麼?

+0

無論你正在閱讀什麼文檔,說創建該函數是「刪除數組」的替代方法,將它們扔掉。 'split(「」,array)'是'delete array'的可移植替代。 –

回答

2

你刪除功能的工作。

由於您缺少圍繞for (e in a)循環的大括號,因此它只包含print ".."語句,這就是您看不到任何點的原因。

print e命令只是打印分配給e(來自先前的for (e in a)循環)的最後一個值,即4

但是你的功能並不是非常有用,因爲幾乎所有版本的awk都允許delete a命令沒有索引。它符合POSIX標準。

+0

但是在之前調用delarray(a)'之後,第二個'print e'中的'e'如何存活? – branquito

+1

爲什麼不呢?它不是數組的一部分。這是一個完全獨立的變量。 – ooga

+0

哦的確如此。滑稽。 – branquito

2

您在第二個循環周圍缺少花括號。

for (e in a) { 
    print ".." 
    print e 
} 

輸出:

3 
4