Dynamically Creating Variables

T

Tom

Hello,

I have a chunk of code that executes six statement handles from the
DBI module as follows:

$sth1->execute;
$sth2->execute;
$sth3->execute;
$sth4->execute;
$sth5->execute;
$sth6->execute;

The code runs fine but is it possible to run that through a loop using
Perl? I.e. something like:

for( my $i = 1; $i < 7; $i++ ) {
$sth${i}->execute;
}

The above doesn't work, was just my attempt. I've done quite a bit of
this type of looping via shell but am not sure of the correct syntax
for Perl.

Thanks for any help.
Tom
 
T

Tore Aursand

[...] is it possible to run that through a loop using Perl? I.e.
something like:

for( my $i = 1; $i < 7; $i++ ) {
$sth${i}->execute;
}

You don't want to do that. Quote from 'perldoc';

"Beginners often think they want to have a variable contain
the name of a variable.
[...]
This works sometimes, but it is a very bad idea for two
reasons."

Read through 'perldoc -q variable' for more information about this
specific topic.


--
Tore Aursand <[email protected]>

"Whenever I see an old lady slip and fall on a wet sidewalk, my first
instinct is to laugh. But then I think, what if I was an ant, and she
fell on me. Then it wouldn't seem quite so funny." -- Jack Handey
 
U

Uri Guttman

T> for( my $i = 1; $i < 7; $i++ ) {
T> $sth${i}->execute;
T> }

use an array. you're falling under the evil spell of symrefs and you
don't want to go there.

uri
 
T

Tad McClellan

Tom said:
I have a chunk of code that executes six statement handles from the
DBI module as follows:

$sth1->execute;
$sth2->execute;
$sth3->execute;
$sth4->execute;
$sth5->execute;
$sth6->execute;

The code runs fine but is it possible to run that through a loop using
Perl?


(untested)

foreach my $sth ( $sth1, $sth2, $sth3, $sth4, $sth5, $sth6 ) {
$sth->execute;
}

or

$_->execute for $sth1, $sth2, $sth3, $sth4, $sth5, $sth6;


I thought you were going to ask something about dynamically
creating variables.

Did you leave the question corresponding to your Subject out of your
article by mistake or something?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,137
Messages
2,570,795
Members
47,342
Latest member
eixataze

Latest Threads

Top