Your problem is that, actually you assigned values to other variables with the same name, but in a different scope. Those variables you my'd in the foreach loop, are not the variables you declared in your format statement.
This is the answer to your question, but I want to elaborate on this a little bit:
- Even within the same scope, you should not re-declare your variables. In the following code, $a is declared twice, first within the format statement, second time with my. Although $a is assigned to 1, don't expect the printing matches it, as that's a different $a. Remove the 'my' resolves the problem, as now it is a pure assignment, not a declaration any more.
format SomeFormat =
@###.## @>>>>>>>
$a, $b
.
my $a = 1;
- Although scope migth cause a problem, if one is careless, but I disagree with the thought that the write and format statement have to be in the same scope. Actually, as long as you fully qualify your variables, as you should always do, things would be fine, even if format and write reside in different scopes. The following code I wrote demos this:
use strict;
format Something =
Test: @##.## @###.##
$a, $b
.
sayit();
sub sayit {
$main::a = 1;
$main::b = 2;
$~ = 'Something';
write;
}