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.
|