Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

processing an array

Status
Not open for further replies.

isahak

Programmer
Dec 12, 2007
3
Hi everyone
My question is I have a text file, like this

123456 4
111111 8
666666 4

Now I want to read all these information into an array.
so I wrote,

arr[$1]=$2;
{
for(x in arr)
print x, arr[x];
}

my output is

123456 4
123456 4
111111 8
111111 8
123456 4
666666 4
111111 8
666666 4
123456 4

why is it like this. it should be
123456 4
111111 8
666666 4

So, does anyone know, how to solve this.
Thanks
 
You only want to execute the for loop once at the end of the input, so you should put it in an END clause.

Also, you want to execute the array population for every line of input, so you should include it between braces, e.g.

Code:
{ arr[$1]=$2 }
END {
    for(x in arr)
        print x, arr[x]
}

Annihilannic.
 
To complete the explanation; if you put code outside the { ... } braces, it is considered an expression. If it evaluates to true (which arr[$1]=$2 always will) for the current input line, the code between { ... } that follows it will be executed for that line.

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top