Windows Perl Scripting Forums » Perl

How to exclude modules in a cross-platform script

(2 posts)

Tags:


  1. csburris
    Member

    I am writing a script (actually updating a script that already works on unix) and I need the Win32::OLE modules to emulate some functions (processinfo, etc) to make it run cross-platform. I'm trying to exclude the Win32 modules from being looked for.

    The following code does NOT work:

    print "OS=$^O\n";
    if ($^O eq 'MSWin32') {
    use Win32;
    use Win32::OLE qw(in);
    $Win32::OLE::Warn = 2; # Always warn with verbose error messages
    $strComputer = Win32::NodeName(); #hostname;
    }

    It tells me that the Win32:OLE module cannot be found in @INC - any ideas?
    Posted 12 years ago #
  2. Dave
    Perl guy

    The problem is that the "use" command executes before any of the script does. Therefore any inclusion/exclusion of libraries or modifcation of @INC should be performed in a BEGIN block. BEGIN blocks are executed before the rest of the script is (including before "use" commands are run).

    In your case it would be easiest to not use the "use" command. when you "use" a module what you are really doing is loading the module (which you can do using the "require" command) then the "import" command (to import whatever the module exports).
    Therefore the following two code blocks are functionally identical:

    use Win32::OLE qw( in );


    and

    BEGIN
    {
      require Win32::OLE;
      import Win32::OLE qw( in );
    }


    If you did this require/import in a BEGIN block then your code should work just fine. In your case you should do:

    BEGIN
    {
      if ($^O eq 'MSWin32')
      {
        require Win32;
        require Win32::OLE;
        import Win32::OLE qw( in );
        $Win32::OLE::Warn = 2;
        $strComputer = Win32::NodeName();
      }
    }
    #...begin script code here...

    Posted 12 years ago #

RSS feed for this topic

Reply

You must log in to post.