1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

レガシーなPerlスクリプトのrequireで起こる関数の衝突事故を回避する

Last updated at Posted at 2016-04-08

いわゆるバッドノウハウ。
同じ関数が書かれた.plファイルをそれぞれ呼び出す方法。

lib1.pl
# !/usr/bin/perl
use strict;
sub test1 {
  print "lib1 call test1\n";
}
1;
lib2.pl
# !/usr/bin/perl
use strict;
sub test1 {
  print "lib2 new call test1\n";
}
1;
old/lib2.pl
# !/usr/bin/perl
use strict;
sub test1 {
  print "lib2 old call test1\n";
}
1;

そのままrequireすると上書きされてしまう

use strict;
use warnings;
use lib ".";
require "lib1.pl";
require "lib2.pl";
require "old/lib2.pl";

test1();
___END___
lib2 old call test1

名前空間を分けて呼び出す

a.pl
use strict;
use warnings;
use lib ".";

Lib1->test1();
Lib2New->test1();
Lib2Old->test1();

BEGIN {
  package Lib1;
  do "lib1.pl";
  package Lib2New;
  do "lib2.pl";
  package Lib2Old;
  do "old/lib2.pl";
}
__END__
lib1 call test1
lib2 new call test1
lib2 old call test1
  • requireでなく、doにしているのは、requireは同じ名前で呼ばれると2回目は読み込みされないため。(上記のパターンではrequireでも読み込みされた)

他の手

p.pl
use strict;
use warnings;

sub _hello {
        print "hello [@_]\n";
}
1;
r.pl
use strict;
use warnings;
{
  package p;
  require "p.pl";
  sub hello {
    my $self = shift;
    return _hello(@_);
  }
}
p->hello("argment");
$ perl r.pl
hello [argment]

他の手その2

p.pl
use strict;
use warnings;

sub hello {
        print "hello [@_]\n";
}
1;
r.pl
use strict;
use warnings;
{
  package p;
  require "p.pl";
}
p::hello("argment");

参考

型グロブとシンボリックリファレンスでメソッド定義するときの注意点 - Unknown::Programming
http://d.hatena.ne.jp/fbis/20060602/1149228989

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?