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!

scan function -- setting more than 1 variable

Status
Not open for further replies.

cptk

Technical User
Mar 18, 2003
305
US
This should be easy ...
I'm reading a line from a text file, then I'm scanning the line with a format string to two variables. When I go to display the 2nd variable, it says "Can't read var2: no such variable".
what am I doing wrong within the scan cmd?

EXAMPLE
somefile.txt file contains:
abc xyz

excerpt of code:
1> set FID [open somefile.txt r]
2> gets $FID line
3> scan $line "%3s, %3s" var1 var2
4> .logwindow insert end "$var1 $var2"
{note: "logwindow" is the item_name of a text widget}

Via the scan, how do I write to the 2nd variable?

Note: the following lines give me ...
> .logwindow insert end [llength $line] gives me 2", which is what I expect.
> .logwindow insert end [scan $line "%3s, %3s" var1 var2] gives me "1". WHY ONLY ONE CONVERSION ????

IF the reason is whitspace in my text file, even when I modify the text file to "xyzabc", I still would expect to have two conversions to both var1 and var2 in the scan function.
 
Code:
  set filename somefile.txt
  
  set FID [open $filename w]
  puts $FID "abc xyz"
  close $FID

  set FID [open $filename r]
  gets $FID line
  close $FID
  puts "line: \"$line\""
  set var1 ""
  set var2 ""
  scan $line "%3s, %3s" var1 var2
  puts "var1: \"$var1\""
  puts "var2: \"$var2\""
  set var1 ""
  set var2 ""
  scan $line "%3s %3s" var1 var2
  puts "var1: \"$var1\""
  puts "var2: \"$var2\""

In your code the variable var2 is not initialized, nor loaded by the scan command. This, because your pattern doesn't match the content of the file.
You need, either add a "," in the file after the first string, or remove the "," from the scan pattern.

For this case it is better to initialize the vars before using them in a scan.

HTH

ulis
 
You know, I though it was simple.

I simply took out the "," in my scan; now it's
converting to two variables like I needed.

Funny thing is, I "thought" I tried this prior to my
posting.

Thank for the reply ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top