Re: Difference between $foo and [set foo]



Hans Herrmann wrote:
> last time you helped me with a problem:
>
> ###################
>
> set a 1,0
> set b 2,0
> foreach pos {a b} {
> regsub -all {,} [set $pos] {.} [set pos]
> }
>
> ######################
>
> Why i must not do "$$pos" or "[eval puts $pos]" and for the seconde
> substitution "$pos". I'm not a specialist in programming, I'm a
> "hobby-tcler" but I want to know the difference in simple words.

No doubt there are subtle differences between $foo and [set foo] that
I'll fail to mention. One that occurs to me is that you can't do $$foo
but you can do $[set foo] and [set $foo].

In your example, in the foreach body, pos will have one of two values,
"a" or "b". The third argument to regsub needs to be "1,0" or "2,0".
You have [set $pos] which gets processed this way on the first
iteration:

$pos gets expanded to "a"
[set] gets invoked as it you'd written [set a] and returns "1,0"

The last argument to regsub must be a variable name. You want "a" or
"b" here. You've written [set pos] which will work. It gets processed
this way:

[set] returns the value of pos, "a"

You could also have used "$pos" there.


I find it helpful to use *Name when to name variables which are the
_names_ of other variables. For example:

proc doSomething { arrayName } {
upvar $arrayName a
set a(foo) 1
}
doSomething x
puts $x(foo) ;# displays "1"

In your case:

set a 1,0
set b 2,0
foreach varName {a b} {
set oldValue [set $varName]
regsub -all {,} $oldValue {.} $varName
}

Does that help?

Chris

.



Relevant Pages

  • Re: while loop -> map
    ... push @bar, pos $foo;} print join; ' ... I'm guessing not, since map is expecting a list and not a scalar, which $foo is. ...
    (perl.beginners)
  • Re: [PATCH] more 1.9 warning fixes
    ... |May I apply these patches? ... |pos is shadowed in IRB::OutputFormat#foo, but I don't see where foo is ... If #foo is actually used, ... matz. ...
    (comp.lang.ruby)