On Sep 29, [EMAIL PROTECTED] said:
>Since, everyone is so lively today, I'm going to push my luck today with
>this list. I need a little help here with validating a string to have only
>characters that I want, A-z and _ (underscore).
You'll want to use a regular expression, or perhaps just the tr///
operator.
>sub isValidChars
>{ my $retVal;
>
> @chars=split(//,$_[0]);
>
> for(@chars)
> {
> if($_ =~ /A-z/) { print "good [" . $_ . "]\n"; $retVal=1; }
First, you probably mean /[A-z]/. Second, you probably mean /[A-Za-z_]/.
Third, it's silly to do this character-by-character.
> else { print "bad [" . $_ . "]\n"; $retVal=0; break; }
"break" is spelled "last" in Perl.
> }
> return $retval;
>}
Here are a few variations:
sub isValidChars {
my $str = shift;
if ($str =~ /^[A-Za-z_]+$/) { return 1 }
else { return 0 }
}
which can be written as simply
sub isValidChars {
return shift =~ /^[A-Za-z_]+$/;
}
and, in fact, the 'return' isn't necessary:
sub isValidChars { shift =~ /^[A-Za-z_]+$/ }
Or you could do the opposite: make sure the string DOESN'T have any
ILLEGAL characters in it. The only problem with this is that an empty
string is considered valid. That's why this approach includes a length()
test.
sub isValidChars {
my $str = shift;
return length($str) and $str !~ /[^A-Za-z_]/;
}
That returns true if and only if $str is non-zero in length and DOES NOT
contain a NON-[A-Za-z_] character.
Another way to do it is with tr///.
sub isValidChars {
my $str = shift;
return length($str) and ($str =~ tr/A-Za-z_//c) == 0;
}
This time, we use length() again, but we use the tr/// operator, instead
of the m// operator. The tr/// takes a character class, basically, and
the /c modifier at the end means "take the opposite of this class". So
$str =~ tr/A-Za-z_//c is scanning $str for any NON-[A-Za-z_] characters.
tr/// returns the number of matching characters found. If the number of
non-[A-Za-z_] characters is zero, and the length isn't zero, then it's a
valid string.
Which method should you use? I'd probably use the simplest form of the
first isValidChars() I showed.
--
Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/
RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
<stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
[ I'm looking for programming work. If you like my work, let me know. ]
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]