You are not logged in. Login Now
 0          
 
Author Message
herasleftnut
Incoherent rant on Perl Mark Unseen   Nov 1 02:15 UTC 2006

Okay, so like I needed to be amused on closures in Perl. Doing a google on
in yielded some articles that gave some really fucking lame examples of
closures.

Leading the crew in the lame, the damned, and the braindead was the following
URL:

http://www.perl.com/pub/a/2002/05/29/closure.html

The following example from the site made me go "Wow, that was really
brilliant". Not

 sub make_counter {
        my $start = shift;
        return sub { $start++ }
    }

    my $from_ten = make_counter(10);
    my $from_three = make_counter(3);

    print $from_ten->();       # 10
    print $from_ten->();       # 11
    print $from_three->();     # 3
    print $from_ten->();       # 12
    print $from_three->();     # 4

This example was about as exciting as having my mom walk in when my gf was
giving me a blow job (back in high school).

Okay, let's fastforward a bit. I was recently in awe in how many ways I could
get screwed over using OOP. The following gives a demonstration

#!/usr/bin/perl -w

package Person;

#Please note that new() and name() are taken from perltoot.

sub new {
    my $self = {};
    $self->{NAME} = undef;
    $self->{AGE} = undef;
    $self->{PEERS} = [];
    bless($self);
    return $self;
}

sub name {
    my $self = shift;
    if (@_) { $self->{NAME} = shift }
    return $self->{NAME};
}


package main;

$him = Person->new();
$him->{NAME} = "Chad";

print "The name is: ", $him->name , "\n";

That's right, in one line, I can access the private memebers of this class.
Somewhere buried deep in the perl docs, there was an example to get around
this kind of crap.

#!/usr/bin/perl -w

package Person;

sub new {
    my $that = shift;

    my $class = ref($that) || $that;
    my $self = {
        NAME => undef,
        AGE => undef,
        PEERS => []
        };

    my $closure = sub {
        my $field = shift;
        if (@_) { $self->{$field} = shift }
        return $self->{$field};
    };

    bless($closure, $class);
    return $closure;
}

sub name   { &{ $_[0] }("NAME",  @_[ 1 .. $#_ ] ) }

1;

package main;

$him = Person->new();
$him->name("Jason");

print  $him->name, "\n";

I was like wow, why didn't any of the fucking closure tutorials give this
kind of example. Then I was like wow, why didn't any of OOP Perl tutorials
give this kind of example. Yes, this might be a bit harder to understand, but
at least you're not writing classes where you can go screw yourself later on.

0 responses total.
 0          
Response Not Possible: You are Not Logged In
 

- Backtalk version 1.3.30 - Copyright 1996-2006, Jan Wolter and Steve Weiss