?

Log in

Previous Entry | Next Entry

Aug. 30th, 2005

The Perl way:
sub new {
    my Net::OpenID::Association $self = shift;
    $self = fields::new( $self ) unless ref $self;
    my %opts = @_;
    for my $f (qw( server secret handle expiry type )) {
        $self->{$f} = delete $opts{$f};
    }
    Carp::croak("unknown options: " . join(", ", keys %opts)) if %opts;
    return $self;
}


The PHP way:
  function OpenID_Association($opts) {
    if (!is_array($opts)) {
      die('Argument to OpenId_Association constructor must be an array');
    }

    foreach (array('server', 'secret', 'handle', 'expiry', 'type') as $f) {
      if (array_key_exists($f, $opts)) {
        $this->$f = $opts[$f];
        unset($opts[$f]);
      }
    }

    if (count($opts)) {
      die('unknown options ' . implode(', ', array_keys($opts)));
    }
  }

Comments

( 7 comments — Leave a comment )
matthew
Aug. 30th, 2005 07:05 pm (UTC)
yup, that php is a lot easier to read ;)
brocklisoup
Aug. 30th, 2005 08:02 pm (UTC)
I was kinda thinking that myself.
groundup
Aug. 31st, 2005 03:51 am (UTC)
PHP 1 : Perl 0
mart
Aug. 31st, 2005 05:53 pm (UTC)

To be honest, I don't really see what you're getting at with this one. ;)

daveman692
Aug. 31st, 2005 08:01 pm (UTC)
Just how it is so much longer to get to the same thing. I don't think PHP does this poorly, it just is more function calls versus being able to work on the variable itself. While using $_ isn't a great practice in longer loops, PHP doesn't even offer it to you as a choice.
mart
Sep. 1st, 2005 06:26 pm (UTC)

By that criteria Perl wouldn't have much trouble beating every other language in existence. It's the only one I know of that has an “it” variable ($_), an “unless” construct, postfix control structures or “common case” optimisations like the qw() array literals.

I can't see any places in your example where PHP uses a function where Perl had a language construct. You did use array_key_exists(), which is a function, but PHP also has the operator/thingy isset() which performs a similar (though not completely identical) task without function call overhead. The line between functions and operators is a bit blurry in Perl, though, I'll admit; both can be implemented by subroutines with some suitable teasing.

daveman692
Sep. 1st, 2005 06:37 pm (UTC)
The array_key_exists() call vs isset() comes out of worries of auto-vivication, although I don't think PHP handles that at all as they don't support the concept of undef.
( 7 comments — Leave a comment )