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.


In reply to Re: local variables and classes by Ovid
in thread local variables and classes by jfroebe

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.