15

So I have a file that in short has this problem...

#!/usr/bin/perl -w
package Foo;

use strict;
use POSIX;

...

sub remove {
  ...
}
...

and I get a get an error saying the subroutine remove has been redefined. I know the problem, there is a subroutine called remove in POSIX. However, I don't know how to handle it. How is this problem typically solved?

floogads
  • 271
  • 2
  • 4
  • 13

4 Answers4

27

The other way to suppress this warning is to put your subroutine redefinition inside a no warnings 'redefine' block:

{
    no warnings 'redefine';
    sub remove { ... }
}
mob
  • 117,087
  • 18
  • 149
  • 283
22

do this:

use POSIX ();

which will stop the export all default functionality of the POSIX module. You will then need to prefix all POSIX methods with POSIX:: such as:

POSIX::remove(filename)

for the POSIX remove function.

ennuikiller
  • 46,381
  • 14
  • 112
  • 137
  • Thanks. Is this conventional? – floogads Aug 29 '10 at 03:08
  • 1
    Yes, in general to avoid conflicting subroutine definitions its best to import nothing or only those subroutines you are sure will have unique names. – ennuikiller Aug 29 '10 at 03:17
  • 6
    @floogads, it's more usual to say `use POSIX qw(mkfifo modf);` where you explicitly list all the functions you want to import. That way, you don't have to use the `POSIX::` prefix all over, and you don't have to worry about conflicts with subroutine names in your program. – cjm Aug 29 '10 at 03:48
  • Does this work if `POSIX` was another script and not a Perl module ? Seems like it does not. – Jean Nov 11 '15 at 04:10
19

You can exclude certain symbols from being normally exported with the '!name' directive (see perldoc Exporter), e.g.:

#!/usr/bin/perl -w
package Foo;

use strict;
use POSIX '!remove';

...

sub remove {
  ...
}
...
Ether
  • 53,118
  • 13
  • 86
  • 159
-1

Subroutine XYZ redefined at line N [perl error]

You could wrap your routine in no warnings 'redefine' (which is lexically scoped):

no warnings 'redefine';

sub XYZ{

...
...

}

It worked for me!

Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
  • Welcome to StackOverflow: if you post code, XML or data samples, please highlight those lines in the text editor and click on the "code samples" button ( { } ) on the editor toolbar or using Ctrl+K on your keyboard to nicely format and syntax highlight it! – WhatsThePoint Sep 26 '18 at 10:06