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 <url>
# 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.
The second hit on "open url" at search.cpan brings up Browser::Open:
use Browser::Open qw( open_browser );
my $url = 'http://www.google.com/';
open_browser($url);
If your OS isn't supported, send a patch or a bug report.
You can use $^O
variable to identify a platform and use different commands for each OS.
For example:
sub open_default_browser {
my $url = shift;
my $platform = $^O;
my $cmd;
if ($platform eq 'darwin') { $cmd = "open \"$url\""; } # Mac OS X
elsif ($platform eq 'linux') { $cmd = "x-www-browser \"$url\""; } # Linux
elsif ($platform eq 'MSWin32') { $cmd = "start $url"; } # Win95..Win7
if (defined $cmd) {
system($cmd);
} else {
die "Can't locate default browser";
}
}
open_default_browser("http://www.example.com/");