Rob Dixon wrote:
> Lance wrote:
> > Is there a way to access the 'foreach' variable from a subprocedure
> > called from inside the loop whose variable you want to access?
> > Hooboy, even I don't understand that question! ;-) An example is
> > neccessary, I believe:
> >
> > foreach my $store( values %$server ){
> > if( $$store{errorPageCount} >=1 ){
> > ## loop through each page to check in each store
> > foreach my $page( values %$store ){
> > $$server{emailMessage} .= "$$page{error}";
> > } }
> > if( $$store{badMailSent} ne 'sent' ){
> > mailIt( $$store{emailMessage}, "$$store{name} is
> > non-responsive", 'bad', $$store{email});
> > }
> > }
> >
> > Now, from within my mailIt sub, can I access $$store or $$server? I
> > get the error message: "Global symbol "$store" requires explicit
> > package name at D:\My
> Stuff\lance\perl\store_monitor\store_monitor.pl
> > line 603."
> >
> > inside of mailIt, I am trying to access a variable in %server using:
> > $$server{errorPageCount}++;
>
> A lexical (my) variable is accessible from the point it is declared
> to the end of the innermost containing block or file (including all
> nested blocks). In general, then, a subroutine won't be able to see a
> lexical unless the it is declared after the lexical value within the
> same block.
>
> A lexical used as a control variable for a loop is in scope only to
> the closing brace of the loop's code block.
>
> To access a variable from a subroutine, either declare the variable
> at a scope outside the subroutine or pass it as a parameter.
>
> Don't use global package (our) variables. They're hardly ever
> necessary.
But foreach loops are funny. Try this:
use strict;
our $x = "Hello";
printx();
for $x (1..3) {
print "$x\n";
printx();
}
printx();
sub printx { print "$x\n"; }
prints:
Hello
Hello
Hello
Hello
Hello
Hmm, now try it with "our":
use strict;
our $x = "Hello";
printx();
for $x (1..3) {
printx();
}
printx();
sub printx { print "$x\n"; }
prints:
Hello
1
2
3
Hello
The loop variable can either be a global (default) or a lexical scoped to
the loop. It can't reuse a lexical in an outer scope. Also, when a global is
used, it is localized to the loop.
So, the OP's problem can be addressed by:
1. Using the global variable.
2. Passing the variable to the function.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]