in reply to Perl/MySQL - calling sub from name in dbase
Somehow it just feels safer to me, knowning that I'll only attempt a subroutine call when I know the sub is really there.# define a hash of sub refs, keyed by sub name my %dbsub = ( foo => \&foo, bar => \&bar, baz => \&baz, ); # now run your query, and then: while ( my @db = $result->fetchrow ) { $LHC_OPTIONS .= ( exists( $dbsub{$db[2]} )) ? $dbsub{$db[2]}->() : join(':', @db[0,1]).'<BR>'; }
Update: on second thought, I would actually prefer the while loop to do something like this:
The point being, I'd like to know when the database contains something unexpected in the "sub" field. (Of course, since you seem to be running this as a CGI script, you'll either want to make a habit of scanning the web server's error log, or else you'll want this warning to show up some place where you'll be sure to see it.)while ( my @db = $result->fetchrow ) { if ( exists( $dbsub{$db[2]} )) { $LHC_OPTIONS .= $dbsub{$db[2]}->(); } else { warn "Unknown sub name in DB: $db[2]\n" if ( $db[2] ); $LHC_OPTIONS .= join(':', @db[0,1]).'<BR>'; } }
|
|---|