To check if a string contains only alphabets in Perl, you can use regular expressions or iterate through each character and check if it is an alphabet using functions like grep
and lc
.
In this example,
grep
function to check if the string matches the pattern.contains_only_alphabets
to 1
, otherwise 0
.$str = 'Hello123';
$contains_only_alphabets = ($str =~ /^[A-Za-z]+$/) ? 1 : 0;
print 'String contains only alphabets: ', $contains_only_alphabets;
String contains only alphabets: 0
In this example,
$str
with a value of 'Hello123'
.split
and grep
functions.$contains_only_alphabets
to 0
and exit the loop.$str = 'Hello123';
@chars = split('', $str);
$contains_only_alphabets = 1;
foreach $char (@chars) {
if ($char !~ /^[A-Za-z]$/) {
$contains_only_alphabets = 0;
last;
}
}
print 'String contains only alphabets: ', $contains_only_alphabets;
String contains only alphabets: 0
In this tutorial, we learned How to Check if String contains only Alphabets in Perl language with well detailed examples.