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).