in reply to How not to use "our"?

Here's an example of how to "access a common variable but without resorting to globals":

use strict; use warnings; package A; { my $maxlengths = { tinytext => 100, longtext => 2000, }; sub max_tiny_text { return $maxlengths->{tinytext}; } sub max_long_text { return $maxlengths->{longtext}; } } package B; use base 'A'; print 'From B: ', A->max_tiny_text(), "\n"; print 'From B: ', A->max_long_text(), "\n"; package main; print 'From main: ', B->max_tiny_text(), "\n"; print 'From main: ', B->max_long_text(), "\n";

The output from this is:

From B: 100 From B: 2000 From main: 100 From main: 2000

Here's a quick rundown of what I've done here and why.

I've aimed to keep the same general framework you presented. There are (as usual) more ways to do it. :-)

-- Ken

Replies are listed 'Best First'.
Re^2: How not to use "our"?
by JavaFan (Canon) on Nov 29, 2010 at 21:32 UTC
    Just because the names max_tiny_text and max_long_text take the CODE slot of the typeglob instead of the SCALAR slot doesn't make them any less global.
    I've removed Exporter. Take a look at the Selecting What To Export section in that documentation.
    And instead you write package name, and sub name to get a value. If you're willing to do that, you can do that with scalars as well, and not need Exporter:
    package Max; our $tiny_text = 200; our $long_text = 1000; package main; print "From main: $Max::tiny_text\n"; print "From main: $Max::long_text\n";
    You can even interpolate that way.
Re^2: How not to use "our"?
by Anonymous Monk on Nov 29, 2010 at 16:42 UTC

    Thanks, kcott!

    Wished I had read it in greater detail each time I went to that page, because I missed out that part entirely.

    But I'm a little puzzled.

    Under "Selecting What To Export", the first rule is "Do not export method names!" Why is that so? I thought one of the niceties about modules is that you can put functions in them so that they (the functions) can be reused? And how does one reuse the functions if they aren't exported. Hm...scratches head.

    Thanks to all who have commented, particularly wazoox with the working code!

      Very briefly, methods are functions used in object oriented code (there's OO tutorials in perldoc is you're not familiar with this). Access to methods should be through inheritance - exporting method names will likely break inheritance.

      If you read a bit further down that section you'll see it makes a distinction between modules that are object oriented and those that are just a collection of functions. As an example of the latter type, Scalar::Util is a collection of functions which you can selectively choose to export.

      -- Ken