From: "Rob Dixon" <[EMAIL PROTECTED]> > Jenda Krynicky wrote: > > From: "Rob Dixon" <[EMAIL PROTECTED]> > >> "Jenda Krynicky" <[EMAIL PROTECTED]> wrote in message > >> 3E2E9EDB.5722.62EB5D@localhost">news:3E2E9EDB.5722.62EB5D@localhost... > >>> From: "Rob Dixon" <[EMAIL PROTECTED]> > >>>> There was an example in there that demonstrated > >>>> using 'our' to implement a C-like 'static' variable. > >>> > >>> Well ... if you mean something like > >>> > >>> int Inc() { > >>> static int cnt; > >>> return cnt++; > >>> } > >>> > >>> then our() is not the right way to do that in Perl. the our() only > >>> allows you to use the short name instead of $the::complete::one. > >> > >> It also protects your variable from modification by code which > >> hasn't declared it. > > > > #!perl > > use strict; > > > > sub Inc { > > our $inc; > > return $inc++; > > } > > > > print Inc(),"\n"; > > print Inc(),"\n"; > > $main::inc = 100; > > print Inc(),"\n"; > > __END__ > > > > I would not call this protection. > > I would. I would be surprised if this was coded accidentally! This is > a valid circumvention of the access limitations, which protect > programmers from themselves but still allow access in a special case.
Well ... the static variables in C are supposed to belong to the function. And if two functions declare static variables with the same they are not supposed to overwrite each other's data. Try: #!perl use strict; sub Inc1 { our $inc; return $inc++; } sub Inc2 { our $inc; return $inc++; } print Inc1(),"\n"; print Inc1(),"\n"; print Inc2(),"\n"; print Inc1(),"\n"; __END__ All our() does is that it allows you use the shorter name to access a GLOBAL variable. Sure Perl is based on the assumtion that programmers are adult people who know what they are doing, but why should they prepare ropes for themselves to hang on? > Non-exported module contents can also be accessed this way, but that > isn't considered a breach of security either. It's less likely that you will unintentionaly use a variable in someone elses package, than that you our() a global variable in your own package on two places without noticing it. I don't say you should not use our(). All I say is you should know exactly what it means and use each of sub { our $var; ... } sub { my $var; ... } { my $var; sub { ... } } where it belongs. Jenda ===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz ===== When it comes to wine, women and song, wizards are allowed to get drunk and croon as much as they like. -- Terry Pratchett in Sourcery -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]