Perl CGI script to find vowels in a String

This is another interesting Perl script which accepts a word or a sentence, basically a string and returns the number of vowels present in the string.

What all you will learn from this script?

1. Embedding HTML form in Perl script.
2. How to check a web form is submitted in Perl?
3. String to Lowercase.
4. Finding length of the string.
5. Array in Perl CGI
6. Converting a string into an array.
7. How to For loop in Perl?
8. Writing a custom function to search array values

The above said stuffs are very important in Perl CGI scripting, this program covers all of the above, so you are not only learning how to find vowels but also all other important functions in Perl.

Here is the entire script:

#!/usr/bin/perl -w
##these two lines are used to display errors on browser. If you don't want, you can remove these
use CGI;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
##error display ends
 
##below line is important if you want to display the result in browser
print "Content-type: text/html\n\n";

##HTML Part
print "<html>
<head><title>Perl CGI Script to find vowels in a string</title></head>
<body>
    <h3>Web Based Perl script to Find Vowels in a string - <a href='http://www.tutorialsmade.com/'>Tutorialsmade.com</a></h3>
	<form action='' method='post'>
        <label>Enter a word or sentence to check <label>
        <input type='text' name='string' />
        <input type='submit' value='Submit' />
    </form>
</body>
</html>";	
 
## here is the perl logic starts
my $q = new CGI;
## check if a form is submitted with $q->param()
if($q->param())
{
	$string = lc($q->param('string'));
	@vowels = ("a","e","i","o","u");
	$len = length($string);
    $num = 0;
 
    ##convert string to array 
	@strarr = split(//, $string);
	
    ##loop through each letter
	for($i=0; $i<$len; $i++){

		if(in_array(\@vowels, $strarr[$i]))
		{
			$num++;
		}
	}

	print "<p>Number of vowels : <span style='color:green; font-weight:bold;'>". $num ."</span></p>";
	##search array value
	sub in_array {
		 my ($arr,$search_for) = @_;
		 return grep {$search_for eq $_} @$arr;
	}
}
 

The code is self explanatory, read the comments in the script to understand it well.

Here is the live demo of this script:

demo

Enjoy learning. Good luck!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top