?

Log in

Previous Entry | Next Entry

Don't Even Bother With Regular Expressions

Perl way:
sub usable {
    my Net::OpenID::Association $self = shift;
    return 0 unless $self->{'handle'} =~ /^[\x21-\x7e]{1,255}$/;
    return 0 unless $self->{'expiry'} =~ /^\d+$/;
    return 0 unless $self->{'secret'};
    return 0 if $self->expired;
    return 1;
}


PHP way:
  function usable() {
    if (! preg_match('/^[\x21-\x7e]{1,255}$/', $this->handle)) {
      return 0;
    }

    if (! preg_match('/^\d+$/', $this->expiry)) {
      return 0;
    }

    if (!isset($this->secret)) {
      return 0;
    }

    if ($this->expired()) {
      return 0;
    }

    return 1;
  }

Comments

( 2 comments — Leave a comment )
groundup
Aug. 31st, 2005 03:55 am (UTC)
I really don't see much difference except the number of characters ..

if (! preg_match('/^[\x21-\x7e]{1,255}$/', $this->handle) || preg_match('/^\d+$/', $this->expiry) || !isset($this->secret) || $this->expired())
return 0;

return 1;

That looks like it uses less than your Perl method. I will call this one a tie.

PHP 2 : Perl 1
mart
Aug. 31st, 2005 05:50 pm (UTC)

A less obvious difference is that Perl compiles the regexes during its own compile phase while PHP compiles the regex from that string when the function is called. In a PHP webapp there's little distinction between compile-time and runtime since you generally go through both with every request served, but Perl often runs in environments where a given section of code is compiled once but run many times, so having the regex compiled just once can make things faster.

Of course, Perl is pretty-much alone in having regex support as a core language feature. JavaScript too has some rudimentary core support for regexes, but other than that I don't know any other common languages which do. There's no reason at all why those regexes couldn't be replaced by function calls which implement the regex in pure PHP, but then you're left to wonder why they put the regex support in there in the first place. I generally consider the PCRE library to be more for applying user-supplied regexes (the first parameter to grep, for example) than developer-supplied regexes.

( 2 comments — Leave a comment )