Custom missing module message

浪子不回头ぞ 提交于 2019-12-02 09:19:35

问题


I would like to be able to output a custom error message to STDERR if one of my modules cannot be found.

From what I understand if I import the module with the use command the lack of the module will be discovered prior to my script being executed which poses a significant problem to achieving the result that I am looking for.

Basically what I am looking for is a Perl equivalent of catching the ImportError exception in Python.


回答1:


To catch an exception in Perl you should use the eval operator. If the code passed to eval dies, then the error message is put into $@ instead for you to use however you like.

It would look something like this

use strict;
use warnings;
use 5.010;

BEGIN {

  eval 'use Xyz';

  if ( $@ ) {
    if ( $@ =~ /Can't locate (\S+)/ ) {
      warn "$1 isn't installed";
    }
    else {
      die $@;
    }
  }
}

say 'Continuing...';

output

Xyz.pm isn't installed at E:\Perl\source\trap use.pl line 9.
Continuing...



回答2:


You can use an @INC hook to do this:

BEGIN { push @INC, sub { Carp::croak "Couldn't find $_[1]" } }
use Xyz;


来源:https://stackoverflow.com/questions/28444773/custom-missing-module-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!