Aliasing a function in Perl

In Perl, if I want foo() to do exactly what bar() does, I can do this:

sub foo {return bar(@_);} 

Is there a better way? Something closer to Ruby's "alias" operator?


The A better way, employed by Exporter and similar modules, is to edit your symbol table:

*foo = \&bar;

(edited because this is Perl we are talking about)

There is another way to do it:

sub foo {goto &bar}

This preserves the equivalence between foo and bar even if bar is subsequently redefined.

Here is a detailed demo:

use strict;
use warnings;

sub bar {
    print "This is the original bar().\n";

*bar_copy = \&bar;

sub bar_link {
    goto &bar;

print "Executing bar_copy:\n";
print "Executing bar_link:\n";

*bar = sub {print "This is bar(), redefined.\n"};

print "Executing bar_copy after redefinition:\n";
print "Executing bar_link after redefinition:\n";

which prints

Executing bar_copy:
This is the original bar().
Executing bar_link:
This is the original bar().
Subroutine main::bar redefined at C:\scripts\ line 19.
Executing bar_copy after redefinition:
This is the original bar().
Executing bar_link after redefinition:
This is bar(), redefined.

*foo = \&bar;

Assigning a reference to a glob replaces that portion of the glob with the thingy referred to. So this makes &foo exactly the same as &bar.

*foo = *bar;  # or \*bar

This also works, but also aliases the scalar, array, hash, filehandle, and format between foo and bar.

Courtesy Perlmonks:

sub bar { print( "Hello World\n" ); }

BEGIN { *foo = \&bar; }


Need Your Help

How can I allow django admin to set a field to NULL?

python mysql sql django django-admin

I've set my Model field to null=True, which allows NULL in MySQL, but I can't seem to assign NULL to the field through Django Admin. I've tried also setting blank=True, but that just sets the field...