jb113 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Just wondering if I can define a subroutine that has two names. I'm writing a module that has an install and upgrade subroutine, but the install and upgrade is essentially the same thing, so I'd like to be able to call the same subroutine usng either install or upgrade.
sub install upgrade ($) { code here }
Can something like this be done?

Replies are listed 'Best First'.
Re: subroutine with two names
by BrowserUk (Patriarch) on Jan 20, 2010 at 01:42 UTC
    c:\test>perl use strict; use warnings; sub install{ print 'hi' } *upgrade = \*install; install(); upgrade(); ^Z hihi

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: subroutine with two names
by Marshall (Canon) on Jan 20, 2010 at 01:37 UTC
    I would just make:
    sub Install_or_Upgrade{....}
    and then:
    sub install { Install_or_Upgrade(); } sub upgrade { Install_or_Upgrade(); }
    If this "Installer" or "Upgrader" is in a module, you just export "install" and "upgrade" and nobody has to know that they do the same thing.

    Update: After awhile, if this is a significant application, the "Upgrader" will become a lot more complex than the "Installer".

      Thanks for the replies. The install_or_upgrade method will work well for me. Cheers.
Re: subroutine with two names
by cdarke (Prior) on Jan 20, 2010 at 08:46 UTC
    As a general principle a subroutine should only do one thing. Factor out the common code by all means, but I would still have two subroutines which call the common code. You will almost certainly be thankful for that later as the module develops.