[techtalk] switch function in C (or how to read commandline args?)

Penguina penguina at cosyn.co.nz
Thu Jul 5 08:02:25 EST 2001


it might make sense to separate out the issues of

	command-line interface packages

	hash tables

	lexical analysers

	parsers

	tokens: what they are & the variety of things you can use them for

	how to initialize function pointers, then invoke
	the functions using their pointers in various languages

	our friend the b-tree

While all these things are related (they come together spectacularly
when writing a new compiler, for example), it might be useful for
non CS grads to familiarise themselves with the above concepts
prior to jumping into a project which uses one or the other.

> On Mon, Jul 02, 2001 at 01:33:50AM +0100, Conor Daly wrote:
> > Thanks James and Jeff for the thoughts.  It kinda looks like an if else-if
> > chain is my only option.

On Tue, 3 Jul 2001, Almut Behrens wrote:
> In perl you could do something like:
>
> %handlers = (
>     "-foo" => \&do_foo,
>     "-bar" => \&do_bar,
>     ...
> );
>
> sub do_foo { ... }
> sub do_bar { ... }
> ...
>
> $handlers{$ARGV[0]}->( $ARGV[1] );
>
> $ test.pl -bar baz
>
> the routine do_bar() would get called with the argument "baz" to take
> care of handling the commandline option "-bar".
> The last line of the above code snipped would effectively execute as
>
> $handlers{"-bar"}->("baz");
>
> which does the same as if you had simply written
>
> do_bar("baz");
>
> The $handlers{"-bar"} part selects/returns the appropriate function
> reference via the association declared in the hash table ("-bar" =>
> \&do_bar). This function reference is then called with the argument "baz".

in python, you can use function pointers as dictionary objects
and let the hashing happen behind the scenes.

---------------snip
def joe():
  return "Joe Jackson"

def bill():
  return "Billy the Kid"

main ():
  dict.append ({'name': "joe",  'tok':3, 'fun': joe()  })
  dict.append ({'name': "bill", 'tok':4, 'fun': bill() })

  for entry in dict:
#				test arg by string or token here
        print (entry['fun'])

main()
---------------snip

> So, if we could find an easy way to accomplish this string-to-number
> mapping in C code, we could basically use the same technique in C.

it's called strtok, but for actually parsing text input, you're
better off with lex and yacc (or their gnu counterparts flex and
bison).

These are what the tools most linux compilers are written with
and give you a lot more flexibility in the structure of the input.

Cheryl





More information about the Techtalk mailing list