perlmodulesubroutine

Subroutine with same name in 2 different CPAN modules


I am getting this error when running perl:

[Thu Mar 16 00:24:23 2023] list_directory_1.cgi: Subroutine main::getcwd redefined at /usr/lib/cgi-bin/list_directory_1.cgi line 15.

I think it is coming from the fact that getcwd is defined in CPAN module Cwd and also in POSIX. How do I specify that this subroutine is to be taken from the Cwd module?


Solution

  • Indeed, both Cwd and POSIX export getcwd by default.

    $ perl -we'use Cwd; use POSIX;'
    Subroutine main::getcwd redefined at -e line 1.
    

    The solution is to only import the symbols you need.

    use Cwd      qw( abs_path );
    use POSIX    qw( strftime floor );
    use DateTime qw( );                  # Import nothing.
    

    If you consistently adopt this style of explicitly listing imports, you gain the benefit of being able to see the origin of subs at a glance.