Gossamer Forum
Home : General : Perl Programming :

A better way 2?

Quote Reply
A better way 2?
Is there a better way of doing the following?

Code:
use strict;

use CGI;
my $query = CGI->new();

#######################################################################################
#######################################################################################

my $referrer = $ENV{HTTP_REFERER};
my $goto = $referrer;

if ($referrer =~ m|/en/|g) {
$goto =~ s|/en/|/ws/|g;
}
elsif ($referrer =~ m|/ws/|g) {
$goto =~ s|/ws/|/en/|g;
}
else {
die("Can't understand what to translate to.");
}

print $query->redirect($goto);

- wil
Quote Reply
Re: [Wil] A better way 2? In reply to
Not necessarily better, I was just bored :)

Code:
#!/usr/bin/perl

use strict;
use CGI qw/:redirect/;

my $redir = sub {
my $rev = { en => 'ws', ws => 'en' };
my $ref;
($ref = $ENV{HTTP_REFERER}) =~ s,/(ws|en)/,/$rev->{$1}/,;
return $ref;
};

print redirect(&$redir);

Last edited by:

Paul: Apr 12, 2002, 6:15 AM
Quote Reply
Re: [Paul] A better way 2? In reply to
Hm. How does yours work? I don't understand it.

- wil
Quote Reply
Re: [Wil] A better way 2? In reply to
($ref = $ENV{HTTP_REFERER}) =~ s,/(ws|en)/,/$rev->{$1}/,;

...is just a quicker way of doing those 4 regexs you had :)

Or was there something else you didn't understand?

Last edited by:

Paul: Apr 12, 2002, 6:24 AM
Quote Reply
Re: [Paul] A better way 2? In reply to
Just curious as to how this bit works?

=~ s,/(ws|en)/,/$rev->{$1}/,;

- wil
Quote Reply
Re: [Wil] A better way 2? In reply to
Substitutes /en/ or /ws/ with $rev->{$1}

$1 will either be ws or en so it looks up the key in the $rev hashref and uses the opposite.

eg...referer is http://www.foo.com/en/index.html

The regex will match and $1 will equal "en" - "en"s value in the hash is "ws" so that gets inserted

Last edited by:

Paul: Apr 12, 2002, 6:33 AM
Quote Reply
Re: [Paul] A better way 2? In reply to
Hm. Clever. I've never seen it done like that before. I want to benchmark all these now :-)

- wil
Quote Reply
Re: [Wil] A better way 2? In reply to
Whats the betting mine turns out slower Laugh

It shouldn't though.