in reply to Multiple Package in one file with equal named variables

Though I think it's better to put each package into its own lexical scope, as long as each package defines a new lexical @values, what you've written will work. Each newly-declared one will mask the previous one, but each function will refer to the proper incarnation.

You'll get warnings about "masks earlier declaration", but you intend to do that.

Example code:

use strict; use warnings; package three; my @values = qw(three three three); sub show_values { print "@values\n"; } package two; my @values = qw(two two two); sub show_values { print "@values\n"; } package one; my @values = qw(one one one); sub show_values { print "@values\n"; } package main; three::show_values; two::show_values; one::show_values;

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Multiple Package in one file with equal named variables
by Brutha (Friar) on Jan 30, 2006 at 07:41 UTC
    You'll get warnings about "masks earlier declaration", but you intend to do that.
    Yes, I do. But I do not like the warnings, as they possibly hide the important ones and you can't find the forest amongst the trees.

    And it came to pass that in time the Great God Om spake unto Brutha, the Chosen One: "Psst!"
    (Terry Pratchett, Small Gods)

      The usual way of dealing with warnings for things that you intend to do is to turn off warnings around the offending statement. Often that's done for a lexical scope, but since you don't want to introduce multiple lexical scopes, you'd do:
      no warnings 'misc'; my @values = (...); use warnings 'misc';
      At this point, you're probably at the point that wrapping each package in its own lexical scope looks like the Right Thing To Do. It is.

      For reference, perldoc perllexwarn shows the various categories of warnings you can turn on and off, and perldoc perldiag lists some of the warning messages and which category they fall into. (I found it odd that the "masks earlier declaration" didn't fall under the "redefine" category, and instead was thrown into "misc".)


      Caution: Contents may have been coded under pressure.