user354134
user354134

Reputation:

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?

Upvotes: 18

Views: 8955

Answers (4)

ysth
ysth

Reputation: 98398

*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.

Upvotes: 12

DVK
DVK

Reputation: 129423

Courtesy Perlmonks:

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

BEGIN { *foo = \&bar; }

foo();
bar();

Upvotes: 6

Narveson
Narveson

Reputation: 1111

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";
bar_copy();
print "Executing bar_link:\n";
bar_link();

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

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

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\temp.pl line 19.
Executing bar_copy after redefinition:
This is the original bar().
Executing bar_link after redefinition:
This is bar(), redefined.

Upvotes: 16

mob
mob

Reputation: 118605

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)

Upvotes: 34

Related Questions