No, that's not quite right.
In the first example, change increment() to return $data instead of undef, and then you can call error() without getting an uninitialized value error.
In the second example, simply give $data a default value, call error() before your while block, and you'll see that it prints.
Here's the code I used for an example:
#!/usr/bin/perl -w
use strict;
my $data;
my $ERROR = 0;
# error(); # uncomment this to print $data before the loop
while ( (defined $data++) && everything_is_okay() ) {
print "looping for the $data time.\n";
if ( $data > 5 ) {
$ERROR++;
error(); # print $data if there's an error
}
}
sub everything_is_okay {
if ( $ERROR ) {
print STDERR "ERROR LEVEL $ERROR\n";
exit $ERROR;
}
return 1;
}
sub error {
print $data;
}
I put the defined check in there so the loop will get past the first iteration. $data++ (when $data is not initialized) evaluates to zero:
my $data;
print $data++;
| [reply] [d/l] [select] |
Overall, nice discussion. To comment on one point you raised,
though... you wrote:
sub error {
print $data; # oops, doesn't work!
}
Well, it *does* work. If you try it, you'll see that it works just
fine, because it's a lexical variable... lexical to the scope of the
file. And the error sub is defined in the file, so $data
is visible there.
That's not to say that it's recommended, of course, because it
can definitely cause you problems. Particularly when using
mod_perl. You'll get the dreaded "variable may not stay shared"
message, because essentially you've defined a closure.
That said, though, good points.
| [reply] [d/l] |
As it turns out, almost all my code has to run under mod_perl...
| [reply] |