In article <(E-Mail Removed)>,

Tad J McClellan <(E-Mail Removed)> wrote:

>Tim McDaniel <(E-Mail Removed)> wrote:

>

>> I don't know how to "my" a variable across a BEGIN

>> block boundary.

>

>You can have a file-scoped lexical declared before the BEGIN block:

>

> my($sum, $count);

> BEGIN { $sum = 0; $count = 0; }

>

>Note this excerpt from "Private Variables via my()" in perlsub.pod:

>

> A C<my> has both a compile-time and a run-time effect. At compile

> time, the compiler takes notice of it. The principal usefulness

> of this is to quiet C<use strict 'vars'>
But it interacts non-intuitively with "perl -n". My test program,

transmogrified:

#! /usr/bin/perl -wan

use strict;

my ($sum, $count);

BEGIN { $sum = 0; my $count = 0; }

$sum += $F[1] * 100; ++$count; print "After $count lines, sum is $sum\n";

END { print "The average of column 2 is this percent: $sum/$count=", ($sum / $count), "\n"; }

Data:

chase .0225

citi .0110

uhcu .03

Output:

After 1 lines, sum is 2.25

After 1 lines, sum is 1.1

After 1 lines, sum is 3

The average of column 2 is this percent: 2.25/1=2.25

$count staying 1 on each iteration is easy to see. As "man perlrun"

says, the program is effectively

LINE:

while (<>) {

use strict;

my ($sum, $count);

BEGIN { $sum = 0; my $count = 0; }

$sum += $F[1] * 100; ++$count; print "After $count lines, sum is $sum\n";

END { print "The average of column 2 is this percent: $sum/$count=", ($sum / $count), "\n"; }

}

that is, $sum and $count are redeclared and zorched on every loop

iteration.

But I don't know why $sum keeps its value from the FIRST iteration

.... maybe $sum being used in BEGIN somehow squirrels away a reference

to that iteration's value of $sum, and that's somehow what END sees,

instead of the last iteration's value of $sum, or $::sum, or sum such?

--

Tim McDaniel,

(E-Mail Removed)