DrWhy has asked for the wisdom of the Perl Monks concerning the following question:
Updated: Several typos and omissions fixed.
Here's a weird thing I don't understand. Can another more enlightened share his knowledge? I am working on a large set of scripts and have a 'Utilities' module for simple stuff that's used repeatedly across multiple packages. I wanted to put some sort routines in there, but got tripped up by the fact that the $a and $b used in sort routines are package globals, and these sort routines are used in packages different from the one they are defined in. So I thought, hey, simple answer: export $a and $b from 'Utilities' so the package globals are aliased. That didn't work. I checked and made sure that $a and $b in the Utilities package and the use-ing package were really aliases of e/o, and they were; I even printed out $a inside the sorting sub and the correct value was being printed.
What did turn out to work was exporting *a and *b. I don't understand why that worked and exporting $a/b didn't. Anybody got a clue as to why exporting $a/b doesn't work, but exporting the corresponding type globs does?
Here's some example code:
file1: main.pl
file 2: Sorts.pm#!/usr/bin/perl use lib '.'; use Sorts; $, = "\n"; print sort caseless ('a','s','d','f');
version 1 -- b0rken, a/b not exported:
version 2 -- still b0rken, $a/b exported:use Exporter; package Sorts; use base 'Exporter'; @Sorts::EXPORT = qw(caseless); sub caseless { lc $a cmp lc $b }
version 3 -- works!, *a/b exported:use Exporter; package Sorts; use base 'Exporter'; @Sorts::EXPORT = qw(caseless $a $b); sub caseless { lc $a cmp lc $b }
running main.pl with the first two versions of Sorts.pm produces:use Exporter; package Sorts; use base 'Exporter'; @Sorts::EXPORT = qw(caseless *a *b); sub caseless { lc $a cmp lc $b }
but with the third version outputs:a s d f
a d f s
"If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."
|
|---|