7

What's the Perl equivalent for the following PHP calls?

$_SERVER["HTTP_HOST"]
$_SERVER["REQUEST_URI"]

Any help would be much appreciated.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
dandemeyere
  • 341
  • 1
  • 4
  • 14

4 Answers4

14

Another way, than variable environement, is to use CGI :


use strict;
use warnings;
use CGI ;

print CGI->new->url();

Moreover, it also offers a lot of CGI manipulation such as accessing params send to your cgi, cookies etc...

benzebuth
  • 695
  • 3
  • 11
6

Environment variables are a series of hidden values that the web server sends to every CGI you run. Your CGI can parse them and use the data they send. Environment variables are stored in a hash called %ENV.

For example, $ENV{'HTTP_HOST'} will give the hostname of your server.

#!/usr/bin/perl

print "Content-type:text/html\n\n";
print <<EndOfHTML;
<html><head><title>Print Environment</title></head>
<body>
EndOfHTML

foreach my $key (sort(keys %ENV)) {
    print "$key = $ENV{$key}<br>\n";
}

print "</body></html>";

For more details see CGI Environmental variables

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Nikhil Jain
  • 8,232
  • 2
  • 25
  • 47
5

Or you can do this and use the variable $page_url.

my $page_url = 'http';
$page_url.='s' if $ENV{HTTPS};
$page_url.='://';
if($ENV{SERVER_PORT}!=80)
{
    $page_url.="$ENV{SERVER_NAME}:$ENV{SERVER_PORT}$ENV{REQUEST_URI}";
}
else
{
    $page_url.=$ENV{SERVER_NAME}.$ENV{REQUEST_URI};
}
ZzZombo
  • 1,082
  • 1
  • 11
  • 26
TechDex
  • 71
  • 1
  • 7
2

What's the environment you're working in? If it's CGI script try:

use Data::Dumper;
print Dumper \%ENV;
hlynur
  • 596
  • 2
  • 7
  • This worked great, thanks. Do you happen to know the Perl equivalent of the PHP function file_get_contents() as well? I've been playing around with open but can't get it to access a page on a different server the way file_get_contents() does. – dandemeyere Aug 05 '10 at 08:06
  • @dandemeyere: What I usually did was: open FILE, $data = join'', then close FILE – hlynur Aug 05 '10 at 08:15
  • hlynul's answer regarding file_get_contents is erroneous. dandemeyere asked (and had an answer for that question) at http://stackoverflow.com/questions/3413151 – Mark Fowler Aug 05 '10 at 10:33