tags:

views:

36

answers:

1

Hi, I encountered this issue on both Solaris and Linux, with tcl version 8.3/8.4

please see the following code:

#!/usr/bin/tclsh

set pattern "this is * and *"
set str "this is tcl and c++"

switch -glob $str {

  $pattern {
    puts "matched pattern"
  }
  "this is * and *" {
    puts "matched plain text"
  }
  default {
    puts "matched none"
  }

}

and the result is "matched plain text". I though it should have matched the $pattern... is this an incorrect usage of switch, or I am not giving correct pattern for -glob option?

please someone give some idea and it is better if you can tell how to modify the code to make it run with switch and variable.

Thanks! XM

+7  A: 

I believe you're misunderstanding how Tcl parsing/substitution works. Specifically, the glob command is getting the arguments:

1: -glob
2: $str
3: {

  $pattern {
    puts "matched pattern"
  }
  "this is * and *" {
    puts "matched plain text"
  }
  default {
    puts "matched none"
  }

}

The {...} construct "groups" the things inside it into a single, un-substituted (verbatim) piece of data. As such, the third argument to switch contains "$pattern", not the result of replacing $pattern with the value of the pattern variable.

If you need substitution, you need to avoid using curly braces (I'm simplifying). So, if you really want to substitute the value for the pattern in, the easiest way to do it is to use the other form of switch (which passes in each pattern/code block as a separate argument):

switch -glob $str $pattern {
    puts "matched pattern"
} "this is * and *" {
    puts "matched plain text"
} default {
    puts "matched none"
}

As a note, it's almost always a good idea to use the -- (no more flags) flag with switch when you're using a variable substitution for the string to match. That avoids the problem where your $str contains something starting with a -

switch -glob -- $str $pattern {
    puts "matched pattern"
} "this is * and *" {
    puts "matched plain text"
} default {
    puts "matched none"
}
RHSeeger
Seeger, thanks for your answer, it works and helps. Your words on how tcl scripts are being substituted also inspires alot. Thank you. XM.
X.M.
Glad I could help. Honestly, "groking" Tcl "grouping" (quotes vs curly braces) tends to be the single biggest stumbling point to those new to Tcl. If you don't get it, you can wind up going down a long road of doing it wrong, leading to lots of pain. If you do get it, nearly everything else in the language is really simple.
RHSeeger