in reply to Whether to use local()

"...why would you go to the trouble of using local if you aren't trying to keep some private value ... somewhere?"

Personally, i wouldn't. But the caveat depends on what kind of program you are writing.

When i write utility scripts, avoiding global variables is usually a waste of typing to me - i use them. Keep in mind that i do have a CS degree and my professors would never allow us to use globals ever anywhere! I appreciated that, but now that i understand the rules, i can break them. >:)

Let's say that i am writing a larger program. Then i would strongly consider OO. OO is good for eliminating globals, because you instead have accessor methods (considering, of course, that it is good OO).

Finally, local vs. my - in my limited experience with local, i only use it to erase Perl's built-in variables, like $/ for slurp mode (thanks again tye!):

my $slurp = do {local $/; <FH>};
All of my variables are declared with my. To be honest, i am still missing the picture of when you need our.

Hope this helps :)

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: (jeffa) Re: Whether to use local()
by tachyon (Chancellor) on Mar 15, 2002 at 19:25 UTC

    Does this snippet explain our for you jeffa ?

    # comment use strict in and out # use strict; package Foo; our $global = 'global '; $not_so_global = 'not so global'; package Bar; print "Full package name: ", $Foo::global, $Foo::not_so_global, "\n"; print "No package name: ", $global, $not_so_global, "\n";

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      Ahhhh, i am starting to see now:
      • my declares a local variable which is not found in a package's symbol table
      • a local var does show up in the symbol table, but if you use strict, then you have to fully qualify the variable name (that is, prefix the package name)
      • our handles the strict vs. non-fully qualified local vars
      perrin pointed me to CPAN and the Devel::Symdump module. Here is another snippet to help explain:
      #!/usr/bin/perl #use strict; use Devel::Symdump; my $obj = Devel::Symdump->new('Foo'); print map {"$_\n"} $obj->scalars; package Foo; local $Foo::qualified; local $unqualified; our $our; my $my;
      Which (without use strict) produces this ouput :
      Foo::qualified
      Foo::our
      Foo::unqualified 
      
      If strict is turned on, then $unqualified will cause a compliation error. I think i get it now! :)

      Thank you tachyon, perrin, and also rob_au for pointing out What is it adding to my symbol table?.

      jeffa

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      B--B--B--B--B--B--B--B--
      H---H---H---H---H---H---
      (the triplet paradiddle with high-hat)