Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Use of Typeglob

by murugu (Curate)
on Aug 09, 2005 at 13:51 UTC ( #482211=perlquestion: print w/replies, xml ) Need Help??
murugu has asked for the wisdom of the Perl Monks concerning the following question:

Hi Esteemed Monks,

Please suggest me what is the real use of typeglob. I read it somewhere that they are used to create 'alias' for variables and also used in passing filehandles to subroutines as arguments. Kindly suggest me with any practical example depicting the use of typeglobs.

As always million thanks in advance.....

Regards,
Murugesan Kandasamy.

Update: Sorry monks... My intention was to ask what are all the advantages of using typeglobs. I already know the examples given by ikegami(i.e use of typeglob such as passing filehandles, aliasing variables).... sorry for the way i have written my question.

Replies are listed 'Best First'.
Re: Use of Typeglob
by ikegami (Pope) on Aug 09, 2005 at 14:00 UTC

    Example one:

    open(FILE, '>', 'temp.txt') or die("Can't create output file: $!"); greet(*FILE); sub greet { my ($fh) = @_; print $fh "Hello World\n"; }

    Example two:

    sub foo { print("Hello World\n"); } *bar = \&foo; bar();

    Most scripts don't use typeglobs. They just reap the benefits of very special modules which use them. For example, Exporter and constant might use typeglobs to import the symbols into the caller's namespace.

    The top example can be rewritten without typeglobs. It's safer without them.

    open(my $file, '>', 'temp.txt') or die("Can't create output file: $!"); greet($file); sub greet { my ($fh) = @_; print $fh "Hello World\n"; }

    Note how greet didn't change? Where file handles are concerned, typeglobs, ref to typeglobs and IO::Handle objects are almost always interchangable.

Re: Use of Typeglob
by ikegami (Pope) on Aug 09, 2005 at 14:40 UTC

    Answer to udpated question:

    When used as a file handle:

    • Pro: Lexicals can't be localized (but they can be block scoped).
    • Con: Typeglobs can't be blocked scoped (but they can be localized).
    • Pro: open LEXICAL, ... requires 5.6 or greater.
    • Con: The name isn't checked at run-time, so typos are harder to find. However, you will get a compile-time warning if the typo isn't repeated or pasted. For example,
      perl -Mstrict -w -e "my $fh = *STDOOUT; print $fh 'moo'"

    When used as a tied file handle:

    • I think you have no choice but to use a typeglob if you want a tied file handle.

    When used to alias function:

    • There's no other way without using eval EXPR.

    When used to alias other things:

    • There's no other way.
      When used as a tied file handle:
      • I think you have no choice but to use a typeglob if you want a tied file handle.
      As of 5.8.0, filehandle ties are attached to the IO handle, not the typeglob, so you can tie even globless lexical filehandles:
      use Tie::Handle; use Symbol "geniosym"; my $fh = geniosym; tie *$fh, "Tie::StdHandle" or die; print tied(*$fh);
      The * is required only to let tie/tied know you want a filehandle tie, not a scalar tie; no actual typeglobs are used, except temporarily.
Re: Use of Typeglob
by Tanktalus (Canon) on Aug 09, 2005 at 14:45 UTC

    To answer the update - the only time I use typeglobs is when I've chosen a bad name for a function, and want to deprecate it. I'll rename the function, and create the aliased function:

    our *old_name = \&new_name;
    Or, if I need to "inherit" a function from another module that isn't actually in my @ISA:
    our *some_func = \&Other::Module::some_func;
    I've done this in cases where this module should be inheriting from Other::Module, but it isn't, yet. It allows me to use some of the advanced features of the new base class without having to use all the features. It can be tricky to do in general, so I have to pick and choose the cases where it will work. When it does, however, it really makes it easier in the future to switch base classes as I'm already part-way there.

Re: Use of Typeglob
by dsb (Chaplain) on Aug 10, 2005 at 02:29 UTC
    Seems like several of the previous posters used a typeglob to have a passable version of a filehandle. By passable, I mean that the filehandle can be passed into a function or placed in some other list form like an array.

    In Seven Useful Uses of local, Tachyon demonstrates a pretty neat way of accomplishing just that.

    my $filehandle = do { local *FH };
    Tachyon's explanation:
    do just introduces a block which will be evaluated, and will return the value of the last expression that it contains, which in this case is local *FH. The value of local *FH is a glob. But what glob?

    local takes the existing FH glob and temporarily replaces it with a new glob. But then it immediately goes out of scope and puts the old glob back, leaving the new glob without a name. But then it returns the new, nameless glob, which is then stored into $filehandle. This is just what we wanted: A glob that has been disconnected from the symbol table.


    dsb
    This @ISA my cool %SIG
Re: Use of Typeglob
by Transient (Hermit) on Aug 09, 2005 at 14:00 UTC
    #!/usr/bin/perl -w use strict; local *FILE; open( FILE, ">log.txt" ) or die "Unable to open log!\n$!\n"; sub print_log { my $fh = shift; my $message = shift; print $fh $message; } &print_log( *FILE, "Hello!\n" ); print FILE "All done!\n"; close FILE or die "Unable to properly close log!\n$!\n";
    This is just an example way to use it. I personally don't use them much, but it has come in handy, especially with formats.
Re: Use of Typeglob
by BrowserUk (Pope) on Aug 09, 2005 at 15:01 UTC

    Maybe Re: Simple Pass By Reference is what you are alluding to?


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://482211]
Approved by mattriff
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (8)
As of 2017-12-14 19:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (408 votes). Check out past polls.

    Notices?