in reply to local variables and classes

1: sub numtoname { 2: local ($_) = @_; 3: unless (defined $numtoname{$_}) { 4: my (@a) = gethostbyaddr(pack('C4', split(/\./)),2); 5: $numtoname{$_} = @a > 0 ? $a[0] : $_; 6: } 7: return $numtoname{$_}; 8: }

Line two "localizes" the variable $_. Because $_ is a global variable, it's necessary to use local with this global variable to ensure that whatever value you currently assign the variable does not overwrite the previous value. For example:

foreach (1 .. 3) { foo($_ + 1); print "$_\n"; } + sub foo { $_ = shift; $_ += 7; }

That code prints 9, 10, and 11 (on successive lines) instead of the 1, 2, and 3 that some would expect. Changing the first line of &foo to local $_ = shift will prevent $_ from being overridden.

Line 3 says "unless we've already looked up this host, let's look it up and store it in our cache. Line 7 returns the host from the cache.

Incidentally, use of $_ is a shorthand. If it's confusing, you could write that function like this:

sub numtoname { my $address = shift; unless (defined $numtoname{$address}) { my (@a) = gethostbyaddr(pack('C4', split(/\./, $address)),2); $numtoname{$address} = @a > 0 ? $a[0] : $address; } return $numtoname{$address}; }

Cheers,
Ovid

New address of my CGI Course.