How to resolve 'constant flags' for Windows and Linux clients in Perl?
I am using following Linux and Windows perl libraries as given below -
Linux:
use Fcntl;
use File::FcntlLock
Windows:
use Win32::API;
use Win32API::File qw(:Func :Misc :FILE_:FILE_FLAG_ :FILE_SHARE_ :FILE_ATTRIBUTE_ :GENERIC_ )
So on the basis of the host(Linux or Windows) I am using to run the scripts, I am loading the package-
my $linux_packages = "use Fcntl; use File::FcntlLock; use File::Copy;1;";
my $window_packages
= "use Win32::API; use Win32API::File qw(:Func :Misc :FILE_ "
. ":FILE_FLAG_ :FILE_SHARE_ :FILE_ATTRIBUTE_ :GENERIC_ );1;";
if ( $Hosttype =~ /unix/ ) {
eval "$linux_开发者_运维知识库packages";
} elsif ( $Hosttype =~ /windows/ ) {
eval "$window_packages";
}
Now i am trying to use the flags from Linux or windows client , but if i run the script on Linux client it thrown the error for windows flags as
SCRIPT ERROR: Bareword "GENERIC_READ" not allowed while "strict subs" in use
And if quoted GENERIC_READ, it is used as string not as actual flag and via versa.
How to resolve?
You should factor out operating system specific bits of your own code into separate modules that present a unified interface, and then require
the appropriate module depending on operating system.
To do that, you can use Sys::Info::OS and require and import. Something along the lines of the following (untested) should work:
use strict; use warnings;
use Sys::Info::OS;
BEGIN {
my $os = Sys::Info::OS->new;
if ($os->is_windows) {
require Win32::API;
Win32::API->import;
require Win32API::File;
Win32API::File->import(qw(
:Func
:Misc
:FILE_
:FILE_FLAG_
:FILE_SHARE_
:FILE_ATTRIBUTE_
:GENERIC_
));
}
elsif ($os->is_linux) {
require Fcntl;
Fcntl->import;
require File::FcntlLock;
File::FcntlLock->import;
require File::Copy;
File::Copy->import;
}
else {
die sprintf "Unknown OS: %s\n", $os->name;
}
}
# rest of the code
精彩评论