jkeys
jkeys

Reputation: 145

TCL: Find first number in list?

Using a list, is it possible to find the first value within a list ? (without using the obvious foreach item> $list loop)

eg I have a list {23dsf} { } {2a} {255} {gsd3fs} {fg'dslk23} {...}

I was looking at lsearch -integer, but that requires identifying what the number is :(

I need to simply identify the first numeric value, ie 255 (lindex 3)

Upvotes: 1

Views: 585

Answers (3)

user15498903
user15498903

Reputation:

Using lsearch -regexp as pointed out in comments.

given the list:

set lst {{23dsf} { } {2a} {255} {gsd3fs} {fg'dslk23} {...}}

lsearch -regexp $lst {^\d+$}

or its equivalent

lsearch -regexp $lst {^[[:digit:]]+$}

Return the index (3) of the first numeric value in the list.

Upvotes: 2

Colin Macleod
Colin Macleod

Reputation: 4382

Here's a one-liner, using lmap to filter out non-integers and then just taking the first element of what's left:

(bin) 9 % set lst [list {23dsf} { } {2a} {255} {gsd3fs} {fg'dslk23} {...} 42]
23dsf { } 2a 255 gsd3fs fg'dslk23 ... 42
(bin) 10 % lindex [lmap i $lst {expr {[string is integer -strict $i] ? $i : [continue]}}] 0
255

Upvotes: 0

Shawn
Shawn

Reputation: 52409

I'd just use a foreach loop, but if you really don't want to, well, recursion is just looping in a different dress:

#!/usr/bin/env tclsh
package require Tcl 8.6

proc firstint {lst} {
   if {[llength $lst]} {
      set first [lindex $lst 0]
      if {[string is integer -strict $first]} {
         return $first
      } else {
         tailcall firstint [lrange $lst 1 end]
      }
   }
}

set lst [list {23dsf} { } {2a} {255} {gsd3fs} {fg'dslk23} {...}]
puts [firstint $lst]

Upvotes: 1

Related Questions