code help

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
samip1983
Forum Newbie
Posts: 7
Joined: Thu Jul 28, 2005 9:57 am

code help

Post by samip1983 »

Hi all,

I have the following code, used to manipulate the postcode entered depending on the format. U = uppercase, L = Lowercase, NS = No space, and SP = a space in correct place.

Code: Select all

#!/usr/bin/perl
use strict;
use CGI ':standard';

my ($postcode, $format);

print "Content-type: text/html\n\n";

$postcode = param('postcode');
$format = param('format');

if ($postcode =~ /\D{2}\d{1,2}\s*\d\D{2}/)
{
if ($format =~ /U/)
{
$postcode = uc($postcode);
print "$postcode\n";
}
elsif ($format =~ /L/)
{
$postcode = lc($postcode);
print "$postcode\n";
}
elsif (($format =~ /ns/) or ($format =~ /NS/))
{
$postcode =~ s/\s//g;
print "$postcode\n";
}
elsif (($format =~ /sp/) or ($format =~ /SP/))
{
$postcode =~ s/\s//g; #clear out spaces
my $postcodergt = substr($postcode,-3);
my $postcodelft = substr($postcode,0,-3);
$postcode = $postcodelft." ".$postcodergt;
print "$postcode\n";
}
else
{
print "Invalid Data";
}
}
else
{
print "invalid data\n";
}

The problem is, when no format is entered i need the $postcode entered to be outputed as it is. Also if the NS or SP formats are not used, and a space is in a different position i.e (GH16S Y). I need the space to be in the proper position i.e (GH1 6SY).

Any help would be great, Thanks

Sami P
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Again, you should not be using =~ /L/ to match a single letter L... that matches anything containing the letter L (such as Lisa, or Louise, or Leiticia, or Laura 8O). Use eq instead in perl ;)

Code: Select all

if ($string eq "L")
{
    //Code here
}
I'll take a look at your code but my perl is somewhat rusty so you may be better on a perl forum than a php one ;)
Post Reply