in reply to RE: Hard Lessons
in thread Hard Lessons

i'm not so sure about this. my will initialize a variable to undef (lexical scoping), but i don't think that using local on a variable does anything but introduce dynamic scoping of the variable for the enclosing block and contained subroutine calls. it is not (re-)initialized, as it would be for my.

update: so, as turnstep proves in his response, i am incorrect. damn.

Replies are listed 'Best First'.
RE: RE: RE: Hard Lessons
by turnstep (Parson) on Jun 10, 2000 at 18:43 UTC
    Well, it does work, as local not only squirrels away the old global value, but sets it to undef for the loop. However, upon writing some example code, I noticed a strange difference between two global variables, $/ and $^T. Both mean something, and always have values (and are thus defined) at the start of a script. However, $/ gets set to undef when used with a local, while $^T gets set to "0". [Luckily, $/ does not get set to 0, or my examples would not work. :)] Anyone know why $^T acts like that? Here's the code, and the results. This is perl 5.005_03, FWIW.

    $MY = 1; $LOC = 1; { local $LOC; local $LOC2; local $/; local $^T; my $MY; my $MY2; printf "LOC defined: %s\n", defined $LOC ? "YES" : "NO"; printf "LOC2 defined: %s\n", defined $LOC2 ? "YES" : "NO"; printf "IRS defined: %s\n", defined $/ ? "YES" : "NO"; printf "TIME defined: %s\n", defined $^T ? "YES" : "NO"; printf "MY defined: %s\n", defined $MY ? "YES" : "NO"; printf "MY2 defined: %s\n", defined $MY2 ? "YES" : "NO"; print " LOC=$LOC, LOC2=$LOC2, TIME=$^T, IRS=$/, MY=$MY, MY2=$MY2\n" +; } print "AFTER LOOP:\n"; print " LOC=$LOC, LOC2=$LOC2, TIME=$^T, IRS=$/, MY=$MY, MY2=$MY2\n";

    Which produces:

    LOC defined: NO LOC2 defined: NO IRS defined: NO TIME defined: YES MY defined: NO MY2 defined: NO LOC=, LOC2=, TIME=0, IRS=, MY=, MY2= AFTER LOOP: LOC=1, LOC2=, TIME=960648360, IRS= , MY=1, MY2=
      Since $^T is the time in seconds since the script began, I would be surprised if *anything* ever automatically set it to undef. Zero seems like a pretty good default to me, so I'll just make the assumption that somewhere in perlguts, someone agreed with me.