in reply to Confused about typeglobs and references

Assigning a reference to a typeglob (not a reference to a typeglob!) populates the appropriate slot within the typeglob. For example, *a = []; populates something you can address as @a. If you're passing arguments to a function, what would happen if someone sent the wrong reference type? *a = {}; is very different.

Consequently, I think you're much better off working with references explicitly. Run-time symbol table manipulation is powerful, and one percent of the time it's absolutely necessary. I think this falls strongly within the remaining 99%.

Replies are listed 'Best First'.
Re: Confused about typeglobs and references
by Argel (Prior) on Nov 04, 2002 at 22:13 UTC
    Thanks for all the comments!

    Chromatic, you have me wondering if I should start using either prototypes or 'ref' to verify what reference I have. Otherwise, there seems to be little difference between the typeglob trick and using references -- if you assume you have an array you're still not going to catch the hash problem until runtime (perhaps you will get a more descriptive error message).

    Do many of you check the reference type? And is there a way to figure out what type of variable a typeglob is aliasing to?

      Prototypes won't really help here. All they do is coerce the passed arguments into what you're expecting. You still have to document the API carefully so people are enlightened as much as possible. (I almost never use them.)

      My point is that with using references directly, you'll get a better error message. If you're expecting an array reference and someone passes a hash reference, Perl will complain that you're doing arrayish operations on something that doesn't look like a hash. (If you're lucky, you won't get one of the obscure pseudohash errors...)

      I'm not sure what you mean by figure out what type of variable a typeglob is aliasing to. You can use defined and exists on the typeglob slot to see if something's there and usable, but that has other subtleties and optimizations.

      Checking the reference type with ref or UNIVERSAL::isa() is much better. It's much simpler.

      Don't use prototypes unless you can clearly explain why you're using them. Their only significant benefit in Perl is to change how you call a subroutine, but they are so filled with caveats and gotchas that they're easy to use incorrectly. Read this recent thread on prototypes for more info, particularly the short and accurate explanation by Dominus.

      As for using ref: I hate to say it, but I'd avoid that also. Take a look at code on this site that uses ref and you'll find that most (not all!) instances of it are indicative of some design flaw in the code.

      Cheers,
      Ovid

      Join the Perlmonks Setiathome Group.

      New address of my CGI Course.