Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: validateMask

by Petruchio (Vicar)
on May 13, 2001 at 07:33 UTC ( [id://79990]=note: print w/replies, xml ) Need Help??


in reply to validateMask

Consider the following program which calls your subroutine:

my $x = '255.0.0.0'; print "$x is a valid mask!\n" if validateMask($x); sub validateMask { return # return undef if it's not com +plete unless $_[0] =~/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; $_[0] = unpack ( "B32", pack( "C4", split ( /\./, $_[0] ) ) ); return # return undef if we find an i +nvalid if $_[0] =~ /01/; # mask ( a zero followed by a +one ) return 1; # return 1 if everything is ok +ay }

It returns the following:

11111111000000000000000000000000 is a valid mask!

Which isn't exactly what one might expect. Similarly, if I say

print "255.0.0.0 is a valid mask!\n" if validateMask('255.0.0.0');
I get the error:
Modification of a read-only value attempted at ./idnopheq.pl line 5.

The problem is, parameters to subroutines in Perl are passed by alias; which is to say, $_[0] is just another name for $x in the former program, and a string literal in the latter. For this reason, it's a good idea to assign the values of any members of @_ to other variables as soon as you begin your subroutine, unless you really want to modify the original.

For instance, ybiC says

my $mask = shift;

and then works with the variable $mask, which will cease to exist once he leaves validateMask. Another option is to use $_, which can make your statements more succinct (and, sometimes, harder to read).

sub validateMask { $_ = shift; return unless /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; unpack('B32', pack('C4', split /\./)) =~ /01/ ? undef : 1; }

Hope this helps.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://79990]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2024-04-16 09:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found