Joe Gottman wrote:
> 
>    I just read Exegesis 4, and I have a few questions about private
> variables.  First, is it possible to have 2 private variables of the same
> name in different functions?

No. At least, not in different functions belonging to the same
namespace (i.e. module, class, or package)


> For instance, what would happen in the
> following code?
> 
> sub func1() {
>     our $varname is private \\= 1;
>     return $varname;
> }
> 
> sub func2() {
>     our $varname is private \\= 2;

Fatal error: "Private variable $varname declared in two distinct scopes".



> Second, in the above code, the "\\=" operator is used to initialize the
> private variable.  This allows it to be initialized the first time the
> function is called, but prevents it from being reinitialized subsequent
> times as long as the variable never becomes undefined.  But what if the
> variable can become undefined?  In that case, the next time you call the
> function the variable will be reinitialized, whether you want it to or not.

In which case, use an external declaration:

    {
      our $varname is private = 1;
          sub func1() {
         return $varname;
      }
    }

or just:

    {
      my $varname = 1;
          sub func1() {
         return $varname;
      }
    }

        
> 
>    Both of these show that "private" variables in Perl6 do not quite replace
> C or C++ static variables.  It would be nice if there was some way to do
> something like this:
> 
> my $foo is static = 3;

See above.


> so that $foo acts like a C++ static variable, i.e. its value always persists
> between calls to the function containing it, and the initialization code is
> performed only once.  Unfortunately, I have no idea how  this would be
> implemented in Perl 6.

Probably like this:

      sub func1() {
         my $varname is static = 1;
         return $varname;
      }

:-)

But I'm still to convince Larry of the rightness of providing that
extra Way To Do It.

Damian

Reply via email to