Skip to content

Commit

Permalink
Implement alias() [github #23]
Browse files Browse the repository at this point in the history
  • Loading branch information
schwern committed Jun 14, 2009
1 parent 51c9184 commit 025e561
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
1 change: 1 addition & 0 deletions MANIFEST
Expand Up @@ -7,6 +7,7 @@ MANIFEST This list of files
MANIFEST.SKIP
META.yml
README
t/alias.t
t/autobox.t
t/autodie.t
t/CLASS.t
Expand Down
58 changes: 55 additions & 3 deletions lib/perl5i.pm
Expand Up @@ -5,6 +5,7 @@ use 5.010;
use strict;
use warnings;
use Module::Load;
use Carp;

our $VERSION = '20090502';

Expand Down Expand Up @@ -38,9 +39,59 @@ implement it yourself.
=head1 What it does
perl5i enables each of these modules. We'll provide a brief
description here, but you should look at each of their documentation
for full details.
perl5i enables each of these modules and adds/changes these functions.
We'll provide a brief description here, but you should look at each of
their documentation for full details.
=head2 alias()
alias( $name => $reference );
alias( $package, $name => $reference );
alias( @identifiers => $reference );
Assigns a $refrence a $name. For example...
alias foo => sub { 42 };
print foo(); # prints 42
It will also work on hash, array and scalar refs.
our %stuff;
alias stuff => \%some_other_hash;
Multiple @identifiers will be joined with '::' and used as the fully
qualified name for the alias.
my $class = "Some::Class";
my $name = "foo";
alias $class, $name => sub { 99 };
print Some::Class->foo; # prints 99
If the $name has no "::" in it, the current caller will be prepended.
This is basically a nicer way to say:
no strict 'refs';
*{$package . '::'. $name} = $reference;
=cut

sub alias {
croak "Not enough arguments given to alias()" unless @_ >= 2;

my $thing = pop @_;
croak "Last argument to alias() must be a reference" unless ref $thing;

my @name = @_;
unshift @name, (caller)[0] unless grep /::/, @name;

my $name = join "::", @name;

no strict 'refs';
*{$name} = $thing;
return;
}


=head2 Modern::Perl
Expand Down Expand Up @@ -179,6 +230,7 @@ sub import {
*{ $caller . '::gmtime' } = \&dt_gmtime;
*{ $caller . '::localtime' } = \&dt_localtime;
*{ $caller . '::time' } = \&dt_time;
*{ $caller . '::alias' } = \&alias;
}

# autodie needs a bit more convincing
Expand Down

0 comments on commit 025e561

Please sign in to comment.