in reply to variable sees it, array doesn't - stumped!

The cause of the problems is found, now let's look at some other things. Most often when you say "our $variable" you mean "my $variable".

"my $variable" means "please create a brand new variable with this name that's accessible only within this block". "our $variable" on the other hand means just "I'm going to use the global variable (OK, package variable, there are multiple namespaces for globals) with this name within this block. I know it's global, but I do not want to waste time typing out its whole name each time". "our $variable", doesn't create a new variable, it just silences use strict;.

Compare,

use strict; { my $x; $x = 1; print "\$x=$x\n"; } { my $x; $x +=1; print "\$x=$x\n"; } # and { our $y; $y = 1; print "\$y=$y\n"; } { our $y; $y +=1; print "\$y=$y\n"; } # and see the globals in the main namespace print "\$main::x=$main::x, \$main::y=$main::y\n";

Replies are listed 'Best First'.
Re^2: variable sees it, array doesn't - stumped!
by shrdlu (Novice) on Jan 01, 2009 at 15:11 UTC
    Yes, having declared everything globally just to get the sod to work (work around my ignorance, that is), the penny has just dropped about why/where/how one should use local variables.

    I have managed to get the script working, though am aware there are several things to be done to improve it, primarily in optimising email address validation, and in getting the form field values - oko1's and Jenda's words of wisdom, and indeed everyone else's, have given me much to meditate upon. Phrases like 'reinventing the loop' spring to mind, but it's useful practice for me.

    I'm loth to post acres of pre-competent code here, but if anyone needs a shudder, do feel free to have a look at the form code and/or the Perl code.

    I'm overwhelmed by the response from this forum, muchas gracias senors, mucho gusto. What started as an optimistic 2-hour hack of someone-else's code a week ago seems to be turning into an obsession.

    Cheers, Jim