http://www.perlmonks.org?node_id=973825

johnpat123 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to create a sub procedure which will connect to an oracle db and select some data. The issue is that the data it retrieves is different each time. Meaning the sql string changing based on the parameters passed into this procedure. so the following commented out 'while' line works, but it is hard coded. Is there a way to put a variavle in fetch whch can contain different variables each time?

$xxx = "$DBNAME,$USERNAME,$PROFILE";

#while (my ( $DBNAME,$USERNAME,$PROFILE )=$sth->fetchrow())

while (my ( '$xxx' )=$sth->fetchrow())

{

....

thanks!

Replies are listed 'Best First'.
Re: oracle connection
by Eliya (Vicar) on Jun 01, 2012 at 18:00 UTC

    You could put them in a hash. For example, pass the names to the routine (e.g. proc( [qw(foo bar)] )), and then say in the routine

    my $names = shift; ... @v{@$names} = $sth->fetchrow()

    (The @v{...} is a hash slice, which means you can assign multiple entries in one go.)

    You can then access the "variables" as $v{foo} and $v{bar}.

      You can also directly ask DBI to return you a hash:

      my $hash = $sth->fetchrow_hashref();

        Sure you can (presuming the query produces the desired column names).

        I was mainly trying to answer the general case, i.e. the typical "beginner's" problem of wanting to dynamically create variables like

        $xxx = "$DBNAME,$USERNAME,$PROFILE"; my ( '$xxx' ) = ( ... );