How can I detect the operating system in Perl?

后端 未结 11 1456
我在风中等你
我在风中等你 2020-12-04 16:41

I have Perl on Mac, Windows and Ubuntu. How can I tell from within the script which one is which? Thanks in advance.

Edit: I was asked what I am doi

相关标签:
11条回答
  • 2020-12-04 16:55

    FYI on Mac computers $^O now returns 'darwin' for 10.13.6 (High Sierra) and 10.15.4 (Catalina).

    0 讨论(0)
  • 2020-12-04 16:56

    A classic one-liner:

    my $windows=($^O=~/Win/)?1:0;# Are we running on windows?
    
    0 讨论(0)
  • 2020-12-04 16:58
    #Assign the $home_directory variable the path of the user's home directory
    my $home_directory = ($^O eq /Win/) ? $ENV{HOMEPATH} : $ENV{HOME};
    #Then you can read/write to files in the home directory
    open(FILE, ">$home_directory/my_tmp_file");
    print FILE "This is a test\n";
    close FILE;
    #And/or read the contents of the file
    open(FILE, "<$home_directory/my_tmp_file");
    while (<FILE>){
        print $_;
    }
    close FILE;
    
    0 讨论(0)
  • 2020-12-04 16:58

    For a generic mapping in a pre-packaged perl module, check out Perl::OSType.

    It's used by Module::Build.

    0 讨论(0)
  • 2020-12-04 16:59

    Here's a quick reference on how to find the OS the local machine is running from Perl.

    The $^O variable ($OSTYPE if you use English) contains the operating system that your perl binary was built for.

    0 讨论(0)
  • 2020-12-04 17:05

    If you need more specific information on Windows this may help.

    my $osname = $^O;
    
    
    if( $osname eq 'MSWin32' ){{
      eval { require Win32; } or last;
      $osname = Win32::GetOSName();
    
      # work around for historical reasons
      $osname = 'WinXP' if $osname =~ /^WinXP/;
    }}
    

    Derived from sysinfo.t, which I wrote the original version.

    If you need more detailed information:

    my ( $osvername, $major, $minor, $id ) = Win32::GetOSVersion();
    
    0 讨论(0)
提交回复
热议问题