davorg has asked for the wisdom of the Perl Monks concerning the following question:

Here are the guts of a module that I'm working on called Globwalker.pm. It's supposed to give you a list of objects of a given type in a given typeglob (e.g. for example all subs in main::). It seem to work OK for most glob types, but I'm getting strange results for scalars. I assume this is because the scalar knob is defined as soon as the typeglob comes into existance.

Does anyone have any idea how I can work out if the scalar has really been used?

package Globwalker; use strict; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK); require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw(get_things get_subs get_scalars get_arrays get_hashes get_filehandles); $VERSION = '0.01'; sub get_things { my $thing = shift; my $pkg = shift || caller; my @things; no strict 'refs'; # WARNING: Deep magic here! while (my ($sym_name, $sym_glob) = each %{"${pkg}::"}) { push @things, $sym_name if defined *$sym_glob{$thing}; } @things; } sub get_subs { get_things('CODE', shift || caller) }; sub get_scalars { get_things('SCALAR', shift || caller) }; sub get_arrays { get_things('ARRAY', shift || caller) }; sub get_hashes { get_things('HASH', shift || caller) }; sub get_filehandles { get_things('IO', shift || caller) }; 1;
--
<http://www.dave.org.uk>

"Perl makes the fun jobs fun
and the boring jobs bearable" - me

Replies are listed 'Best First'.
Re: Finding out if a scalar exists in a typeglob
by merlyn (Sage) on Oct 23, 2000 at 20:18 UTC
    A glob automatically comes with a scalar as an optimization, so the answer for all current Perl versions is automatically "yes".

    -- Randal L. Schwartz, Perl hacker

Re: Finding out if a scalar exists in a typeglob
by chromatic (Archbishop) on Oct 23, 2000 at 20:19 UTC
    You can get at them if the underlying scalars are defined:
    while (my ($sym_name, $sym_glob) = each %{"${pkg}::"}) { push(@things, $sym_name) if (defined ${ *$sym_glob{SCALAR} }) ; }
    Unfortunately, if they've been declared but never initialized, I can't seem to get at them in five minutes of trying. The trick you came up with for coderefs doesn't do the job here.

      Thanks for trying.

      Like merlyn says, it's a space optimisation. As a scalar takes as much room as a reference to it would, each typeglob comes with a free scalar. Which is good most of the time, but a little frustrating here :(

      Your fix will, at least, get me a bit closer and will presumably remove things like STDOUT from the list.

      --
      <http://www.dave.org.uk>

      "Perl makes the fun jobs fun
      and the boring jobs bearable" - me