[MUD-Dev] Flexible Perl MUD-like Server Project

Joshua Judson Rosen rozzin at geekspace.com
Wed Sep 25 12:10:33 CEST 2002


On Tue, Sep 24, 2002 at 05:56:37PM -0700, stanza wrote:
 
> I looked more towards Python for my MUD bases when I realized that
> Perl doesn't support static local variables (in C I use "static
> int") but I'm much more fluent in Perl.  Does this crimp your
> coding style as much as it does mine?

This isn't exactly true, because Perl does have lexical closures
(which Python finally got in 2.2, and in 2.1 via the __future__
module, actually--though you're probably referring to using Python's
OO features, keeping state on instances and using instance-methods
rather than closed functions).

Using closures generally doesn't look the same as using C's static
locals, but can give you the same effect (it's really more generic
and flexible).

Where, in C, you would do:

    int next ()
    {
      static int x=0;
      return x++;
    }

    int main ()
    {
      printf ("%d", next());
      printf ("%d", next());
      printf ("%d", next());
      return 0;
    }

... you could do the following, in Perl:

    $next = sub {my $x = 0; return sub { return $x++; }}->();
    print $next->();
    print $next->();
    print $next->();

... or you could store the outer anonymous subroutine above and call
it whenever you want a new counter-function; you could even write it
to take parameters that influence what kind of counter-function it
produces (e.g.: initial value and step-size)--try that in C ;)

e.g.:

    sub new_counter
    {
      my $x = shift;
      my $step = shift;
      $x -= $step;
      return sub { return $x+=$step; };
    }

    $count_up = new_counter (0, 1);
    $count_down =  new_counter (9, -1);

    print $count_up->();
    print $count_up->();
    print $count_down->();
    print $count_down->();


You could also move the closure outward so that it was shared by all
of the produced functions, so they'd all use the same counter.

_______________________________________________
MUD-Dev mailing list
MUD-Dev at kanga.nu
https://www.kanga.nu/lists/listinfo/mud-dev



More information about the mud-dev-archive mailing list