[aklug] Re: perl doesn't natively do booleans?????

From: Michael Fowler <michael@shoebox.net>
Date: Wed Aug 18 2010 - 01:23:41 AKDT

On Tue, Aug 17, 2010 at 03:15:11PM -1000, Lee wrote:
> #!/usr/bin/perl
>
> use strict;
> use warnings;
>
> <snip>
> if (isValidIP($ip)) {
> push (@temphosts,"$ip\t$name");
> }
> <snip>
>
> sub isValidIP($) {

Please, stop doing this. That ($) is a Perl prototype; prototypes in
Perl are not like any other language. They are intended for use in
changing how your subroutine call is -parsed-; they are not intended for
use as validation.

For example:

    sub foo ($) { print "@_\n" }
    my @x = qw( a b c );
    foo(@x);

This code prints 3.

Basically, never use prototypes. I can dig up links to describe in
detail what they're really for, but their uses are very specialized.

> my $isValid = false;
>
> if ($string =~ /(\d+)(\.\d+){3}/) { $isValid=true; }
> else { $isValid=false; };

This would be the simplest replacement for your subroutine:

    sub is_valid_id { $_[0] =~ /(\d+)(\.\d+){3}/ }

Although this does not actually validate an IP address, even with the
anchoring Arthur suggested. 355.299.789.999 would be treated as a valid
IP address. Presumably further code verifies the octets somehow, but
this can be accomplished with a single regex.

There's a regex in Regexp::Common for matching a valid IP address.
Cleaned up it looks like:

    my $octet = qr/(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})/;
    my $ipaddr = qr/^ (?:$octet\.){3} $octet $/x;

Where $ipaddr is your regex. The original regex from Regexp::Common is
$RE{net}{IPv4}.

Given you aren't actually looking for this in text, then using
inet_aton() or inet_pton() to validate your IP address would also be a
good idea. There are many things that can be treated as a valid IP
address that are not simply a dotted quad.

> But I'm still having a problem with true and false not being native
> keywords.

It would be nice if Perl had a true and false, if only for
self-documenting purposes. Too often a 0 or 1 is returned from a
function, and it's not clear from the code if the intent is a number, or
a boolean.

--
Michael Fowler
www.shoebox.net
---------
To unsubscribe, send email to <aklug-request@aklug.org>
with 'unsubscribe' in the message body.
Received on Wed Aug 18 01:25:44 2010

This archive was generated by hypermail 2.1.8 : Wed Aug 18 2010 - 01:25:44 AKDT