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

Can anyone tell me why the following prints out both SCALAR and CODE? What am I missing?

#!/usr/bin/perl -l use strict; use warnings; { package Foo; sub bar {}; } foreach my $type ( qw<SCALAR ARRAY HASH CODE IO FORMAT> ) { print $type if defined *Foo::bar{$type}; }

I only want that to print CODE. How do I fix it?

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re: Misbehaving typeglob
by Errto (Vicar) on Oct 27, 2006 at 16:35 UTC
    The behavior is documented in perlref:
    *foo{THING} returns undef if that particular THING hasn't been used yet, except in the case of scalars. *foo{SCALAR} returns a reference to an anonymous scalar if $foo hasn't been used yet. This might change in a future release.
    Given that I'm not certain what can really be done about it.
Re: Misbehaving typeglob
by grep (Monsignor) on Oct 27, 2006 at 17:01 UTC
    It's not pretty, but here's my workaround.
    { no strict qw/refs vars/; local $varname = 'bar'; local $fullname = "Foo::$varname"; foreach my $type ( qw<SCALAR ARRAY HASH CODE IO FORMAT> ) { print $type if (defined *{$fullname}{$type} and !($type eq 'SC +ALAR' and !defined($$fullname)) ); } }


    grep
    One dead unjugged rabbit fish later
Re: Misbehaving typeglob
by stvn (Monsignor) on Oct 27, 2006 at 20:43 UTC

    I ran into this same problem in Class::MOP (more specifically Class::MOP::Package). IIRC the value it creates is always a reference to undef, so I just deal with it as a special case for SCALAR and check for the ref to undef. I figure that it still behaves appropriately in most use cases, which is ugly, but there is little else that can be done. Of course if you do find a solution, please let me know :)

    -stvn
Re: Misbehaving typeglob
by diotalevi (Canon) on Oct 28, 2006 at 02:48 UTC

    Upgrade to bleadperl where SCALAR isn't autocreated. You can't avoid it on anything less than 5.9.3.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊