Redirecting URL in Perl

pradeep's Avatar author of Redirecting URL in Perl
This is an article on Redirecting URL in Perl in Perl.
A very common technique used by many developers is to redirect the user to another URL or the referrer URL after doing some work e.g. processing a form. In Perl all headers have to printed before any actual content is outputed.

A very simple way of redirecting to another URL
Code: Perl
#!/usr/bin/perl

print "Content-Type: text/html\n";
print "Location: http://www.go4expert.com/no-page-here.html\n\n";

Doing the same thing using the CGI module.
Code: Perl
#!/usr/bin/perl

use CGI;

my $cgi = new CGI;

print $cgi->header(-location => q[http://www.go4expert.com/no-page-here.html]);

You may also pass the HTTP status code, sometimes it's needed e.g. if you pass a 302 status code, the URL of the page in the browser remains the same. Here's all the status codes used for redirecting a page.

Code:
301 Moved Permanently
302 Found
303 See Other
So, here's how we redirect with the status.
Code: Perl
#!/usr/bin/perl

use CGI;

my $cgi = new CGI;

print $cgi->header(-location => q[http://www.go4expert.com/no-page-here.html], -status=>301);
shabbir, sundeep.kumar likes this
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Nomination for article of the month for December 2008 Started.
0
dsouza's Avatar, Join Date: Jan 2009
Go4Expert Member
nice post
0
fazalca's Avatar, Join Date: Apr 2009
Newbie Member
print redirect('URL');

will do the same thing
sundeep.kumar like this