[sf-perl] Meaning of an asterisk (*)
garth.webb at gmail.com
Tue Feb 26 12:37:34 PST 2008
On Tue, Feb 26, 2008 at 11:59 AM, <nheller at silcon.com> wrote:
> I got a few questions about the following snippet of code.
> The questions follow the code.
> I appreciate any answers I can get.
> #! /usr/bin/perl
> use strict;
> use warnings;
> can_ok('SongPlayer', 'new');
> can_ok( $song, 'player');
> package SongPlayer;
> use subs 'system';
> package main;
> my $fail = 0;
> my @args;
> *SongPlayer::system = sub;
> @args = @_;
> return $fail;
> My questions:
> 1. What is the meaning of the line "use subs 'system';"?
Its to allow you to override Perl's built-in function names. In this
case to allow the code to override the 'system' function.
See 'man perlsub'
> 2. Why were two package statements used in the space of 3 lines?
You can use a package statement to change the code's context. Global
variables and subroutines are affected by the last package statement.
In this case its making sure that the 'system' function can be
overridden later in code. I'm not sure why it wasn't overridden while
still in the 'SongPlayer' context.
> 3. What is the meaning of the asterisk in this code?
Its called a typeglob, see 'man perldata'. It basically makes an
alias to the name given just after the asterisk to what its being
> 4. For that matter, what is the meaning of this entire line, and why are
> the lines below it set into a block by braces?
This is a bug. The code meant to define an anonymous subroutine that
does stuff (and then gets aliased as 'system' in the 'SongPlayer'
package), but the semicolon after 'sub' creates an empty anonymous
subroutine that does nothing, plus a section of code that will be run
at the end of the script (rather than when it gets called).
More information about the SanFrancisco-pm