in reply to Re: passing arguments in a dispatch table
in thread passing arguments in a dispatch table
Frankly, I think I need an object, but I'm reluctant to use one or a closure. I am introducing a dispatch table as a new concept on a perl beginners mailing list (PBML on Yahoo!). The original script used @book as a global variable. I changed it to $friut for the example above.
I haven't added the response yet. I do a ton of editing before replying, so I'm still able to scrap this approach.
Currently, I'm here:sub process { my ( $choice, $book ) = @_; my $dispatch = { 1 => \&search_menu, 2 => sub { return \&edit_name($book) }, 3 => sub { return add_entry($book) }, 4 => sub { return delete_entry($book) }, 5 => \&save_default, 6 => \sub{ print "Goodbye!\n"; die; }, e => \sub{ print "Goodbye!\n"; die; }, }; print &{ $dispatch->{ $choice } }; }
It's a direct move from a group of if - elsif blocks that did the same thing. That's why I'd like to call the subs the same way now. I can introduce better concepts in later posts. I consider this an intermediate approach. Later, $dispatch will be passed to process()as well (which is why I use a hash reference instead of a hash). To help with processing the search menu. $book is reference to @book initally taken from a flat file. memoize immediately comes to mind, but too many beginners shun modules and I don't want to lose my audience.
I initially scrapped an idea of using a BEGIN block. Perhaps I could combine the two and grab the array reference in each subroutine as someone else mentioned. Though I find using the dispatch table as a source for the arguments that are passed more powerful.
BEGIN { open FH, 'my_db' or die "Cannot open my_db: $!"; my @book = split /,/, <FH>; sub address_book { return \@book } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Re: passing arguments in a dispatch table
by abstracts (Hermit) on Apr 29, 2002 at 03:12 UTC | |
by CharlesClarkson (Curate) on Apr 29, 2002 at 06:06 UTC |