This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Using a proc in a regsub?

Help for those learning Tcl or writing their own scripts.
Post Reply
User avatar
CrazyCat
Revered One
Posts: 1334
Joined: Sun Jan 13, 2002 8:00 pm
Location: France
Contact:

Using a proc in a regsub?

Post by CrazyCat »

Hello there,

I'm trying to do a small tcl who generate a random string based on a pattern, I want to replace a special char ("?") with a random other char. The trouble is that this special char could be several times in the pattern, I don't want to have the same replacement.

I'm trying with someting like:

Code: Select all

proc rnd:replace {pattern} {
   regsub -all -- \? $pattern [rand 9] pattern
   return pattern
}
And sure, it fails (couldn't compile regular expression pattern: quantifier operand invalid)...
Is there a way to eval a proc in a regsub?

Thanks by advance
User avatar
user
 
Posts: 1452
Joined: Tue Mar 18, 2003 9:58 pm
Location: Norway

Re: Using a proc in a regsub?

Post by user »

I think you mean "\\?", not "\?". The first backslash is substituted when the regsub line is evaluated, resulting in "?" being passed as a pattern to regsub, which will interpret the unescaped "?" as a quantifier - leading to the error message you got.

There is no way to invoke a command for each match using regsub - currently - some people in #tcl@freenode are experimenting with a new regexp engine that may be included in a future version of Tcl, but don't hold your breath ;)

However... replacing a single character is easy to do using split,foreach and append:

Code: Select all

proc replacething {str find code} {
	set out ""
	foreach chr [split $str ""] {
		append out [if {[string eq $chr $find]} {eval $code} {set chr}]
	}
	set out
}

# tclsh tests:
% proc rand i {expr {int(rand()*$i)}};# there's no [rand] in tclsh
% replacething "Hello????" ? {rand 9}
Hello5643
% replacething "axaxax" x {format %c [expr {65+int(rand()*26)}]}
aZaWaU
Have you ever read "The Manual"?
User avatar
CrazyCat
Revered One
Posts: 1334
Joined: Sun Jan 13, 2002 8:00 pm
Location: France
Contact:

Post by CrazyCat »

OK, that's what I was thinking...
I'm used to use regexp in PHP, with callback function and eval...

Thanks a lot
Post Reply