10.6. Bringing Some Closure

Understanding how lexical variables work is worth the effort. Suppose you have advanced to the stage of understanding closures—give yourself a pat on the back—and you decide to code a few subroutines that use a private variable that way:

   {
   my $protocol = "ftp";  # default

   sub get_proto
      {
      return $protocol;
      }
   sub set_proto
      {
      $protocol = shift;
      }
   }  # End of block containing closures

print get_proto();

(We've removed anything not necessary to understanding this point.) If you run this, you'll see that it indeed knows what the default protocol is, and you've successfully isolated that shared variable to the two subroutines that use it.

Let's say that later you decide that the subroutines are better off declared at the ...

Get Perl Debugged now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.