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

How do i make it so there is multiple conditions for the while loop with an 'or' command or something. my while loop goes something like this
sub write1 { while ( @data=$STH1->fetchrow_array() ) { print "<CENTER>"; print "<TR>"; print "<TD BGCOLOR='red'>"; print "<P ALIGN='CENTER'>"; print "<FONT COLOR='white'>";
ect.. ect.. what i want it to do is to make @data = to $STH1 or $STH2 or $STH3 ect ect without creating a sub write for every table for each $STH. thanks for any help i greatly appreciate it!

Replies are listed 'Best First'.
Re: multiple conditions while loop
by kennethk (Abbot) on May 17, 2012 at 15:45 UTC
    It seems like the natural thing here is to pass your desired target handle as an argument to the subroutine rather than using a closure -- see perlsub for info on how to use subs in Perl. Your code might look like:
    sub write1 { my $STH = shift; while ( @data=$STH->fetchrow_array() ) { print "<CENTER>"; print "<TR>"; print "<TD BGCOLOR='red'>"; print "<P ALIGN='CENTER'>"; print "<FONT COLOR='white'>"; } }

    Alternatively, if you mean a closure that systematically goes over three previously defined statement handles, you can wrap your while loop in a foreach loop like:

    sub write1 { foreach my $STH ($STH1, $STH2, $STH3) { while ( @data=$STH->fetchrow_array() ) { print "<CENTER>"; print "<TR>"; print "<TD BGCOLOR='red'>"; print "<P ALIGN='CENTER'>"; print "<FONT COLOR='white'>"; } } }

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re: multiple conditions while loop
by locked_user sundialsvc4 (Abbot) on May 17, 2012 at 21:02 UTC

    It also occurs to me that you could provide an arrayref of statement-handles to your routine.   Iterate over the list of handles in an outer for loop, then include within it the while loop that you already have.

    This approach is painless:   the array merely contains a list of new references to what the existing statement-handle variables already refer to.

Re: multiple conditions while loop
by diddy_perl (Novice) on May 17, 2012 at 15:21 UTC

    I am not sure what you meant but from what I understood you could have one function that takes a parameter representing a table. So, something along the lines of

    sub write() { my $STH = shift; while( @data = $STH->fetchrow_array() ) { ## processing goes here } }

    And call that same function for each table.