How do I launch the default web browser in Perl on any operating system?

前端 未结 3 457
再見小時候
再見小時候 2021-02-07 21:25

I want to open a URL, such as http://www.example.com/, at the end of a Perl script. I don\'t want to access it with WWW::Mechanize but actually show the web page to

3条回答
  •  伪装坚强ぢ
    2021-02-07 21:55

    If installing CPAN module Browser::Open is not an option or not desired, Taras' answer provides a good alternative, but can be improved in the following ways:

    • make the function work robustly on Windows with URLs that contain shell metacharacters such as & and ^.
    • on Windows, add support for the MSYS, Git Bash, and Cygwin Unix-emulation environments
    • add support for additional operating systems that also have the xdg-open utility, namely all OSs that are freedesktop.org-compatible, i.e., use GUIs that are X Window-based, which includes non-Linux platforms such as PC-BSD (FreeBSD-based) and OpenSolaris.
    # SYNOPSIS
    #   openurl 
    # DESCRIPTION
    #   Opens the specified URL in the system's default browser.
    # COMPATIBILITY
    #   OSX, Windows (including MSYS, Git Bash, and Cygwin), as well as Freedesktop-compliant
    #   OSs, which includes many Linux distros (e.g., Ubuntu), PC-BSD, OpenSolaris...
    sub openurl {
      my $url = shift;
      my $platform = $^O;
      my $cmd;
      if    ($platform eq 'darwin')  { $cmd = "open \"$url\"";       }  # OS X
      elsif ($platform eq 'MSWin32' or $platform eq 'msys') { $cmd = "start \"\" \"$url\""; } # Windows native or MSYS / Git Bash
      elsif ($platform eq 'cygwin')  { $cmd = "cmd.exe /c start \"\" \"$url \""; } # Cygwin; !! Note the required trailing space.
      else { $cmd = "xdg-open \"$url\""; }  # assume a Freedesktop-compliant OS, which includes many Linux distros, PC-BSD, OpenSolaris, ...
      if (system($cmd) != 0) {
        die "Cannot locate or failed to open default browser; please open '$url' manually.";
      }
    }
    

    Cygwin caveat: Bizarrely, the only way to protect the URL passed to cmd.exe from interpretation of chars. such as & and ^ is to append a trailing space. This works in all but one edge case, which, however, should be rare in the real world: if the URL contains something like %FOO% and an environment variable named FOO exists, %FOO% is inadvertently expanded.

提交回复
热议问题