"Leon" <[EMAIL PROTECTED]> writes:
[...]
> (1) how to make a variable within loops non-lexical as in this eg:-
> while (<FILE>){
> my $count++; # how to globalised this variable?
$count++; # NO "my", therefore implicitly global.
> };
>
> (2) how to make a variable available to all parts of this while loop
> ONLY.... eg:-
> use strict;
> while (<FILE>){
^ $count scope starts here
> my $count++;
> if (1){
> #what must I do to return $count here.
you probably don't mean "return", but merely "access"
> $count_available_here_also = $count;
This is it!!! You did it. It's accessable here.
$count is lexically scoped to the enclosing braces, and all
subordinate scopes.
V $count scope ends here
> };
> };
> #I do not wish to return $count here..
Add a set of braces. See example below
> $but_not_here = $count;
print "not accessable\n" unless defined $loop_count;
{
my $loop_count;
print "not accessable\n" unless defined $loop_count;
while (<FILE>) {
$loop_count++;
print "$loop_count\n";
if (localtime % 2) {
print "$loop_count at 'random' times\n";
}
}
print "Loop exited having exicuted $loop_count times.\n";
}
print "not accessable\n" unless defined $loop_count;
It does what you'd expect. The "my" variable isn't
accessable before or after the loop. (Actually, *another*
one *is*. There are actually two $loop_count variables.
One that we use inside the braces, and only in the braces.
The other one (that we really don't use) is at a higher
scope. Even though it's spelled the same, it's a different
variable.
Here's a good little example. It remembers the scalar
between invocations, but doesn't allow it to be accessable
outside the blocck that encloses the subroutine.
{
my $serial_num = 100_000;
sub serial_num {
return $serial_num;
}
}
foreach (20..30) {
printf "Next up: %d\n", serial_num();
}
--
Michael R. Wolf
All mammals learn by playing!
[EMAIL PROTECTED]
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]