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
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:
&
and ^
.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.