In Perl, how can I check for the existence of Socket options without generating warnings?

≡放荡痞女 提交于 2019-12-23 12:50:04

问题


I'm checking for the existence and default values of various socket options using Perl.

#!/usr/bin/perl -w
use strict;
use Socket;

if (defined(SO_BROADCAST)) {
    print("SO_BROADCAST defined\n");
}

if (defined(SO_REUSEPORT)) {
    print("SO_REUSEPORT defined\n");
}

When I run this it outputs:

SO_BROADCAST defined

Your vendor has not defined Socket macro SO_REUSEPORT, used at ./checkopts.pl line 9

Is there a way to do this without generating warnings in the output?


回答1:


Ask whether the sub has been defined, not whether the expression's value is defined:

if (defined &SO_REUSEPORT) { ... }

The documentation for defined explains:

You may also use defined(&func) to check whether subroutine &func has ever been defined. The return value is unaffected by any forward declarations of &func. Note that a subroutine which is not defined may still be callable: its package may have an AUTOLOAD method that makes it spring into existence the first time that it is called—see perlsub.

If the sub is exported into your namespace, it has to be defined.




回答2:


That message is coming from AUTOLOAD in Socket.pm. When it finds a constant that isn't supported, it croaks. You can catch that with an eval:

 use Socket;

 if( defined eval { SO_REUSEPORT } ) {
      ...;
      }


来源:https://stackoverflow.com/questions/2216636/in-perl-how-can-i-check-for-the-existence-of-socket-options-without-generating

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