tags:

views:

99

answers:

2

I want to access $hash_element->{'test_plan'} and $hash_element->{'build'} outside the for loop

my $hash_element;
for $hash_element (@bats) {
    my $dbh = DBI->connect( $dsn, $BAT_DB_user, $BAT_DB_password );
    my ( @plan_id, @plan_run );
    @plan_id = $dbh->selectrow_array(
               "select id from plan where name='$hash_element->{'test_plan'}'");
}

$emailsubject = "BAT - " . $hash_element->{'test_plan'} . " on " . $hash_element->{'build'} . " done.";
+8  A: 

First, please learn how to use placeholders and bind variables in SQL.

Second, what values do you expect "outside the loop"? You've gone through the entire list of @bats. What do you think would be in there after that's all done?

Randal Schwartz
+7  A: 

It depends on what exactly you want to do - there's no obvious value for a loop variable outside of its loop. Do you want to access the LAST element of @bats? FIRST element? Some element satisfying a particular condition?

For the last element, simply do:

my $hash_element_last;
for my $hash_element (@bats) {
    # whatever logic
    $hash_element_last = $hash_element;
}
my $emailsubject = "BAT - " . $hash_element_last->{'test_plan'};

For some other element, you also stash it inside of a separate value:

my $hash_element_remembered;
for my $hash_element (@bats) {
    # whatever logic
    # Use for the first element
    $hash_element_remembered = $hash_element unless defined $hash_element_remembered;
    # Use for the "special" element
    $hash_element_remembered = $hash_element if (some_special_logic)
}
my $emailsubject = "BAT - " . $hash_element_remembered->{'test_plan'};    

Please note that for first/last, your can of course simply use $bats[0] and $bats[-1] without specially remembering the loop element inside the loop (assuming you don't want "the last element seen in the loop which may exit via last prior to finishing looping).

DVK