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

associative array

Status
Not open for further replies.

TCLstud

Technical User
Feb 6, 2007
1
CA
i'm new to tcl and familiar with perl
i prob where i have to count the number of phone
by user

example

JOHN: 234-4534
JOHN: 234-1212
SARAH: 567-3434
SARAH: 646-1212
ALICE: 234-2342

if perl i
can do
while (<>) {

$COUNTPHONE{$1}++ if /^(\S+): /;
}

how can i do the same thing in TCL
THX
 
How is your data presented? Do you read a file?
Do you know what user names you have apart from the sample input? That is, do you know a priori that you're looking for, say, "JOHN"?

_________________
Bob Rashkin
 
1 - the list is known:
Code:
  # create the list
  set list \
  {
    "JOHN: 234-4534"
    "JOHN: 234-1212"
    "SARAH: 567-3434"
    "SARAH: 646-1212"
    "ALICE: 234-2342"
  }
  # declare an array
  array set phones {}
  # fill the array with phone number lists
  foreach line $list \
  {
    # split each line to get the name & the number
    foreach {name number} [split $line :] break
    # trim the heading space of the number
    set number [string trim $number]
    # add the number to a named entry of the array
    if {[info exists phones($name)]} \
    {
      # one more
      lappend phones($name) $number 
    } \
    else \
    {
      # the first
      set phones($name) [list $number] 
    }
  }
  # display the array
  parray phones
  # get the numbers count from the lists
  foreach name [array names phones] \
  { 
    set numbers $phones($name)
    puts "$name: [llength $numbers] ([join $numbers])"
  }

The result:
Code:
phones(ALICE) = 234-2342
phones(JOHN)  = 234-4534 234-1212
phones(SARAH) = 567-3434 646-1212
ALICE: 1 (234-2342)
SARAH: 2 (567-3434 646-1212)
JOHN: 2 (234-4534 234-1212)

2 - getting the list from a file
Code:
  # the name of the file
  set fn mylist.txt
  # opening the file
  set fp [open $fn r]
  # getting the content
  set content [read $fp]
  # closing
  close $fp
  # splitting the content into lines
  set list [split $content \n]

If you need info about the command [red]cmd[/red] try:
[red]cmd[/red]

HTH

ulis
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top