Reputation: 4084
Perl noob here - i have the following script
if(substr($pc, 3,1)!=" "){
$newpc = substr($pc, 0, 4) . " " . substr($pc, 4);
}
It's designed to put a space in postcodes, for example NN141NJ
becomes NN14 1NJ
... however with postcodes such as NN102DE
it doesn't do anything, does Perl recognize " "
and "0"
as the same? How can I go about perl not ignoring strings with 0
as the fourth letter?
Upvotes: 2
Views: 141
Reputation: 2847
In Perl, this sort of string-bashing is usually done using regular expression operators.
So you might want to look at using m//
and/or s///
.
See "Regexp Quote-Like Operators" in the perlop documentation page, and also the whole perlretut documentation page.
Then again, if you are dealing with UK postcodes you might want to search for "Postcode" on CPAN or look at Geo::Postcode
Upvotes: 1
Reputation: 19309
It's because perl needs specification between string comparison and numeric comparison. You're using numeric comparison which would convert " " to a 0. Do this instead:
if(substr($pc, 3,1) ne " "){
$newpc = substr($pc, 0, 4) . " " . substr($pc, 4);
}
Upvotes: 3
Reputation: 12581
You are using the !=
operator when you want to be using the ne
(not-equal) operator. !=
is a numeric-only compare, while ne
is a string compare.
Upvotes: 3
Reputation: 7487
Use ne
instead of !=
. The latter is for numeric comparisons, in which both are 0
in your case. See perldoc perlop
Upvotes: 7