Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • I'm confused.

    What does it mean to change package within a sub?
    • by drhyde (1683) on 2004.10.19 3:55 (#35313) Homepage Journal
      Quite simply, it means that when you enter the sub you're in one package, and then at some point during the sub the current package changes. I recently did something like that, and it was also because of some refactoring.

      I have a bunch of classes, all subclasses of a single class, and all pretty similar. I broke a ton of code out into a "helper" module which they all use. However, part of that is to call a method in the class's superclass, like this:

      package Foo;
      @ISA(qw(Bar));

      use HelperMethods;

      sub blah {
      # massage data
      return HelperMethods::blah(...);
      }

      ########

      package HelperMethods;

      sub blah {
      ...
      $class->SUPER::blah(...) # call calling class's superclass's blah()
      }

      Trouble is, although in HelperMethods::blah() the $class variable is correctly set to Foo (indicating that this was called from Foo::blah), but it doesn't work. This is because SUPER is evaluated in the context of the current package (HelperMethods) and not really in the context of $class.

      The solution was:

      eval "
      package $class;
      \$class->SUPER::blah(...);
      ";

      The extra step of the eval is needed because packge $class is illegal - package names must be constant.