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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

print output from array and foreach command

Status
Not open for further replies.

merang

Programmer
Aug 27, 2014
17
MY
Hi, i am new to tcl programming. i have one question about array. i store data from .txt files in an array call country.

[highlight #EF2929]array set country {$food $place}[/highlight]

where $food and $place is the data that i get from the .txt file. i want to display them so i do:

foreach {$food $place} [array get country] {
puts "Food : $food Where? : $place"
}

and the output is:

Food : Burger Where? : Mexico
Food : Curry Where? : India
Food : Sushi Where? : Japan

now i want to count the total elements in array country. i try [highlight #EF2929]puts "[array size country]"[/highlight] but the output is 1.

the expected output:
Food : Burger Where? : Mexico
Food : Curry Where? : India
Food : Sushi Where? : Japan
Total elements : 3

Please help, thanks in advance :)
 
Hi

There is a bug, but that is in [tt]foreach[/tt] : the loop control variables should be just names, without sigil. The [tt]array size[/tt] works exactly as you wrote it :
Code:
[blue]%[/blue] array set country { Burger Mexico Curry India Sushi Japan }

[blue]%[/blue] foreach {food place} [array get country] { puts "Food : $food Where? : $place" }
Food : Sushi Where? : Japan
Food : Curry Where? : India
Food : Burger Where? : Mexico

[blue]%[/blue] puts "[array size country]"
3

[blue]%[/blue] puts $tcl_version
8.6

So I tend to believe the problem is somewhere else.


Feherke.
feherke.ga
 
Normally, is such cases, I tend to simply work around the problem and not spend too much time to the root cause. But, best practice is to investigate why the problem occurs, of course. Depends on the priority and importance of one's code I guess...

Anyway, one most simple workaround would be running a counter in the foreach loop incrementing with 1 with each loop and simply puts $counter instead of [array size country] in the end?

thacoda
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top