Subroutine with same name in 2 different CPAN modules
Asked Answered
M

2

6

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?

Madelainemadeleine answered 16/3, 2023 at 0:42 Comment(2)
I changed to: use Cwd qw(cwd); Is this correct? What do I need to change for POSIX if I am only using the seek function? How do you find out which symbols are available?Madelainemadeleine
use POSIX qw( seek );. Except seek is a builtin. No need to override the builtin seek with the one from POSIX.Webfooted
W
10

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.

Webfooted answered 16/3, 2023 at 0:52 Comment(0)
N
4

Besides what ikegami already shows, there's another way to go. Instead of importing, fully specify which one you want:

use Cwd ();  # import nothing

my $dir = Cwd::getcwd();

This can be helpful if people know that the function can come from different sources, but don't remember which one you chose.

Navada answered 16/3, 2023 at 11:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.